CAN stepper application: A two-wheel self-balancing robot
Phone-sensed tilt, acceleration-mode PID, two CAN-linked wheels, logged tuning and drawn-path following
This application builds a two-wheel self-balancing robot from two CANStepper boards. Each board drives one wheel. An Android phone mounted on top of the robot measures the tilt. The phone streams the tilt over Bluetooth Low Energy (BLE) to the first board, which runs the balance controller. That board drives its own wheel and commands the second wheel over CAN. The article covers the rig as it stands at the first project checkpoint. It describes what was built and how faults were isolated. It also gives the measured balance result from logged runs, the motor-stall limit those logs revealed, and the drawn-path following that is built and simulated but not yet run on the robot.
1. Application overview
The robot is an inverted pendulum on two wheels. When the body leans forward, the wheels must accelerate forward and roll back under the centre of mass. Each wheel is a NEMA17 stepper with a CANStepper board, so each wheel has closed-loop speed control. Each also has a 14-bit MT6701 encoder that reports how fast the wheel really turned.
The tilt sensor is not on the boards. A phone lies flat on top of the robot. The phone's fused rotation sensor gives the pitch angle, and its gyroscope gives the pitch rate. Using a phone means no IMU wiring. It also gives a screen, a battery-powered radio and a user interface, all on the robot.
State at this checkpoint
| Item | State |
|---|---|
| CAN between the two boards | Working, 0 bus-off errors (after one faulty board was replaced) |
| Both wheels driven and read back | Working; encoder speed tracks the command closely on both wheels |
| Balancing on the floor | Working: best run 140 s, typical 10–60 s with the current gains |
| Main cause of falls | Identified from logs: both motors stall during hard catches (Section 9) |
| Run logging and analysis tools | Working (phone app + laptop scripts) |
| Laptop control page over Wi-Fi | Working, tested end to end |
| Drawing a path on laptop or phone | Working, tested end to end |
| Driving the drawn path | Firmware and app built; tested in simulation only, not yet run on the robot |
2. Hardware and control architecture
| Part | Role |
|---|---|
| CANStepper board A (node 1) | Right wheel. BLE link to the phone, balance controller, path follower. Drives board B over CAN |
| CANStepper board B (node 2) | Left wheel. Plain CANStepper running GCSP; obeys velocity commands from A |
| 2 × NEMA17 steppers, 1.2 A | One per wheel, run at 63 % of TMC2209 full scale (≈1.2 A) in SpreadCycle for torque |
| Wheels | Ø 102 mm (90 mm printed rim + 6 mm TPU tyre); 320.4 mm per turn |
| Track width | 160 mm wheel centre to wheel centre (142 mm between inner faces, 178 mm overall) |
| Android phone | Tilt sensor (game rotation vector + gyroscope), user interface, run logger, Wi-Fi web server |
| 24 V supply | Powers both boards and motors |
| CAN bus | Two boards, 1 Mbps, GCSP |
Both boards run the same firmware image: stock CANStepper firmware 1.12 plus a balance add-on (Balance.h, PathFollow.h). A role command over USB serial (role A or role B) stores the node ID and the wheel direction in flash. Because the two motors face opposite ways, board B is set to invert_dir = 1, so a positive speed means "forward" on both wheels.
Signal path
phone sensors ──BLE 125 Hz──► board A: balance controller (200 Hz)
│ wheel speed command
├──► own stepper (right wheel)
└──CAN MOVE_VEL──► board B ──► stepper (left wheel)
board B encoder speed ──CAN telemetry 20 Hz──► board A
board A status (54 bytes; 65 with path following) ──BLE 20 Hz──► phone ──Wi-Fi──► laptop pageTiming
| Loop | Rate |
|---|---|
| Phone tilt packets to board A | ~125 Hz (every 8 ms) |
| Balance control loop on board A | 200 Hz (5 ms) |
| Board A status to the phone | 20 Hz |
| Board B speed telemetry to board A | 20 Hz |
| Phone → robot → phone round trip (measured from logs) | ~30 ms |
| Link timeout: robot stops if no tilt sample arrives for | 150 ms |
Phone ↔ board A messages (BLE, little-endian)
| ID | Message | Content |
|---|---|---|
| 0x01 | Tilt | f32 pitch °, f32 pitch rate °/s, i16 drive °/s, i16 turn °/s (joystick) |
| 0x02 | Arm | start / stop balancing |
| 0x03 | Parameter | u8 id, f32 value (gains, R, limits, mode) |
| 0x04 | Save | store settings in flash |
| 0x05 | Zero | current pitch becomes "upright" (trim) |
| 0x06 | Motor test | one wheel at a set speed, for testing |
| 0x07 | Path piece | up to 12 path points (mm), path-following firmware only |
| 0x08 | Follow | GO at a speed (m/s), or stop, path-following firmware only |
3. Step 1: Bring up two boards on one CAN bus
The first wiring of the two boards gave CAN bus-off errors whenever they talked. The bus, cable and connectors had to be separated from the boards themselves. The test that settled it relies on one property of CAN. A node alone on a bus with a healthy transceiver gets no acknowledgements, so it goes error-passive and keeps trying. It does not go bus-off. Bus-off with no cable attached means that node's own CAN hardware is faulty.
| Test | Board A (original) | Board B |
|---|---|---|
| Transmitting alone, cable removed | 16 bus-off events in 3 s | 0 bus-off |
| Board B with its connector and the cable | — | Fine |
The original board A was replaced. With the new board A, the two boards exchanged commands with 0 bus-off errors. A spun its own wheel, and B spun when commanded from A over CAN.
4. Step 2: Make the encoder agree with the motor direction
Board B is mounted mirrored, so its direction pin is inverted with invert_dir = 1. A 20° relative move on board B then ran away instead of stopping. The board was stopped by hand at about −500°. The cause: invert_dir flipped the step direction but not the encoder reading. The closed loop saw its own correction as growing error, which is positive feedback.
The fix flips the encoder count together with the direction pin. When invert_dir changes at runtime, the zero offset shifts so the logical position does not jump.
// encoderUpdate(): invert_dir flips the DIR pin, so the encoder must flip with it,
// or the closed loop sees its own correction as error and runs away.
int64_t phys = rawUnwrapped + corr;
if (pu(P_INVERT_DIR)) phys = -phys;
encCounts = phys - encZeroOffset;After the fix, board B moved +20.0° and −19.9° exactly, and both wheels report + = forward. The balance code then no longer needs to negate either wheel by hand.
5. Step 3: The balance controller
Error. The controller does not act on the angle directly. It acts on how far the centre of mass is ahead of the axle, horizontally. That is the quantity that actually makes the robot fall:
$$ e = R,\sin\theta_0 - R,\sin\theta $$
Here θ is the phone pitch after trim (+ = leaning forward), θ₀ is the setpoint (normally near 0°), and R is the distance from the axle to the centre of mass. A 5° lean with R = 60 mm puts the centre of mass about 5.2 mm ahead of the axle.
PID. The controller computes $u = K_p e + K_i \int e,dt + K_d \dot e$. The D term uses the phone's gyroscope directly, $\dot e = -R\cos\theta,\dot\theta$, instead of differentiating a noisy angle. Anti-windup stops integrating while the output is pinned at its limit, and also caps $|K_i\int e|$.
Two output modes were implemented:
| Mode | PID output means | How the wheel speed is formed |
|---|---|---|
| Acceleration | wheel acceleration (°/s²) | speed is integrated: speed += clamp(−u) · dt, limited to the max speed |
| Velocity | wheel speed (°/s) | speed moves toward −u, limited by the max acceleration |
Outer loop. A slow outer loop moves the setpoint so the robot stays in place instead of rolling away. Without it, any error in "upright" (the phone mount, or the centre of mass) makes the robot balance while drifting off:
$$ \theta_0 = -\left(K_v,(\omega_{wheel} - \omega_{drive}) + K_x,x_{wheel}\right), \quad |\theta_0| \le 6^\circ $$
When the joystick (or the path follower) asks for a drive speed, the position term is reset. The robot then holds a speed, not a place.
Safety states
| State | Trigger | Action |
|---|---|---|
| Balancing | Armed, and held within 10° of upright | Controller runs |
| Fell over | |θ| > 45° | Motors stop; must re-arm |
| Link lost | No tilt sample for 150 ms | Motors stop; must re-arm |
| Ran at the speed limit | Wheel at ≥ 98 % of max speed for 1.5 s | Motors stop; must re-arm |
Board B also stops by itself if board A goes quiet for 300 ms.
6. Step 4: Speed limits
In the first floor test, the wheels reached very high speeds. The original limit was 1600 rpm (about 8.5 m/s with the 102 mm wheels). Every speed in the firmware was then capped, so that neither the app nor a saved setting can exceed it:
| What | Before | Now |
|---|---|---|
| Balancing max speed | 9600 °/s (1600 rpm) | 900 °/s (150 rpm, ≈0.8 m/s) |
| Motor-test speed | whatever the app sent | max 600 °/s (100 rpm) |
| Motor-test acceleration | 20000 °/s² | 720 °/s² (≈1 s ramp) |
| Joystick drive / turn | not capped | 300 / 200 °/s |
The 150 rpm figure came from the simulator. A 10° start plus a hard push peaked at 142 rpm, and 100 rpm failed the push case.
After the cap, the robot sometimes went straight to 150 rpm and stopped. That was the speed-limit safety trip doing its job. In acceleration mode, the controller sets how fast the wheel speeds up, so a lean that never goes away makes the speed climb until it hits the cap. With Kp = 400 and a 5° lean, the P term alone asks for about 400 × 5.2 ≈ 2100 °/s², which reaches the cap in under half a second. This happens when the robot is held in the air, where the wheels cannot push the body upright. It also happens when the tilt or wheel direction is reversed, so the wheels push the wrong way. It is a symptom of a sign or trim error, not of a speed limit set too low.
7. Step 5: Offline gain search in simulation
A Python simulator (algorithm/simulate.py) models the robot as a body pivoting on the axle. Each stepper is modelled as a velocity source with the firmware's acceleration ramp. The phone is modelled too: 100 Hz samples, 25 ms latency, angle and gyro noise, and a mount offset. The controller is a line-for-line twin of the firmware.
A grid search (algorithm/tune.py) ran 1346 gain sets (a coarse grid, then a finer grid around the best) through 8 cases at the real 150 rpm cap. The cases were a 3° start, a 9° start, a tap, a 50 ms link delay, a phone mounted 3° off, R = 45 mm, R = 90 mm, and a noisy phone. A gain set counts only if it survives all 8. Survivors are ranked on wobble, peak wheel speed, command jerk and drift.
| Mode | Best Kp / Ki / Kd (sim) | Wobble | Peak | Jerk |
|---|---|---|---|---|
| Acceleration | 400 / 200 / 46.7 | 1.05° | 104 rpm | 3.1 |
| Velocity | 40 / 350 / 0.33 | 1.04° | 113 rpm | 14.8 |

