安装
环境:
win7 64位
python-3.43rc1(32)
使用pip进行安装:
pip install pyserial
测试
安装官网的测试程序进行测试,出现字符编码问题。
>>> import serial
>>> ser = serial.Serial(2)
>>> print (ser.name)
COM3
>>> ser.write("hello")
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
ser.write("hello")
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
根据错误提示,查找原因及解决方法:
解决方法
网上已经给出了合理的解释:
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’).
根据解决方法,进行修改:
>>> import serial
>>> ser = serial.Serial(2)
>>> print(ser.name)
COM3
>>> ser.write(b'hello')
5
>>> ser.write('hello'.encode('utf-8'))
5
>>> ser.write('hello'.encode('ascii'))
5
>>> ser.close()
这一次,可以正常的使用串口进行通信,其中 write() 函数的返回值是我们发送数据的长度。