flowchart LR E[Rotary encoder] --> A[Arduino Uno] A -- "serial, 9600 baud" --> R[Serial reader] R -- queue --> K[Keyboard emulator] K -- "emulated key presses" --> G[Gym game] G -- reward --> S[Score queue]
Stroke rehabilitation means doing the same movement many times a day, for weeks. That gets boring fast, and patients who are bored stop doing their exercises. Games help. A patient who is trying to win at Pong will happily repeat a movement they’d skip as a plain exercise.
At CMC Vellore I built a proof of concept that lets a patient play Atari games from OpenAI Gym by moving their wrist instead of using a keyboard. A rotary encoder measures the wrist angle, and Python turns that angle into key presses or mouse movement that the game understands. It was never tested with patients; the goal was to show that the control loop works.
Code: Zilch123/Gym-game-emulated-control
Hardware
- Rotary encoder: an Orange 600 PPR 2-phase incremental optical encoder, aligned with the wrist joint so that it measures the wrist angle.
- Arduino Uno: reads the encoder and sends the angle to the PC over serial.
On the PC side it needs Python 3.6, gym (with the Atari games), pyserial and pynput.
How the pieces fit
MainFile.py runs three processes in parallel with Python’s multiprocessing:
- Serial reader: reads the angle from the Arduino.
- Keyboard emulator: turns the angle into key presses.
- Game: runs the Gym game in human play mode.
They pass data to each other through queues. Separate processes matter here, because serial reads block and the key timing uses busy-wait loops. If everything ran in one loop, the game would stutter.
Reading the encoder
The Arduino sends each reading as a 5-byte packet: two 0xFF header bytes, the angle as a signed 16-bit number, and a checksum (the sum of the first four bytes, mod 256). The reader waits for the header, rebuilds the angle and drops any packet whose checksum doesn’t match:
def serial_read(qu):
ser = serial.Serial("COM11", 9600)
while True:
s1=int.from_bytes(ser.read(),"big")
s2=int.from_bytes(ser.read(),"big")
if(s1==255 & s2==255):
d1=int.from_bytes(ser.read(),"big")
d2=int.from_bytes(ser.read(),"big")
data=int.from_bytes(bytes([d1,d2]), byteorder='big', signed=True)
cksum=int.from_bytes(ser.read(),"big")
cksum0=sum([s1,s2,d1,d2]) % 256
if(cksum==cksum0):
qu.put(data)Proportional control with key presses
A game only knows whether a key is pressed or not. That makes control all-or-nothing: a small movement moves the paddle exactly as fast as a big one, which is no good for rehab, where you want effort to matter.
The fix is the same idea as PWM. In each short cycle, the key is held down for a fraction of the time, and that fraction grows with the angle. A small movement taps the key briefly and the paddle creeps; a bigger movement holds it longer and the paddle moves faster. Turning one way presses up, the other way presses down.
Here is the “up” half of the keyboard emulator, as in the repo. The timing uses perf_counter_ns() busy-waits, because time.sleep() isn’t precise enough at the millisecond level:
def keyboard_emulator(qu, lock):
Th_angle1=1000
Th_angle2=1000
TonMax=10*10**6 #10*10**6 ns = 10 ms
TT_PWM= 15*10**6 #15*10**6 ns = 15 ms
k1= Th_angle1/TonMax
k2= Th_angle2/TonMax
Offset=(9*10**6)
keyboard = Controller()
while True:
while not qu.empty():
data=qu.get()
lock.acquire()
print("Data", data, qu.get())
if(data<0):
D2on= (abs(data)/k2)+Offset
keyboard.press(key.up)
t2_onstart = perf_counter_ns()
while((perf_counter_ns()-t2_onstart)<D2on):
pass
t2_onstart=0
keyboard.release(key.up)
t2_offstart = perf_counter_ns()
while((perf_counter_ns()-t2_offstart)<TonMax-D2on):
pass
t2_offstart=0The “down” half is the same with the sign flipped.
Running the game
The game is Atari Pong through Gym’s play() utility, which shows the game window and reads the keyboard, so the emulated key presses just work. A callback pushes each reward into a queue, so the patient’s score can be tracked:
def game_HM(score):
def callback(obs_t, obs_tp1, action, rew, done, info):
score.put(rew)
env = AtariEnv(game= 'pong',mode=0,difficulty=1, obs_type='image', frameskip=1, full_action_space=False)
# env = gym.make("BreakoutDeterministic-v4") #Breakout-v0 #Pong-v4 #BreakoutDeterministic-v4
play(env, fps=15, zoom=3,callback=callback)Breakout works the same way by swapping the environment.
Two simpler modes
The repo also has two standalone scripts.
PWM_keyEmulator.py is plain on/off control. If the angle goes past a threshold band (±150), it taps a or d; inside the band, it releases both keys. It’s simpler, but you lose the proportional feel.
MouseInterface.py maps the angle straight to the mouse’s horizontal position. The cursor starts at a fixed centre point and moves left or right with the encoder, limited to ±245 pixels:
deltax = xx+(data/mouse_factor)
if(xx+dx>deltax>xx-dx):
mouse.position = (deltax, yy)This suits games where the avatar follows the mouse, because the patient’s position maps one to one to the avatar’s position.
Later
This setup was the input side of the work. Later, I looked at reinforcement learning agents that add a weighted amount of assistance to the player’s input, and how that changes the game score. That’s in AgentAssistance-RL.