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 借助numpy保存数据为csv格式的实现方法

借助numpy可以把数组或者矩阵保存为csv文件,也可以吧csv文件整体读取为一个数组或矩阵。 1.csv ==> matrix import numpy my_matrix...

Scrapy的简单使用教程

Scrapy的简单使用教程

在这篇入门教程中,我们假定你已经安装了python。如果你还没有安装,那么请参考安装指南。 首先第一步:进入开发环境,workon article_spider 进入这个环境:...

使用Python实现博客上进行自动翻页

使用Python实现博客上进行自动翻页

先上一张代码及代码运行后的输出结果的图! 下面上代码: # coding=utf-8 import os import time from selenium import web...

python利用openpyxl拆分多个工作表的工作簿的方法

python利用openpyxl拆分多个工作表的工作簿的方法

实现按目录拆分工作簿,源数据如下图 按目录拆分成N个文件。 上代码,没有找是否有整个sheet 复制的,先逐个cell复制解决问题。: # encoding: utf-8 """...

Python使用QQ邮箱发送邮件报错smtplib.SMTPAuthenticationError

Python使用QQ邮箱发送邮件报错smtplib.SMTPAuthenticationError

最新在学习Python的基础入门系列课程,今天学习到使用python 的内置库smtplib发送邮件内容。 使用Python发送邮件步骤简单: 创建SMTP连接 使用邮箱和密码...