Figure 1. Simulated response of the best gains in each mode: 5° start, tap at 3 s. The dotted lines are the 150 rpm cap.
213 of 694 acceleration-mode sets and 199 of 652 velocity-mode sets survived every case. Acceleration mode was chosen. It gave about the same wobble as velocity mode with wheel commands about five times smoother.
The real robot disagreed with the simulator. The gains that balanced the real robot (Section 8) fall over in every simulated case. That stays true even after sweeping the body size and wheel radius widely. The simulated link delay (25 ms one way) is close to the measured round trip (~30 ms), so the mismatch most likely lies in the body or motor model. The simulator has to be fitted to logged runs before its gain predictions can be trusted for this robot.
8. Step 6: Run logging and tuning on the real robot
Every time balancing starts, the phone app saves the try as one CSV file. The file starts 1 s before arming and ends 1 s after the robot stops. Each file records:
- every setting in force (mode, Kp/Ki/Kd, I limit, Kv, Kx, R, max acceleration, trim, reverse-tilt flag) and a free-text note
- the robot status at 20 Hz: θ, θ₀, the P/I/D terms, wheel command, both wheels' measured speeds, and the path-follow pose
- the phone tilt exactly as sent, at ~125 Hz
- events: settings changed mid-run, Set upright, STOP
- a footer with the outcome, seconds balanced, peak rpm and largest tilt
A laptop script (tools/runs.py pull) copies the runs off the phone over USB, lists them, and plots any run.
Results across 26 logged runs
| Mode | Kp / Ki / Kd | Runs | Balanced |
|---|---|---|---|
| Velocity | 1.5 / 400 / 0 | 6 | 0.9–1.6 s (one 6.6 s) |
| Acceleration | 54 / 83 / 40 | 2 | 7.5, 10.8 s |
| Acceleration | 60 / 83 / 40 | 15 | 140 s, 63 s, 38 s, 28 s, 20 s, … |
| Acceleration | 80 / 83 / 40 | 3 | 16, 5.5, 5 s |
Other settings: I limit 3000, Kv = Kx = 0.004, R = 60 mm, max acceleration 20000 °/s², fall angle 45°.
Velocity mode overshoots. It drives the right way but reaches the speed cap too late, passes upright, and falls the other way. Raising Kp from 60 to 80 made the robot fall sooner. The working setting is acceleration mode, Kp 60 / Ki 83 / Kd 40.

