0

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?

1
  • 2
    Perhaps your python script should send 1 and enter. Commented Sep 24, 2021 at 15:29

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

btw, I don't think that 115200 is enormous if the setup is using a usb serial port.
@quamrana: Yes, but it's unnecessarily large for something like this. This isn't doing large data transfers or something like that; it's just controlling an LED. There will be hardly any difference in speed changing it from 115200 to 9600, in this case. It's good to eliminate all possible causes of the problem.
Well, yes, at the very least they can start by changing down to 9600 to get it working and change back up again to see if that helped or not. Anyway its currently down to the data content of the message. We await the OP.
ultimately it wasn't the baud rate, it was the bytes("1", "utf-8") that fixed it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.