PC-Arduino Serial communication
介绍
记录最简单的用python和Arduino实现异步通信的方法, 通过使用python serial 模块让Arduino 的build-in LED实现开关
PC: python serial 程序
import serial
import serial.tools.list_ports, warnings
#port detection - start
ports = [
p.device
for p in serial.tools.list_ports.comports()
# if 'USB' in p.description
]
print (ports)
if len(ports) > 1:
warnings.warn('Connected ...')
ser = serial.Serial(ports[0],9600) # to connect the first ports
while 1:
val = input("Enter 0 or 1 to control the LED:")
ser.write(val.encode())
Arduino代码
void setup() {
// put your setup code here, to run once:
Serial.begin(9600); // set the baud rate of 9600 bps
Serial.println("Ready"); // print "Ready" once
pinMode (13, OUTPUT); // configure the on-board LED as output
}
void loop() {
// put your main code here, to run repeatedly:
if (Serial.available())// if the receiver is full
{
switch (Serial.read())
{
case '0': digitalWrite(13, LOW);
break;
case '1': digitalWrite(13, HIGH);
break;
default: break;
}
delay(1); // delay for 0.1 second for each loop
}
}