Search code examples
pythonencodingarduinoraspberry-piserial-communication

How to encode a string variable correctly to send it to Arduino via serial?


I want to send value of a variable via serial from RaspberryPi to Arduino Uno. if I type as :

ser.write(b'RED')

I can read it as RED on Arduino serial monitor. But if I type as:

color = "GREEN"
ser.write(color)

or

ser.write(color.encoding('utf-8'))

then I can't see anything. What should I do to send a string using variable? Python and pyserial library running o Raspberry.


Solution

  • ser.write(b'RED') is doing the same as ser.write('RED'.encode()) so you are casting a string to its bytes equivalent then sending it to the Arduino.

    color = 'GREEN' (what I assume you meant since GREEN is otherwise undefined) is not doing any conversion so you are sending a string literal with ser.write(color)

    ser.write(color.encode()) should do what you want