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 :
ser.write(f"b'myString'")
didn’t work…
- the
.format()
method (neither did it work)
- 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'```
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"))
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 :
ser.write(f"b'myString'")
didn’t work…- the
.format()
method (neither did it work) - 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'```
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"))