Basic movement programs
Time: 9:30 AM to 10:15 AM
Get the day 2 code
SSH into your robot and clone the camp scripts:basic_movement.py and keyboard_drive.py, but first you are going to build them yourself so you understand every line.
The movement API
Every program starts the same way — import the library and create a robot object:px is your robot. Here are the commands you can call on it:
Every program that controls motors or servos must run with
sudo:Program 1: movement demo
Create a new file on the robot:Step 1 — Setup and imports
Start with the imports and create the robot object. Wrap everything in atry/finally block so the robot always stops cleanly, even if you press Ctrl-C:
Step 2 — Straight lines
The simplest commands: drive forward, wait, stop, then reverse:px.forward(30) starts the motors at 30% power. They keep running until you call px.stop(). The time.sleep(2) makes the program wait 2 seconds while the motors run.
Step 3 — Steering turns
To turn, set the steering angle before or while driving. Remember to reset it to 0 afterwards:Step 4 — Speed ramp
Use afor loop to smoothly ramp the speed up and then back down:
range(10, 65, 5) counts from 10 to 60 in steps of 5. Each step lasts 0.3 seconds, so the robot accelerates and then decelerates smoothly.
Step 5 — Figure-8
Combine steering changes while driving to create a figure-8 pattern:Step 6 — Three-point turn
A three-point turn uses forward, backward, and steering together:Step 7 — Main block
Add the entry point that runs the demo safely:finally block guarantees the motors stop and steering centers even if you interrupt the program.
Run it
Final code: basic_movement.py
Click to see the complete program
Click to see the complete program
Program 2: keyboard drive
Now build an interactive driver where you control the robot in real time with WASD keys.Step 1 — Read keypresses without Enter
Normally Python waits for you to press Enter. This helper function reads a single keypress immediately:getch() returns whatever key the user pressed.
Step 2 — Set up state variables
Track the robot’s current state:Step 3 — The control loop
Read a key, match it to an action, and update the robot:\033[2K\r escape code clears the current line so the status updates in place instead of scrolling.
Run it
Final code: keyboard_drive.py
Click to see the complete program
Click to see the complete program
Challenge: build your own sequence
Write a custom movement pattern from scratch. Try to make the robot:- Drive in a square (forward, turn 90°, repeat 4 times)
- Drive in a spiral (gradually increase the speed while turning)
- Do a parallel park (forward, steer, reverse into a spot)
from picarx import Picarx and import time, create px = Picarx(), and build your pattern using forward, backward, stop, set_dir_servo_angle, and sleep.

