栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

ubuntu18里用python编写modbus-RTS

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ubuntu18里用python编写modbus-RTS

1.conda环境

用PIP3 或 conda 安装好下面库

1.1 python3.6

1.2 pyserail3.5

1.3 crcmod 1.7

2.代码

查看USB名字,终端输入:

ls /dev/

通过对比插拔usb时,新增的名字,确认串口名,通常是: ttyUSB0

打开串口权限 ,终端输入:

sudo chmod 777 /dev/ttyUSB0

 在pycharm里选择配置好的conda环境,运行以下代码。

import serial
import time
import math
from crcmod import mkCrcFun
from binascii import unhexlify


def crc16_modbus(s):
    crc16 = mkCrcFun(0x18005, rev=True, initCrc=0xFFFF, xorOut=0x0000)
    return get_crc_value(s, crc16)


def get_crc_value(s, crc16):
    data = s.replace(' ', '')
    crc_out = hex(crc16(unhexlify(data))).upper()
    str_list = list(crc_out)
    if len(str_list) == 5:
        str_list.insert(2, '0')  # 位数不足补0
    crc_data = ''.join(str_list[2:])
    return crc_data[:2] + ' ' + crc_data[2:]


def pressure_input_transform(num1, num2=0, num3=0, num4=0):
    p1 = hex(math.ceil(num1 / 0.6 * 409.5))
    p2 = hex(math.ceil(num2 / 0.6 * 409.5))
    p3 = hex(math.ceil(num3 / 0.6 * 409.5))
    p4 = hex(math.ceil(num4 / 0.6 * 409.5))

    str1 = p1[2:len(p1)].zfill(4)
    str2 = p2[2:len(p2)].zfill(4)
    str3 = p3[2:len(p3)].zfill(4)
    str4 = p4[2:len(p4)].zfill(4)

    str5 = crc16_modbus('01' + '10' + '00' + '01' + '00' + '04' + '08' + str1 + str2 + str3 + str4)
    crc_h = str5[3:5]
    crc_l = str5[0:2]

    return '01' + '10' + '00' + '01' + '00' + '04' + '08' + str1 + str2 + str3 + str4 + crc_h + crc_l


if __name__ == '__main__':
    s = serial.Serial('/dev/ttyUSB0', 9600, bytesize=8, stopbits=1, parity='N')
    d = bytes.fromhex(pressure_input_transform(0.25, 0, 0, 0))

    a = s.write(d)

    time.sleep(2)  # must stop
    s.close()

以上代码包含了我机器的部分转换代码,请根据实际情况更改代码。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/665009.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号