之前使用minimalmodbus可以实现与ModBus485传感器通信了,但是有个检测SF6和氧气的传感器却无法获取数据,不管是minimalmodbus还是pymodbus,都是在获取最后一位校验码时失败了,导致CRC错误,报文被丢弃。尝试了很多方法和咨询厂家之后也没有更好的方法。最后只能选择使用最原始的方式,串口通信。

首先安装pyserial
pip install pyserial

然后直接上码

indows下端口为COM*, Ubuntu下为/dev/ttyS0或ttyUSB*

import serial

class Ser(object):
  def __init__(self):
    # 打开端口
    self.port = serial.Serial(port='COM4', baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=5)

  # 发送指令的完整流程
  def send_cmd(self, cmd):
    self.port.write(cmd)
    response = self.port.readall()
    response = self.convert_hex(response)
    self.port.close()
    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

这里定义了一个Ser类,它有两个方法,send_cmd是发送并接收报文,convert_hex是将接收到的报文转成16进制。将文件保存为sf6.py,因为我们的目的是获取SF6和氧气的值

示例:

# 调用
from sf6 import Ser

# 实例化对象
obj = Ser()

# 要发送的报文
request = [0x05, 0x03, 0x10, 0x00, 0x00, 0x05, 0x80, 0x8d]

# 发送数据到
results = obj.send_cmd(request)

# 返回的数据是一个list
# 按照传感器的返回报文格式,将数据转换成十进制
sf6 = int(results[4],16) + int(results[5],16)
o2 = (int(results[6],16) + int(results[7],16))/10
print (sf6,o2)

参考资料:
Python使用pyserial进行串口通信的实例
Convert hex string to int in Python
python调用其他文件函数或类

标签: none

评论已关闭