How To Build Byte Array Frame And Calculate Checksum
I'm trying to communicate with a serial port as defined in a specification. ser = serial.Serial('/dev/ttyUSB0', baudrate='115200') frame = bytearray([ 0x00, 0x00, #frame con
Solution 1:
Yes it is that simple - you will normally fill in your frame, and append the checksum in another stage - like in:
In [73]: frame = bytearray([
...: 0x00, 0x00, #frame control (2 bytes)
...: 0x00, 0x00, #machine id (2 bytes)
...: 0x07, # number of bytes in data field
...: 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, #data field itself
...: ])
In [75]: checksum = sum(frame)
In [76]: frame.extend((checksum // 256, checksum % 256))
In [80]: print (", ".join("\\x%02X" % v for v in frame))
\x00, \x00, \x00, \x00, \x07, \x01, \x01, \x01, \x00, \x00, \x00, \x00, \x00, \x0A
Now, note a detail: I added the 2 bytes of the checksum in the "natual order" - which is "MSB" (most significant byte) first. As is in your spec. That should work - if not you likely hae some formatting error in one of the other fields.
Post a Comment for "How To Build Byte Array Frame And Calculate Checksum"