Python使用pyserial进行串口通信的实例

Phedra ·
更新时间:2024-09-21
· 531 次阅读

安装pyserial

pip install pyserial

查看可用的端口

# coding:utf-8 import serial.tools.list_ports plist = list(serial.tools.list_ports.comports()) if len(plist) <= 0: print("没有发现端口!") else: plist_0 = list(plist[0]) serialName = plist_0[0] serialFd = serial.Serial(serialName, 9600, timeout=60) print("可用端口名>>>", serialFd.name)

所发十六进制需转换为以下格式

# 所发十六进制字符串010591F50000F104 cmd = [0x01, 0x05, 0x91, 0xF5, 0x00, 0x00, 0xF1, 0x04]

串口通信

Windows下端口为COM*, Ubuntu下为/dev/ttyS0 import serial class Ser(object): def __init__(self): # 打开端口 self.port = serial.Serial(port='COM4', baudrate=9600, bytesize=8, parity='E', stopbits=1, timeout=2) # 发送指令的完整流程 def send_cmd(self, cmd): self.port.write(cmd) response = self.port.readall() response = self.convert_hex(response) return response # 转成16进制的函数 def convert_hex(self, string): res = [] result = [] for item in string: res.append(item) for i in res: result.append(hex(i)) return result

以上这篇Python使用pyserial进行串口通信的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持软件开发网。

您可能感兴趣的文章:Python实现串口通信(pyserial)过程解析Python实现TCP通信的示例代码Python3简单实现串口通信的方法Python两台电脑实现TCP通信的方法示例python3利用Socket实现通信的方法示例Python中的Socket 与 ScoketServer 通信及遇到问题解决方法Python网络编程使用select实现socket全双工异步通信功能示例基于python实现蓝牙通信代码实例



pyserial 串口 串口通信 通信 Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号