Figure 2. The longest run, 140 s in acceleration mode, Kp 60 / Ki 83 / Kd 40. From top: tilt (phone raw and after trim), the P/I/D terms, wheel command against both encoders, and controller state.
9. Measured performance: what the logs show
The wheels track the command. Outside the stall events below, both encoders follow the commanded wheel speed closely while balancing, and board B's speed arrives over CAN in step with board A's.
The controller works mostly through the D term. Across the ten Kp 60 runs longer than 5 s, the D term makes up 69–85 % of the output, P 11–19 % and I 4–12 %. Damping catches every small wobble, but there is little restoring push after a large lean. In the falls plotted in detail, a sudden lean of about 20° was caught at high wheel speed, the catch overshot, and the robot then fell.
Falls coincide with both motors stalling. A run was flagged as stalling when the commanded speed was at least 60 rpm while both encoders read under 25 % of it for at least two samples. That happened just before the fall in 14 of the 17 acceleration-mode falls.
| Observation | Value |
|---|---|
| Falls with a stall in the 2 s before the fall | 14 of 17 |
| Wheel speed when stalls began | mostly 60–78 rpm (some up to ~100) |
| Commanded acceleration in the 0.2 s before a stall | 500 – 11600 °/s², many below 2500 |
| Motor current | 63 % of full scale ≈ 1.2 A (rated), SpreadCycle |

