Question

I am very new to python and trying to write data using serial and python 3. Please help with the error below.

>>> import serial
>>> check=serial.Serial(1)
>>> print(check.name)
COM2
>>> check.write("test")
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    check.write("test")
  File "C:\Python34\lib\site-packages\serial\serialwin32.py", line 283, in write
    data = to_bytes(data)
  File "C:\Python34\lib\site-packages\serial\serialutil.py", line 76, in to_bytes
    b.append(item)  # this one handles int and str for our emulation and ints for Python 3.x
TypeError: an integer is required
Was it helpful?

Solution

import serial
check=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 serial
check=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 :)

OTHER TIPS

You can also us data.encode('utf-8'). One of the problems of course is that the utf-8 codec is limited to a max value of 127 (7-bits) instead of the full 256 (8-bits) byte....

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top