python serial library issue with ser.write() command

Question:

I am looking for a solution to combine a string of integers(let’s say, ‘0000’ and ‘1000’ for example). But I need to encode to bytes anything that is sent through ser.write() with the b attribute that goes next to the string I want to send, which will give something like :
ser.write(b'0000')if I want to send 0000

Now , I want to add a for loop that changes each time the integers that will be sent, but I can’t figure out how to add a string variable with the ser.write() command AND the b at the begining.

What I would like to achieve is something like

ser.write(myString encoded in bytes)

Thanks for your help !

I looked at other similar posts, and tried such things as :

  1. ser.write(f"b'myString'")didn’t work…
  2. the .format() method (neither did it work)
  3. And the %-formatting method (also get an error)

Here are the errors I get when I try one of these 3 methods :

TypeError: unicode strings are not supported, please encode to bytes: '1111101000'```
Asked By: chipmunktunic

||

Answers:

Assuming the device on the other end of the line wants text encoded as UTF-8 bytes, .encode() it (as the error says):

ser.write(f"hëllo world".encode("utf-8"))

IOW, for a loop, you might do

for x in range(100):
    ser.write(f"{x:04d}".encode("utf-8"))
Answered By: AKX
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.