Search code examples
pythonarduinopycharmesp8266serial-communication

How to establish serial communication between ESP8266 and Python


I followed this guide to try and learn serial communication but the code does not seem to work properly.

#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()

The only things I've changed are the pin number and the COM port.

When I run both the Arduino code and the Python code, I'm able to see output from the Python side but the Arduino code isn't outputting anything into the Python terminal. I'm not receiving any error messages either so I don't know what the cause could be.

If it's important, I'm using PyCharm as the python editor and the Arduino IDE for the ESP8266.


Solution

  • Your Arduino code is setting the speed of the serial line to 9600.

      Serial.begin(9600);
    

    Your Python code is setting it to 115200.

    serialcomm = serial.Serial('COM3', 115200)
    

    You need to choose one and be consistent. Try changing your Python code to use 9600.