python的串口通信(pyserial)
1 使用用硬件
树莓派,CH340串口转USB两个,PC
2 环境安装
树莓派我使用的是自带系统,环境都已经配好了,PC这边我安装了的ubunt子系统,有python环境,那么就需要安装pyserial库和CH340的驱动
sudo apt-get update
sudo apt install python-pip
pip install --upgrade pip
pip install pyserial
可以使用命令查看本机的串口
python -m serial.tools.list_ports
python3 -m serial.tools.list_ports
PC的话将会列举一堆,需要取设备管理器中找到对应的COM口号,例如我串口是COM8,则是用的/dev/ttyS5
树莓派的话将会显示两个,/dev/ttyAMA0是GPIO处的串口,/dev/ttyUSB0则是我插入的串口转USB模块
pi@raspberrypi:~ $ python -m serial.tools.list_ports
/dev/ttyAMA0
/dev/ttyUSB0
3 收发测试
PC
lissettecarlr@lissettecarlr ~ % python
Python 2.7.12 (default, Nov 12 2018, 14:36:49)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import serial
>>> com=serial.Serial('/dev/ttyS8',115200,timeout=0.2)
>>> com.isOpen()
True
>>> com.write('123')
3
>>> com.readline()
'lalala'
>>>
树莓派
root@raspberrypi:~# python
Python 2.7.13 (default, Sep 26 2018, 18:42:22)
[GCC 6.3.0 20170516] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import serial
>>> com=serial.Serial('/dev/ttyUSB0',115200,timeout=0.5)
>>> com.isOpen()
True
>>> com.readline()
'123'
>>> com.write('lalala')
6
>>>
4 miniterm
这是一个简单的串口收发工具,在控制台每输入一个字符将被立即发送出去。而接收到的信息会被打印在当前窗口中
例如
pi@raspberrypi:~ $ python -m serial.tools.list_ports
/dev/ttyAMA0
/dev/ttyUSB0
2 ports found
pi@raspberrypi:~ $ sudo miniterm.py /dev/ttyUSB0
--- Miniterm on /dev/ttyUSB0 9600,8,N,1 ---
--- Quit: Ctrl+] | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H ---
AT
image.png
5编写一个串口收发的小程序
该程序接收控制台输入,将其串口发送出去,如若需要接收对应模组应答信息,则将屏蔽取消
import serial
import os
import threading
import serial.tools.list_ports
from time import sleep
def rcv_data():
while True:
rcv=serial.readline()
rcv=rcv.decode()
print(rcv)
if __name__=='__main__':
port_list = list(serial.tools.list_ports.comports())
k=0
for i in port_list:
print(i,k)
k=k+1
if len(port_list) <= 0:
print("not find serial")
else:
serial_k=input("please switch serial:")
k = int(serial_k)
serial_list = list(port_list[k])
serialName = serial_list[0]
#print(serialName)
serial=serial.Serial(serialName,115200,timeout=3600)
th=threading.Thread(target=rcv_data)
th.setDaemon(True)
th.start()
if serial.isOpen():
print("open succeed >",serial.name)
else:
print("open failed >",serial.name)
while True:
send_data=input("=>")
send_data = send_data + '\r\n'
serial.write(send_data.encode())
# data=serial.read(1)
# sleep(0.1)
# data = (data + serial.read(serial.inWaiting())).decode()
# print(data)
运行结果
image.png
注意事项:
不要将文件命名为serial,这和导入包名称相同!
参考资料
来源:CSDN
作者:史努B
链接:https://blog.csdn.net/f2157120/article/details/103765653