Python2 To Python3 Differences With Byte Additions And Sending To Serial Port
Solution 1:
Your bytes are not UTF-8 data; for any of your chr()
values you create outside the range 0 - 127, encoding to UTF-8 produces two bytes.
You were creating Unicode codepoints from integer values; these create Latin-1 codepoints if you limited those to integers between 0 and 255; in principle you could encode to 'latin1'
to get the bytes again, but it is much easier to just create bytes in the first place.
In Python 3, use the bytes
type, created from a list of integers:
defmove(self, id, position):
self.direction(Ax12.RPI_DIRECTION_TX)
Ax12.port.flushInput()
p = [, position>>8]
checksum = (~(id + Ax12.AX_GOAL_LENGTH + Ax12.AX_WRITE_DATA + Ax12.AX_GOAL_POSITION_L + p[0] + p[1]))&0xff
outData = bytes([
Ax12.AX_START, Ax12.AX_START, id,
Ax12.AX_GOAL_LENGTH, Ax12.AX_WRITE_DATA,
Ax12.AX_GOAL_POSITION_L, p[0], p[1], checksum])
Ax12.port.write(outData)
Your own attempt did not include the id
value and you used AX_REG_WRITE
rather than AX_WRITE_DATA
.
You could also use a bytearray()
object, which would let you append additional bytes; you could use that to calculate the checksum by referencing the bytes produced so far, avoiding having to repeat yourself (a common source of errors):
def move(self, id, position):
self.direction(Ax12.RPI_DIRECTION_TX)
Ax12.port.flushInput()
outData = bytearray([
Ax12.AX_START, Ax12.AX_START, id,
Ax12.AX_GOAL_LENGTH, Ax12.AX_WRITE_DATA,
Ax12.AX_GOAL_POSITION_L, position & 0xff, position >> 8])
checksum = ~sum(outData[2:]) & 0xff
outData.append(checksum)
Ax12.port.write(outData)
You could use concatenation too of course (outData = bytes([...])
, outData += bytes([checksum])
) but bytearray
is also available in Python 2, so the above version is compatible with both major Python versions.
Post a Comment for "Python2 To Python3 Differences With Byte Additions And Sending To Serial Port"