脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 使用python3实现操作串口详解

使用python3实现操作串口详解

2021-05-10 00:25白话 Python

本文给大家介绍的是在python中通过引用serial模块包,来操作串口的方法的示例,有需要的小伙伴可以参考下

通过引用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、操作

有两种设置串口的方式:

方式一:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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

方式二:这个是可以关闭串口的

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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()

原文链接:http://blog.51cto.com/feature09/2335556

延伸 · 阅读

精彩推荐