Create a new file called remote.py and add the code to the right.
+# remote.py
+
+import board
+import busio
+
+START_BYTE = 0xAA
+END_BYTE = 0xBB
+PACKET_LENGTH = 8
+
+# Calibration values
+LEFT_MIN = 0
+LEFT_MID = 131
+LEFT_MAX = 203
+RIGHT_MIN = 51
+RIGHT_MID = 120
+RIGHT_MAX = 255
+
+class ThumbInput:
+ def __init__(self, tx=board.GP0, rx=board.GP1, baudrate=115200):
+ self.uart = busio.UART(tx=tx, rx=rx, baudrate=baudrate, timeout=0.1)
+ self.buffer = bytearray()
+
+ def read(self):
+ """Returns (left_percent, right_percent) in range [-100, 100], or None if packet incomplete."""
+ data = self.uart.read(1)
+
+ if data:
+ byte = data[0]
+ self.buffer.append(byte)
+
+ if len(self.buffer) > PACKET_LENGTH:
+ self.buffer = self.buffer[-PACKET_LENGTH:]
+
+ if len(self.buffer) == PACKET_LENGTH and self.buffer[0] == START_BYTE and self.buffer[-1] == END_BYTE:
+ payload = self.buffer[1:7]
+ self.buffer = bytearray()
+ left_raw = payload[1]
+ right_raw = payload[3]
+
+ left = self._map_thumbstick(left_raw, LEFT_MIN, LEFT_MID, LEFT_MAX)
+ right = self._map_thumbstick(right_raw, RIGHT_MIN, RIGHT_MID, RIGHT_MAX)
+
+ return (int(left), int(right))
+
+ return None
+
+ def _map_thumbstick(self, x, min_val, mid_val, max_val):
+ if x < mid_val:
+ return (x - mid_val) / (mid_val - min_val) * 100
+ else:
+ return (x - mid_val) / (max_val - mid_val) * 100
+
+
+ Import just the ThumbInput part of the library.
Initialize the receiver with receiver = ThumbInput()
Create a new loop as this won't work nicely with any i2c, this loop should be placed after the motors are created, and before the i2c is initialized.
+
+
+from remote import ThumbInput
+
+receiver = ThumbInput()
+
+while True:
+ result = receiver.read()
+ if result:
+ left_motor.move(result[0])
+ right_motor.move(result[1])
+ #print("Left:", result[0], "Right:", result[1])
+ time.sleep(0.001)
+
+