Search code examples
pythonarduinopyserial

sending serial data to arduino works in serial monitor, but not in python


I'm trying to flip a single bit on my arduino from 0 to 1 via python script. The following arduino code works great to turn on an LED if I type 1 into the serial monitor and hit enter:

int x;

void setup() {
  // this code proves that the LED is working
  digitalWrite(7, HIGH);
  delay(300);
  digitalWrite(7, LOW);
  Serial.begin(115200);
}

void loop() {
  Serial.print(x);
  if(Serial.available()){
    x = Serial.parseInt();
    // if x is anything other than 0, turn the LED on
    if (x){
      digitalWrite(7, HIGH);
    }
  }
}

but when I try to use this python script, the variable x presumably stays 0 because the LED isn't turning on:

import serial
import time
arduino = serial.Serial(port='COM3', baudrate=115200, timeout=5)
time.sleep(5)
print(arduino.read())
arduino.write(b"\x01")
print(arduino.read())
arduino.close()

I put the two print statements in to try to figure out what was happening, but I can't make sense of the output. Usually it's

b'0'
b'0'

but sometimes it's

b'0'
b''

or if I run the script right after plugging the arduino in it's:

b'\x10'
b'\x02'

or some other random number. What am I doing wrong here?


Solution

  • Using bytes("1", "<encoding>") instead of b"\x01" might work, where encoding is the encoding of your python file (like utf-8), although I'm not sure what the difference is.

    Another possible error cause: your baud rate is enormous. For something as simple as this, you don't need such a huge baud; using the standard 9600 will work fine. Try changing the baud and see if that helps.