Python Serial write function not working Python Serial write function not working python-3.x python-3.x

Python Serial write function not working


import serialcheck=serial.Serial(1)check.write(b"test")

Previous versions of Python did a lot of the string to bytes conversion for you (personally I liked the old methods quite a lot). Nowadays, in Python3+ you need to handle the data-type conversion yourself depending on your output/input, which makes more sense even though I hate it...

This goes for sockets and numerous other objects as well.
So in order to send data via serial or sockets, all you need to do is convert your string into a bytes object. Do this by declaring b"this is bytes" or bytes(MyString, 'UTF-8').

For instance:

import serialcheck=serial.Serial(1)data = "test"check.write(bytes(data, 'UTF-8'))

When the machine (your pc) is working with data on lower levels (serial, sockets etc) it's used to working with binary code, that's the 01010101 you might have heard of.
But you're used to working with strings such as "Hello world".There's a middle layer in between, which is closer to machine code but still usable and understandable by us humans, and that's byte object.

a -> 97 -> 01100001

Previously (as mentioned) python converted your a into 97 for you in order to prep it for the driver that handles the machine-code. This caused a lot of problems in the Python source and therefore it's decided that you yourself need to convert the data when you need to instead of Python trying to figure it out for you.So before sending it to the socket layer (serial uses sockets as well) you simply convert it one step closer to something the machine will understand :)

  • Here you'll find a complete list of what values each character have.

Ps: This is an oversimplification of how stuff works, if I got the terminology mixed up or something just leave a comment and I'll correct it. This is just to explain WHY you put a b in front of your strings :)