Adrunio-LED控制

时间:2017-05-10 10:13:01

标签: python arduino

我试图编写一个代码来闪烁LED 3次,这是从Python连接到Arduino。我能够这样做,但即使在python代码停止运行后,LED仍然闪烁。附上代码,有任何建议吗?

Python代码

import serial #import the pyserial library
connected = False #this will represent whether or not ardunio is connected to the system
ser = serial.Serial("COM3",9600) #open the serial port on which Ardunio is connected to, this will coommunicate to the serial port where ardunio is connected, the number which is there is called baud rate, this will provide the speed at which the communication happens
while not connected: #you have to loop until the ardunio gets ready, now when the ardunio gets ready, blink the led in the ardunio
    serin = ser.read()
    connected = True
    ser.write('1') #this will blink the led in the ardunio
    while ser.read() == '1': #now once the led blinks, the ardunio gets    message back from the serial port and it get freed from the loop!
ser.read()
ser.close()

Ardunio代码

void setup() {
 Serial.begin(9600);
 pinMode(10,OUTPUT);
 Serial.write('1');
}
void loop() {
if(Serial.available()>0){
  digitalWrite(10,HIGH);
  delay(500);
  digitalWrite(10,LOW);
  delay(500);
  digitalWrite(10,HIGH);
  delay(500);
  digitalWrite(10,LOW);
  delay(500);
  digitalWrite(10,HIGH);
  delay(500);
  digitalWrite(10,LOW);
  Serial.write('0');

}  }

1 个答案:

答案 0 :(得分:2)

Serial.available()的条件始终为真,因为始终存在(相同的旧)数据。您需要读取数据以将其从缓冲区中删除。