Keyboard Control
English translation
Learning objectives
To stop a moving device, define its behavior when a key is released or communication is lost, as well as when a key is pressed.
Execution conditions
Reproduce behavior using an input event list. Connecting a real keyboard or device is a separate step that connects the same processing function to the event receiver.
From key input to velocity commands
Starting conditions
s, key=[w,w,release,d,quit,w]. Set w=(1,0) and d=(0,-1) m/s.
Procedure
- Create a pure function that converts each input into vx, vy, and termination state.
- Set velocity to 0 on release, and ignore all inputs after quit.
- Record the command vector and state for each input row.
Results to retain
- A processing table with 6 input rows and a processing function.
events=list(zip([0,.1,.2,.3,.4,.5],['w','w','release','d','quit','w']))
key_velocity={'w':(1.,0.),'s':(-1.,0.),'a':(0.,1.),'d':(0.,-1.)}
# TODO: Write decode(key, stopped), including the stopped state.
Record results and self-check
t [s]:
key:
vx [m/s]:
vy [m/s]:
Termination state:
Points to check
- Does w after quit leave velocity disabled?
- Do undefined keys trigger a stop or an explicitly defined ignore rule?
Time intervals and cumulative movement
Starting conditions
Assume the velocity from activity 1 is maintained until the next input. The initial position is (0,0) m.
Procedure
- Calculate Δposition=v*Δt for each interval.
- Create a position table over time and an xy trajectory plot.
- Compare with the result when all input intervals are changed to .2 s.
Results to retain
- Compare trajectories and final positions under the two interval conditions.
import numpy as np
import matplotlib.pyplot as plt
position=np.zeros(2)
# TODO: Integrate the commands from the first activity over the time intervals.
Record results and self-check
Interval:
Δt [s]:
Velocity [m/s]:
Cumulative position [m]:
Points to check
- Did you distinguish velocity from travel distance?
- Does position remain fixed after termination?
Repeated input and long gaps
Starting conditions
Add a record with repeated w key events at s, followed by .5 s without input. Set the timeout to .2 s.
Procedure
- Compare the behavior to ensure repeated inputs set velocity rather than accumulate acceleration commands.
- Add a rule to stop when .2 s has elapsed since the last input.
- Record how commands and positions differ before and after applying a timeout.
Results to retain
- Plots before and after applying a timeout, and 3 sentences describing the behavior rules.
events=[(0.,'w'),(.01,'w'),(.02,'w')]
timeout=.2
# TODO: Calculate commands up to .5 s using a virtual clock with .01 s steps.
Record results and self-check
Time point:
Last input / elapsed time [s]:
Timeout?:
Velocity:
Position:
Points to check
- Can you reproduce behavior using recorded events without sending actual OS keyboard input?
- Are input processing, time updates, and device transmission separated?