通过引用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()