我对硬件相当陌生。我想用NodeMCU和Python来控制LED灯。我用nodeMCU上传了一段Arduino代码,然后使用pyserial库来获得串行输出。但是当我尝试向端口提供输入时,它不起作用。我不知道问题出在哪里。
以下是arduino代码:
int inputVal = 0;
const int ledPin = 5; //D1 pin of NodeMCU
void setup() {
Serial.begin(9600);
delay(100);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, 0);
}
void loop() {
while(Serial.available()>0){
inputVal = Serial.read();
}
Serial.println(inputVal);
if(inputVal==1){
digitalWrite(ledPin, HIGH);
Serial.println("LED is ON");
}
else{
digitalWrite(ledPin, LOW);
Serial.println("LED is OFF");
}
Serial.println("");
}以下是python代码:
import serial
global ser
ser = serial.Serial("COM8", baudrate=9600, timeout=10,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
while(True):
ser.write(bytes(1))
line = ser.readline()
print(line.decode('utf8'))python的输出结果是:
0
LED is OFF
0
LED is OFF
0
LED is OFF诸若此类。ser.write()函数没有将串行端口上的值写为1。当我更改Arduino代码中的inputVal的值时,发光二极管亮起,并且arduino串行监视器上的输出显示为1 LED is ON,这意味着电路连接和Arduino代码工作正常。
我还注意到,我正在使用的COM端口可以同时与python或arduino一起工作。使用inputVal=1上传arduino代码后,指示灯亮起,arduino串行监视器开始显示(1个指示灯亮起)。但是,我一运行python代码,led就熄灭了,python的输出结果是0 LED is OFF。请帮帮我。
还有,有没有办法完全用python来控制NodeMCU,而不用先用arduino代码?
发布于 2021-05-23 20:09:03
python的输出是正确的。bytes(integer)创建一个给定大小的数组,在size = 1,bytes(1)的情况下,所有数组都初始化为null,因此,如果您尝试bytes(10),则输出将为b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'。
您需要做的是将ser.write(bytes(1))更改为ser.write(bytes('1',encoding= 'utf-8')),这样就可以工作了
https://stackoverflow.com/questions/67659358
复制相似问题