打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Python使用pyserial进行串口通信

安装pyserial

pip install pyserial
  • 1

查看可用的端口

# coding:utf-8import serial.tools.list_portsplist = 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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

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

# 所发十六进制字符串010591F50000F104cmd = [0x01, 0x05, 0x91, 0xF5, 0x00, 0x00, 0xF1, 0x04]
  • 1
  • 2

串口通信
Windows下端口为COM*, Ubuntu下为/dev/ttyS0

import serialclass 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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
python安装pyserial,例如pyserial-3.4.tar.gz
Python的串口通信(pyserial)
python 串口访问模块
python中pyserial模块使用方法
Python 中轻松实现串口通信
如何使用Python开发串口通讯上位机(一)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服