使用python3实现操作串口详解
通过引用serial模块包,来操作串口。
1、查看串口名称
在Linux和Windows中,串口的名字规则不太一样。
需要事先查看。
Linux下的查看串口命令
root@D2:~# ls -l /dev/ttyS*
crw-rw---- 1 root dialout 4, 64 Dec 26 06:53 /dev/ttyS0
crw-rw---- 1 root dialout 4, 65 Dec 26 06:41 /dev/ttyS1
crw--w---- 1 root tty 4, 66 Dec 26 06:41 /dev/ttyS2
crw-rw---- 1 root dialout 4, 67 Dec 26 06:41 /dev/ttyS3
windows下查看串口命令
在电脑的“设备管理器”中的“通用串行总线控制器”里查看。可以看看COM7这种字样的就是了。
2、先安装serial模块包
pip install pyserial
3、操作
有两种设置串口的方式:
方式一:
import serial
# 连接
# linux
ser = serial.Serial('/dev/ttyS0', 9600, timeout=0.2)
# windows
# ser = serial.Serial('COM7', 9600, timeout=0.2)
# 接收返回的信息
while True:
recv = ser.readline()
print(str(recv))
if str(recv) == 'q':
break方式二:这个是可以关闭串口的
import serial
# 连接
ser = serial.Serial()
ser.port = '/dev/ttyS0'
ser.baudrate = 9600
ser.timeout = 0.2
ser.open()
# 接收返回的信息
while True:
recv = ser.readline()
print(str(recv))
if str(recv) == 'q':
break
ser.close() 相关推荐
LandryBean 2020-06-16
vanturman 2020-06-11
xiaoxiaoCNDS 2020-04-20
furongwei 2020-03-26
rareli 2020-03-20
老和山下的小学童 2020-02-22
internetofthings 2019-12-30
huangzonggui 2019-12-12
NeverAgain 2019-12-07
jj 2010-09-15
LUOPING0 2010-08-27
wwater 2011-04-08
jj 2011-03-30
RayDon 2011-02-12
liuweinn 2011-02-08
hbcbgcx 2010-12-04
zjwijy 2011-08-09