The Python `struct` module turns packed C-style binary records into Python values. It is useful when a robot controller must read raw joystick events directly from a Linux device file instead of using a higher-level joystick library. section 7.2 section 7.5.2
A Linux joystick event contains a 32-bit timestamp, a 16-bit value, an 8-bit event type, and an 8-bit axis or button number. `Struct('I h B B')` describes that layout: `I` maps the unsigned 32-bit value, `h` maps the 16-bit signed value, and each `B` maps an 8-bit value. section 7.5.1 section 7.5.2
To unpack one event at a time:
- Create a `Struct` with the format matching the device record: `Struct('I h B B')`. section 7.5.2
- Open `/dev/input/js0` in binary read mode with `'rb'`. section 7.5.2
- Read exactly `event_struct.size` bytes so each loop receives one complete event. section 7.5.2
- Call `unpack(bytes)` and assign the resulting values to `time`, `value`, `type`, and `number`. section 7.5.2
- Check `type == 1` to handle button events, then use `value` and `number` to identify presses and releases. section 7.5.2
Reading button presses
A button numbered `0` produces `value:1 number:0` when pressed and `value:0 number:0` when released. Button `1` follows the same pattern, allowing controller button numbers to drive application behavior. section 7.5.2 section 7.5.1
This direct parsing route fits a joystick-controlled robot stack: joystick events become Python values, which can later be used to send movement requests to a robot server controlling the motors. section 7.2 section 7.8
Listing 7.3 joystick_unpack.py: Unpacking raw joystick events on Linux
#!/usr/bin/env python3
from struct import Struct
DEVICE = '/dev/input/js0'
def main():
event_struct = Struct('I h B B')
with open(DEVICE, 'rb') as js_device:
while True:
bytes = js_device.read(event_struct.size)
data = event_struct.unpack(bytes)
time, value, type, number = data
if type == 1:
print(f'value:{value} number:{number}')
main()
Use the complete `joystick_unpack.py` listing as a runnable starting point for continuously decoding raw joystick events. section 7.5.2

