问题描述
我跟随this guide尝试学习串行通信,但是代码似乎无法正常工作。
#Arduino Code
String InBytes;
void setup() {
// put your setup code here,to run once:
Serial.begin(9600);
pinMode(4,OUTPUT);
}
void loop() {
// put your main code here,to run repeatedly:
if (Serial.available() > 0) {
InBytes = Serial.readStringUntil('\n');
if (InBytes == "on") {
digitalWrite(4,HIGH);
Serial.write("LED ON");
}
if (InBytes == "off") {
digitalWrite(LED_BUILTIN,LOW);
Serial.write("LED OFF");
}
else {
Serial.write("invalid information");
}
}
}
#Python Code
import serial
import time
serialcomm = serial.Serial('COM3',115200)
serialcomm.timeout = 1
def main():
while True:
i = input("input(on/off): ").strip()
if i == 'done':
print('finished program')
break
serialcomm.write(i.encode())
time.sleep(0.5)
print(serialcomm.readline().decode('ascii'))
serialcomm.close()
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
main()
我唯一更改的是引脚号和COM端口。
同时运行Arduino代码和Python代码时,我能够从Python端看到输出,但是Arduino代码没有向Python终端输出任何内容。我也没有收到任何错误消息,所以我也不知道是什么原因。
如果很重要,我使用PyCharm作为ESP8266的python编辑器和Arduino IDE。
解决方法
您的Arduino代码将串行线的速度设置为9600。
Serial.begin(9600);
您的Python代码将其设置为115200。
serialcomm = serial.Serial('COM3',115200)
您需要选择一个并保持一致。尝试更改您的Python代码以使用9600。