与 Python 的串行通信
如果你将 Arduino 连接到计算机或 Raspberry Pi,并且想要将数据从 Arduino 发送到 PC,你可以执行以下操作:
Arduino
void setup() {
// Opens serial port, sets data rate to 9600 bps:
Serial.begin(9600);
}
void loop() {
// Sends a line over serial:
Serial.println("Hello, Python!");
delay(1000);
}
Python:
import serial
ser = serial.Serial('/dev/ttyACM0', 9600) # Start serial communication
while True:
data = ser.readline() # Wait for line from Arduino and read it
print("Received: '{}'".format(data)) # Print the line to the console