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

yipeiwu_com6年前Python基础

安装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设计】。

相关文章

Python BS4库的安装与使用详解

Python BS4库的安装与使用详解

Beautiful Soup 库一般被称为bs4库,支持Python3,是我们写爬虫非常好的第三方库。因用起来十分的简便流畅。所以也被人叫做“美味汤”。目前bs4库的最新版本是4.60。...

Python命令行参数解析模块getopt使用实例

格式 getopt(args, options[, long_options]) 1.args表示要解析的参数. 2.options表示脚本要识别的字符.字符之间用”:”分隔,而且必须...

zbar解码二维码和条形码示例

复制代码 代码如下:#!/usr/bin/env python# coding: u8import osimport zbarimport Imageimport urllibimpor...

用Python登录Gmail并发送Gmail邮件的教程

 这篇快文介绍了使用Gmail作为您的e-mail服务器,通过Python的内置SMTP库发送电子邮件。它并不复杂,我保证。 下面是如何在Python中登录GMail: &nb...

Python3中内置类型bytes和str用法及byte和string之间各种编码转换 问题

Python 3最重要的新特性大概要算是对文本和二进制数据作了更为清晰的区分。文本总是Unicode,由str类型表示,二进制数据则由bytes类型表示。Python 3不会以任意隐式的...