我试图用串行方式点亮arduino nano上的一个LED。 它可以与IDE中的串行监视器一起使用。当我使用python代码时,它会亮起并立即关闭。
arduino代码: '''
int ledPin = 13;
void setup()
{
//Create Serial Object
Serial.begin(9600);
Serial.println("<Arduino is ready>");
pinMode(ledPin, OUTPUT);
}
void loop()
{
//Have the arduino wait to receive input
while (Serial.available() == 0);
// while (Serial.available());
//Read the Input
int val = Serial.read(); - '0';
Serial.println(val);
if (val == 1)
{
Serial.println("Led is On");
digitalWrite(ledPin, HIGH);
}
else if (val == 0)
{
Serial.println("Led is Off");
digitalWrite(ledPin, LOW);
}
else
{
Serial.println("Invalid!");
}
Serial.flush();
}
''' Python代码:
import serial
ser = serial.Serial('/dev/serial/by-id/usb-1a86_USB2.0-Serial-if00-port0', 9600)
print(ser.name)
ser.write([1])
ser.close()