pySerial 学习笔记-安装与测试

pySerial官网介绍
pySerial API介绍

安装

环境:
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() 函数的返回值是我们发送数据的长度。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值