PyQT5 QtSerialPort 校验和前缀问题

问题描述 投票:0回答:1

以下配置:Raspberry Rpi4B / Python 3.11.2 / PyQt5 5.15.9

以下配置:Raspberry Rpi4B / Python 3.11.2 / PyQt5 5.15.9 我有一个关于如何调整前缀校验和字节的问题,在我的代码中我缺少符号 \x,其余部分似乎工作正常,还更改了最后一个数据字节。 请参阅随附的代码和 shell 结果

from PyQt5 import QtCore, QtWidgets, QtSerialPort

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        
        self.send1_btn = QtWidgets.QPushButton(
            text="Send1",
            clicked=self.send1
        )
        lay = QtWidgets.QVBoxLayout(self)
        hlay = QtWidgets.QHBoxLayout()
        hlay.addWidget(self.send1_btn)
        lay.addLayout(hlay)
        
        self.serial = QtSerialPort.QSerialPort('/dev/ttyUSB0',
        baudRate=QtSerialPort.QSerialPort.Baud57600,
        parity=QtSerialPort.QSerialPort.NoParity,
        dataBits=QtSerialPort.QSerialPort.Data8,
        stopBits=QtSerialPort.QSerialPort.OneStop)
        self.serial.open(QtCore.QIODevice.ReadWrite)
        self.serial.setDataTerminalReady(True) 
        #self.serial.readyRead.connect(self.handle_ready_Read)
               
    def send1(self):
        intiger_val = 1468                       # value 1468 that I always want to adjust
        bytes_val = intiger_val.to_bytes(2,'big')
        print("bytes_val=",bytes_val)
        result = bytearray(b'\xCC\x04\x3C\x34')  # fixed previous bytes
        result.extend(bytes_val)
        print("result=",result)                  # correct bytes up to here
        def rs232_checksum(the_bytes):
            return b'%02X' % (sum(the_bytes) & 0xFF)
        checksum_bytes = rs232_checksum(result)
        print("checksum=",checksum_bytes)        # checksum byte correct but missing prefix \x
        result.extend(checksum_bytes)
        send_value=bytes(result)
        print("send_value=",send_value)          # Bytes correct but missing prefix \x 01
        self.serial.write(send_value)            #bytes must be '\xCC\x04\x3C\x34\x05\xbc\x01'

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

外壳结果

# bytes_val= b'\x05\xbc'
# result= bytearray(b'\xcc\x04<4\x05\xbc')
# checksum= b'01
# send_value= b'\xcc\x04<4\x05\xbc01'
serial-port checksum prefix
1个回答
0
投票

我花了几个小时寻找,但找到了解决方案。也许有更短的方法,请给我评论。 将以下内容插入到代码中

导入编解码器

checksum_convert=codecs.getdecoder('hex')(checksum_bytes)[0]

© www.soinside.com 2019 - 2024. All rights reserved.