【问题标题】:calculate checksum of hex data and send it by serial.to_bytes in python计算十六进制数据的校验和并在 python 中通过 serial.to_bytes 发送
【发布时间】:2018-08-09 12:23:10
【问题描述】:

我有这个代码:

def checksum_calc(data):
        checksum = 0
        for ch in data:
                checksum += ord(ch)
        return hex(checksum % 256)

checksum=checksum_calc('\xAA\x41\xA1\x0E\x63\x02\x15\x0A\x3F\x00\x00\x00\x00')
test=[0xAA,0x41,0xA1,0x0E,0x63,0x02,0x15,0x0A,0x3F,0x00,0x00,0x00,0x00,checksum]
 ser.write(serial.to_bytes(test))

我需要串行发送的数据是可变的,可以根据我的代码的其他部分进行更改,所以我需要计算数据的校验和,然后使用 serial.to_bytes 发送

当我运行它返回的代码时:string must be of size 1

但是 checksum_calc 函数运行良好,但我无法将其结果放入测试变量并将其发送到串行。

如何将校验和结果放入测试变量中?

【问题讨论】:

    标签: python hex checksum pyserial


    【解决方案1】:

    我在这里找到了答案: Sending string to serial.to_bytes not working

    我必须这样做

    test= ['0xAA','0x41','0xA1','0x0E','0x63','0x02','0x15','0x0A','0x3F','0x00','0x00','0x00','0x00',checksum]
       int_values = [int(h, base=16) for h in test]
    

    但我喜欢第二种方法

    【讨论】:

      猜你喜欢
      • 2017-08-24
      • 2019-03-01
      • 1970-01-01
      • 2015-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-01
      • 2016-04-06
      相关资源
      最近更新 更多