1、需要模块以及测试工具 模块名:pyserial 使用命令下载:python -m pip install pyserial 串口调试工具:sscom5.13.1.exe 2、导入模块 import serial 3、打开串口 直接通过new一个Serial()的实例即可打开 返回实例 # encoding=utf-8 import serial if __name__ == '__main__': com = serial.Serial('COM3', 115200) print com 运行结果 Serial<id open=True>(port=’CO 在Python编程中,进行串口通信是一个常见的任务,特别是在物联网(IoT)设备或嵌入式系统的开发中。本文将详细介绍如何使用`pyserial`模块进行串口的基本操作,包括发送和接收数据。 我们需要安装`pyserial`模块。在命令行中,可以使用以下命令来下载和安装: ```bash python -m pip install pyserial ``` 安装完成后,我们可以导入`serial`模块以开始使用串口功能: ```python import serial ``` 接下来,我们可以通过创建`Serial()`类的实例来打开串口。例如,打开`COM3`端口,波特率为`115200`: ```python com = serial.Serial('COM3', 115200) ``` 当成功打开串口后,`Serial()`实例会返回一个包含端口信息的对象。例如: ```python print(com) # 输出类似:Serial<id=0x3518940, open=True>(port='COM3', baudrate=115200, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=False, rtscts=False, dsrdtr=False) ``` 发送数据是通过`write()`方法实现的,它接收一个字符串或字节序列作为参数,并返回实际发送出去的字节数: ```python success_bytes = com.write('This is data for test') print(success_bytes) # 输出:21 ``` 为了接收数据,可以使用`read()`方法。默认情况下,它会阻塞并等待接收到指定数量的数据。例如,接收10个字符: ```python data = com.read(10) print(data) # 输出:'123456789a' ``` 如果想要在超时时间内持续接收数据,可以结合`inWaiting()`方法来检查待接收的数据长度,并用`while`循环来处理: ```python over_time = 30 start_time = time.time() while time.time() - start_time < over_time: data = com.read(com.inWaiting()) data = str(data) if data != '': print(data) ``` 为了提高代码的可复用性和可维护性,我们可以将这些功能封装到一个类中,例如`COM`类: ```python class COM: def __init__(self, port, baud): self.port = port self.baud = int(baud) self.open_com = None # 假设WriteLog是用于记录日志的类 self.log = WriteLog.WriteLog('ITC_LOG.LOG') self.get_data_flag = True self.real_time_data = '' # 获取实时数据 def get_real_time_data(self): return self.real_time_data # 清空实时数据 def clear_real_time_data(self): self.real_time_data = '' # 设置是否获取数据 def set_get_data_flag(self, get_data_flag): self.get_data_flag = get_data_flag # 打开串口 def open(self): try: self.open_com = serial.Serial(self.port, self.baud) except Exception as e: self.log.error(f'Open com fail:{self.port}/{self.baud}') self.log.error('Exception:', e) # 接收数据 def receive_data(self, over_time=30): start_time = time.time() while time.time() - start_time < over_time: if self.get_data_flag: data = self.open_com.read(self.open_com.inWaiting()) data = str(data) if data != '': self.real_time_data += data 这样,我们就可以通过创建`COM`类的实例来管理串口操作,方便在不同项目中复用。例如: ```python com = COM('COM3', 115200) com.open() com.receive_data() print(com.get_real_time_data()) ``` `pyserial`库为Python提供了简单易用的串口通信接口,通过创建和配置`Serial`对象,我们可以轻松地进行串口的打开、关闭、发送和接收数据等操作,进一步可以封装成类来提升代码的组织结构和可读性。在实际应用中,确保正确选择串口和波特率,以及处理好数据接收的时机和方式,是实现可靠串口通信的关键。
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![avatar-default](https://csdnimg.cn/release/downloadcmsfe/public/img/lazyLogo2.1882d7f4.png)
- zhanmsl2021-10-13该资源为网上直接找的帖子复制、粘贴过来的,python代码没有格式,介绍的也混乱。
![avatar](https://profile-avatar.csdnimg.cn/default.jpg!1)
- 粉丝: 9
- 资源: 925
我的内容管理 展开
我的资源 快来上传第一个资源
我的收益
登录查看自己的收益我的积分 登录查看自己的积分
我的C币 登录后查看C币余额
我的收藏
我的下载
下载帮助
![voice](https://csdnimg.cn/release/downloadcmsfe/public/img/voice.245cc511.png)
![center-task](https://csdnimg.cn/release/downloadcmsfe/public/img/center-task.c2eda91a.png)
最新资源
![feedback](https://img-home.csdnimg.cn/images/20220527035711.png)
![feedback-tip](https://img-home.csdnimg.cn/images/20220527035111.png)
![dialog-icon](https://csdnimg.cn/release/downloadcmsfe/public/img/green-success.6a4acb44.png)