aa develop

開発と成長

PythonからArduinoにシリアル通信でデータを送る

Pythonからシリアル通信でArduinoにデータを送り、LEDの明るさを制御する。 Arduinoには、D13とGRDにLEDを接続する。

Pythonでのシリアル通信には、pySerialライブラリが必要。

$ pip install pyserial

以下、コード。 PythonからArduinoに数値を送るときは、chr()で変換する。

Arduino


int v = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(13, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(Serial.available() > 0){
    v = Serial.read();
  }
  int ms = map(v, 0, 255, 0, 10);
  digitalWrite(13, HIGH);
  delay(10 - ms);
  digitalWrite(13, LOW);
  delay(ms);
}

Python


#! -*- coding: utf-8 -*-

import serial
import time

ser = serial.Serial('/dev/tty.usbmodem1411', 9600)

v = 0
vc = 1

while True:
    v += vc
    if v > 255:
        v = 0
    print v
    ser.write(chr(v))

    time.sleep(0.02)