arduino使用USB串口通信
示例代码:
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()) { // 如果有数据可用 char c = Serial.read(); // 读取数据 if (c == 'a'){ digitalWrite(13, HIGH); } else{ digitalWrite(13, LOW); } Serial.write(c); // 将数据发送回计算机 } }
arduino连接:
只需要把你的LED灯正极(长的那端)插在13号接头、负极接在GND端即可测试。
Python进行串口通信
示例代码(和上面匹配):
import serial import time import serial # 打开串口 ser = serial.Serial('COM5', 9600) # 将'COM3'替换为您的串口名称 # 发送字符串 time.sleep(2) # 等待连接稳定 ser.write(b'a') # 将要发送的字符串作为字节序列传递给write()函数 print(ser.read()) time.sleep(3) ser.write(b'v') print(ser.read()) # 关闭串口 ser.close()
之所以要等待2秒,是因为测试发现,如果不等待(2s),就不能正常发送和读到结果
实验现象
可以看到LED灯按照Python的代码,亮起了,过了3秒后又熄灭了。