My laptop runs a Python program that reads a joystick to send a speed command to an Arduino that in turn controls the motor on a toy car. To do that the program converts an integer with values between 0 and 255 to a single unsigned byte that it sends over a serial connection to the Arduino.
This code works to do that:
if event.axis == axis:
speed = int((event.value + 1.0) / 2.0 * 255.0)
speedCommand = bytearray(b'\x00')
speedCommand[0] = speed
speedCommand = bytes(speedCommand)
ser.write(speedCommand)
print(speed, speedCommand)
While that code works, it's not very elegant. I would like to find a one-line instruction that does the same thing as the three lines that start with "speedCommand". I tried this, for example:
speedCommand = chr(speed).encode()
But it only works for 0 to 127. Any number above 127 encodes to two bytes[, as the character is seen as a signed byte with values above 127 being negative].
EDITED TO ADD: My assumption that "the character is seen as a signed byte with values above 127 being negative" may not be correct.
You just need:
speed_command = bytes([speed])
The bytes
constructor accepts an iterable of int
objects, so just put it in a list when you pass it to the constructor.