Figure 3. A 13.4 s run. From about 13.6 s the command reaches −150 rpm, but both encoders read close to zero: the wheels have stopped turning, and the robot falls.
The motors run at rated current, and stalls begin at modest speeds with modest acceleration. Both wheels also stop at the same moment. Together these point to a shared cause. The leading candidate is the 24 V supply sagging under the current burst of a hard catch. Two runs ended with "signal lost" or "no data from robot", which would fit board A briefly resetting on the same dip. This has not yet been confirmed by measurement. The next firmware steps are to record the TMC2209 driver status (under-voltage, over-temperature) in the run log, and to add stall recovery. When the encoders show a stall, the command drops to the speed the wheel is actually turning, so the stepper can re-synchronise instead of being asked for still more speed.
10. Step 7: Laptop page and drawn paths
The phone app runs a small web server on port 8080. A laptop on the same Wi-Fi network, or on the phone's hotspot, opens the address shown on the phone, for example http://<phone-ip>:8080/?k=1234. No installation and no internet connection are needed. Requests without the 4-digit key shown on the phone are refused, so other devices on the same network cannot drive the robot. The phone keeps the balance loop. The laptop only changes settings, sends START, STOP and GO, and watches. A Wi-Fi dropout therefore cannot make the robot fall.
| Laptop page tab | Content |
|---|---|
| Draw | Draw a path with the mouse on a 1, 2, 3 or 5 m floor grid; speed setting, GO, Stop path, live robot track |
| Live | θ, wheel command vs both encoders, and the P/I/D terms at 20 Hz |
| Tune | Every controller setting and the mode; Set upright; Save to robot |
| Runs | All saved runs with outcome, and a CSV download per run |
START and a large STOP button stay visible on every tab.
A drawing made on either screen goes through the same cleaning step. Points are clamped to the floor area, smoothed with a 5-point moving average, and resampled every 2 cm. The phone and the laptop always show the identical path, which is also exactly what the robot receives. The robot starts at the first point, facing up the drawing.

Figure 4. The laptop page. A 1 m square drawn with the mouse on the 2 m grid; 3.86 m long after corner smoothing. Green is the start, and the robot faces up. Captured with the earlier app build, before path following was added: GO still reads "soon", and the time estimate uses 0.2 m/s. The current build has GO, Stop path and a speed setting, with a 0.12 m/s default.

