繁体   English   中英

Python serial.write() 不适用于 NodeMCU

[英]Python serial.write() not working for NodeMCU

我对硬件相当陌生。 我想使用 NodeMCU 和 Python 控制 LED 灯。 我在 nodeMCU 中上传了一个 Arduino 代码,然后使用 pyserial 库获取串行 output。 但是当我尝试向端口提供输入时,它不起作用。 我不知道问题出在哪里。

这是 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 中的 output 出来是:

0
LED is OFF

0
LED is OFF

0
LED is OFF

等等。 ser.write() function 没有在串行端口上将值写入 1。 When I change the value of inputVal in Arduino code, the LED turns on and the output on arduino serial monitor comes as 1 LED is ON , which implies that the circuit connection and Arduino code is working fine.

我还注意到我正在使用的 COM 端口一次可以与 python 或 arduino 一起使用。 在使用inputVal=1上传 arduino 代码后,LED 亮起,arduino 串行监视器开始显示(1 个 LED 亮起)。 但是,一旦我运行 python 代码,LED 就关闭了,python output 出来是0 LED is OFF 请帮我。

另外,有没有办法让我完全通过 python 控制 NodeMCU,而不先使用 arduino 代码?

来自 python 的 output 是正确的。 bytes(integer)创建一个提供大小的数组,在你的情况下全部初始化为 null size = 1, bytes(1) ,所以如果你尝试bytes(10) ,你拥有的 output 是0x00输出将是b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

您需要做的是将ser.write(bytes(1))更改为ser.write(bytes('1',encoding= 'utf-8'))应该可以工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM