Search code examples
pythonarduinoserial-portpyserialnodemcu

Python serial.write() not working for NodeMCU


I am fairly new to hardware. I want to control an LED light using NodeMCU and Python. I uploaded an Arduino code in nodeMCU and then used pyserial library to get the serial output. But when I try to give input to the port, it doesn't work. I don't know where the problem is.

Here is the arduino code:

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("");
}

Here is the python code:

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'))

The output in python comes out to be:

0
LED is OFF

0
LED is OFF

0
LED is OFF

and so on. The ser.write() function isn't writing the value as 1 on the serial port. 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.

I also noticed that the COM port that I am using can work with either python or arduino at a time. After uploading the arduino code with inputVal=1, the LED turned on and arduino serial monitor started displaying (1 LED is ON). But, as soon as I ran the python code, the led turned off and the python output came out to be 0 LED is OFF. Please help me.

Also, is there a way for me to control NodeMCU totally by python, without using arduino code first?


Solution

  • the output from python is correct. bytes(integer) creates an array of provided size, all initialized to null in your case size = 1, bytes(1), so the output that you have is 0x00 if you try bytes(10) the out put will be b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'.

    what you need to do is to change ser.write(bytes(1)) to ser.write(bytes('1',encoding= 'utf-8')) that should work