Figure 5. The same square on the phone's Draw tab, received from the laptop. The address for the laptop is shown under the status line (blurred here). Same earlier app build as Figure 4: the 0.2 m/s estimate and the note that GO "comes with the next firmware" predate the path-following build.
In testing, the square drawn on the laptop arrived on the phone exactly, spanning −0.5 m to +0.5 m on both axes and starting and ending at the same corner.
11. Step 8: Following the drawn path
Odometry. Board A integrates its position from both wheel encoders at 200 Hz, with wheel radius r = 51 mm and track width b = 160 mm:
$$ v = \tfrac{r}{2}(\omega_R + \omega_L), \qquad \dot\psi = \tfrac{r}{b}(\omega_R - \omega_L), \qquad \dot x = v\cos\psi,\ \ \dot y = v\sin\psi $$
Path upload. The phone sends the path to board A in pieces of 12 points, as millimetres relative to the start. A 1500-point path covers 30 m. The pieces alternate with tilt packets, so balancing never goes without a tilt sample. GO is accepted only while balancing, and only after every point has arrived.
Steering. The follower uses pure pursuit. It finds the nearest path point a little way ahead, aims at the point 0.15 m further along the line, and turns with curvature $2\sin\alpha / L$. When the target is more than about 57° off the heading, the robot stops and turns on the spot. Speed ramps gently, because a balancing robot must lean to speed up, and slows toward the end. The follower's output is the same drive and turn signal the joystick provides, so the balance controller is unchanged. Touching the joystick, pressing Stop path, or any stop of balancing ends the path.
| Setting | Value |
|---|---|
| Look-ahead | 0.15 m |
| Cruise speed | 0.12 m/s default, 0.25 m/s cap |
| Speed ramp | 0.15 m/s² |
| Max turn rate / ramp | 1.2 rad/s / 4 rad/s² |
| Turn on the spot when target is off by | > 57° |
| Finished when within | 3 cm of the last point |
The default speed is kept low because of the stall limit in Section 9. At 0.12 m/s the wheels turn at about 22 rpm, which leaves room for the balancing corrections on top.
Simulation. A Python twin of the follower (algorithm/path_follow.py) drives a kinematic robot with a 60 ms wheel lag and random wheel-speed wobble standing in for balancing. It checks the geometry and every sign. It does not model the balancing itself.
| Shape | Result | Time | Max distance from the line |
|---|---|---|---|
| Line, 1 m | Finished | 9 s | 10 mm |
| Square, 0.8 m | Finished | 27 s | 40 mm (corners rounded) |
| Circle, Ø 0.8 m | Finished | 22 s | 50 mm |
| Figure 8 | Finished | 29 s | 42 mm |
| Five-point star | Finished | 42 s | 40 mm |

Figure 6. Simulated path following at 0.12 m/s. Orange is the drawn path, and blue is the robot. Every shape finishes within 3 cm of its end point. Sharp corners are cut by up to about 4 cm.
This stage has not yet run on the robot. The first hardware tests planned are a straight line, then a gentle curve to the left. A curve that comes out mirrored would mean the left and right wheel labels are swapped, which is a one-line change.
12. Limits and next steps
| Limit | Next step |
|---|---|
| Both motors stall during hard catches (14 of 17 falls) | Log TMC2209 driver flags; check the 24 V supply's current capability; add encoder-based stall recovery |
| Simulator does not predict the real gains | Fit the body and motor model to the logged runs, then repeat the gain search |
| Controller relies mostly on damping (D 69–85 % of the output) | Re-tune once stalls are fixed; current tests show Kp 80 is worse than 60 |
| R (axle to centre of mass) is an estimate (60 mm) | Measure it on the assembled robot |
| Path following tested only in simulation | Flash board A and test a line, a curve, then drawn shapes |
| The phone app pauses when sent to the background | Keep the app open on the robot while balancing (already the case in use) |
13. What the application demonstrates
- Two CANStepper boards can act as a coordinated two-wheel drive. One board runs a 200 Hz controller and commands the other over a 1 Mbps CAN bus, while reading back both wheels' encoder speeds.
- A phone is a workable tilt sensor and user interface for a balancing robot. The measured round trip through Bluetooth is about 30 ms.
- A fault-isolation test on a single board (bus-off while alone on the bus) can separate a faulty board from wiring problems.
- Closed-loop direction settings must flip the encoder along with the motor, or the position loop runs away.
- Logging every try, with its exact settings, turned tuning from guesswork into measurement. The logs located the main failure: both motors stall at about 60–78 rpm. The gain values were not the cause.
- The same board and protocol can support higher-level behaviour: a path drawn on a laptop, converted to a path the robot can follow from its own odometry.