簡體   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