Wheel Speed
This step makes the wheels go at a commanded speed instead of a commanded voltage. Two motors on the same voltage never turn at the same speed, and a motor slows down under load and as the battery drains. A loop per wheel fixes that: a feed-forward voltage from the speed you ask for, plus a PI correction from the encoder. The balance loop in Step 10 then gives wheel speeds and can count on getting them.
Hardware: nothing new. Wheels in the air for the tests.
Fill in the feed-forward
From Step 5's Test, step 4, you have each wheel's speed in counts per second at 3 V and at 6 V. Turn them into mm/s (multiply by π × diameter / counts per turn, or read them off this step's Test), average the two wheels, then:
| Define | Value |
|---|---|
WHEEL_KV | (6000 − 3000) / (speed at 6 V − speed at 3 V), in mV per mm/s |
WHEEL_KS | 3000 − WHEEL_KV × speed at 3 V, in mV: the voltage it takes before the wheel moves at all |
WHEEL_MAX_MMPS | About 80% of the speed at 6 V, so the loop always has some voltage left |
What you add
| File | What it does |
|---|---|
wheel.c, wheel.h | The speed loop: feed-forward, P on the speed error, I on the position error, anti-windup, and the measured speed and distance in mm |
tick.c | Changed: the control slot runs wheel_tick() after the angle |
main.c | Changed: the motor check gets speed lines, and Test shows each wheel's mm/s and the loop's mV |
c
// Wheel speed control. Each wheel gets a feed-forward voltage from its target speed (what the
// motor needs at that speed with no load) plus a PI correction for what the feed-forward misses:
// load, friction, a weaker motor. The I term integrates the speed error, which is the same as the
// distance the wheel is behind where it should be. So it uses the encoder count itself, which has
// none of the 10 ms speed estimate's coarse steps.
#include "TM4C123.h"
#include "motor.h"
#include "wheel.h"
#define DT (1.0f / WHEEL_HZ)
#define ERR_MAX_MM (MOTOR_MAX_MV / WHEEL_KI) // Anti-windup: the I term alone can't pass full voltage
struct wheel
{
volatile float target; // mm/s
float target_mm; // Where the wheel should be by now
int32_t mv;
};
static struct wheel w[2];
static volatile int on, starting;
static float clip(float x, float lo, float hi) { return x < lo ? lo : x > hi ? hi : x; }
void wheel_speed(float left_mmps, float right_mmps)
{
w[WHEEL_L].target = clip(left_mmps, -WHEEL_MAX_MMPS, WHEEL_MAX_MMPS);
w[WHEEL_R].target = clip(right_mmps, -WHEEL_MAX_MMPS, WHEEL_MAX_MMPS);
if (!on)
{
starting = 1; // The tick zeroes the integrators before the first step
on = 1;
}
}
void wheel_off(void)
{
__disable_irq(); // So a tick half way through wheel_tick() can't start the motors again
on = 0;
__enable_irq();
motor_stop();
w[WHEEL_L].mv = w[WHEEL_R].mv = 0;
}
float wheel_mmps(int wheel) { return encoder_speed(wheel) * MM_PER_COUNT; }
float wheel_mm(int wheel) { return encoder_count(wheel) * MM_PER_COUNT; }
int32_t wheel_mv(int wheel) { return w[wheel].mv; }
static int32_t step(int i)
{
struct wheel *s = &w[i];
float target = s->target, pos = wheel_mm(i);
if (starting) s->target_mm = pos;
s->target_mm += target * DT;
float err_mm = s->target_mm - pos;
if (err_mm > ERR_MAX_MM) { err_mm = ERR_MAX_MM; s->target_mm = pos + err_mm; }
if (err_mm < -ERR_MAX_MM) { err_mm = -ERR_MAX_MM; s->target_mm = pos + err_mm; }
float u = WHEEL_KV * target
+ WHEEL_KS * clip(target / 50.0f, -1.0f, 1.0f) // Full friction push from 50 mm/s up
+ WHEEL_KP * (target - wheel_mmps(i))
+ WHEEL_KI * err_mm;
s->mv = (int32_t)clip(u, -MOTOR_MAX_MV, MOTOR_MAX_MV);
return s->mv;
}
void wheel_tick(void)
{
if (!on) return;
int32_t left = step(WHEEL_L), right = step(WHEEL_R);
starting = 0;
motor_volts(left, right); // Also keeps the dead-man happy
}c
#pragma once
#include <stdint.h>
#include "encoder.h"
#define WHEEL_HZ 500 // wheel_tick() rate: the tick's control slot
#define MM_PER_COUNT (3.14159265f * WHEEL_DIAMETER_MM / ENC_COUNTS_PER_REV)
#define WHEEL_MAX_MMPS 1200.0f // Targets are clipped to this: keep it below the motors' top speed
// Feed-forward, from the speeds you measured at 3 V and 6 V in Step 5 (see Notes)
#define WHEEL_KV 4.0f // mV per mm/s
#define WHEEL_KS 300.0f // mV just to get the wheel turning (friction)
// Feedback
#define WHEEL_KP 2.0f // mV per mm/s of speed error
#define WHEEL_KI 40.0f // mV per mm of position error: the integral of the speed error
void wheel_speed(float left_mmps, float right_mmps); // Target speeds; the loop starts if it was off
void wheel_off(void); // Loop off, both motors coasting
void wheel_tick(void); // From the tick's control slot
float wheel_mmps(int wheel); // Measured speed
float wheel_mm(int wheel); // Distance since boot
int32_t wheel_mv(int wheel); // The loop's last command to the motorc
// The 1 kHz system tick. Everything periodic runs from SysTick_Handler: buttons, the battery, the
// motors' dead-man and the encoders every 1 ms. Once it owns the I2C bus, odd ticks read the IMU and
// update the tilt angle, then run the wheel speed loop (500 Hz); even ticks send a piece of the
// display's frame. Only the tick
// uses the bus from then on, so two transfers can never overlap.
#include "TM4C123.h"
#include "battery.h"
#include "clock.h"
#include "cycles.h"
#include "encoder.h"
#include "imu.h"
#include "motor.h"
#include "oled.h"
#include "tick.h"
#include "tilt.h"
#include "ui.h"
#include "wheel.h"
#define STCTRL_ENABLE (1U << 0)
#define STCTRL_INTEN (1U << 1)
#define STCTRL_CLKSRC (1U << 2)
static volatile uint32_t ms;
static volatile uint32_t cost_last, cost_max;
static volatile int bus, read_imu;
void tick_init(void)
{
cycles_init();
SysTick->CTRL = 0;
SysTick->LOAD = CPU_HZ / TICK_HZ - 1;
SysTick->VAL = 0;
SysTick->CTRL = STCTRL_CLKSRC | STCTRL_INTEN | STCTRL_ENABLE;
}
void tick_bus_start(int with_imu)
{
oled_async();
read_imu = with_imu;
bus = 1;
}
// 500 Hz: the IMU, then everything that runs on the angle
static void control(void)
{
if (read_imu)
{
struct imu_raw r;
if (imu_read(&r) == 0)
tilt_update(&r);
else
tilt_read_failed();
}
wheel_tick();
}
void SysTick_Handler(void)
{
uint32_t start = cycles();
ms++;
ui_tick();
battery_tick();
motor_tick();
encoder_tick();
if (bus)
{
if (ms & 1) control();
else oled_tick();
}
uint32_t cost = cycles() - start;
cost_last = cost;
if (cost > cost_max) cost_max = cost;
}
uint32_t millis(void) { return ms; }
void delay_ms(uint32_t n)
{
uint32_t start = ms;
while (ms - start < n) {}
}
uint32_t tick_cycles_last(void) { return cost_last; }
uint32_t tick_cycles_max(void)
{
uint32_t m = cost_max;
cost_max = 0;
return m;
}c
// The robot's main program. Each step fills in a mode. Calibrate measures the gyro's offsets and the
// balance point and saves them; Test shows the battery, wheels and tilt angle on the serial log and
// the display, and SW1 steps the motors through a check: fixed voltages, then the speed loop.
#include <stdio.h>
#include <stdlib.h>
#include "TM4C123.h"
#include "battery.h"
#include "clock.h"
#include "encoder.h"
#include "i2c.h"
#include "imu.h"
#include "motor.h"
#include "oled.h"
#include "settings.h"
#include "tick.h"
#include "tilt.h"
#include "uart.h"
#include "ui.h"
#include "wheel.h"
enum { MODE_BALANCE, MODE_DRIVE, MODE_CALIBRATE, MODE_TEST, N_MODES };
static const uint32_t mode_colour[N_MODES] = { LED_GREEN, LED_BLUE, LED_YELLOW, LED_MAGENTA };
static const char *const mode_name[N_MODES] = { "balance", "drive", "calibrate", "test" };
static const char *const batt_name[] = { "usb", "ok", "LOW", "DEAD" };
static int have_oled, have_imu;
// Fixed-point printing: newlib-nano's printf has no %f
#define CENTI(x) ((long)((x) * 100.0f))
#define WHOLE(c) ((c) < 0 ? "-" : ""), (labs(c) / 100), (labs(c) % 100) // For "%s%ld.%02ld"
static void print_battery(void)
{
uint32_t mv = battery_mv();
printf("bat %lu.%02lu V %s", mv / 1000, mv % 1000 / 10, batt_name[battery_state()]);
}
// A message on the display: up to three lines, the rest blank
static void show(const char *a, const char *b, const char *c)
{
if (!have_oled) return;
oled_clear();
oled_text(0, a);
if (b) oled_text(2, b);
if (c) oled_text(4, c);
oled_flush();
}
// Test's motor check: SW1 moves to the next line. Wheels off the ground. The first lines set
// voltages; the speed lines give the speed loop a target in mm/s.
enum { VOLTS, SPEED };
static const struct { const char *name; int kind; int32_t left, right; } motor_check[] = {
{ "motors off", VOLTS, 0, 0 },
{ "left 3 V", VOLTS, 3000, 0 },
{ "left -3 V", VOLTS, -3000, 0 },
{ "right 3 V", VOLTS, 0, 3000 },
{ "right -3 V", VOLTS, 0, -3000 },
{ "both 3 V", VOLTS, 3000, 3000 },
{ "both 6 V", VOLTS, 6000, 6000 },
{ "speed 0", SPEED, 0, 0 },
{ "speed 300 mm/s", SPEED, 300, 300 },
{ "speed 800 mm/s", SPEED, 800, 800 },
{ "speed -800 mm/s", SPEED, -800, -800 },
{ "spin 300/-300", SPEED, 300, -300 },
};
#define N_CHECKS (sizeof motor_check / sizeof motor_check[0])
static void oled_status(uint32_t check)
{
uint32_t mv = battery_mv();
long a = CENTI(tilt_angle()), w = CENTI(tilt_rate());
oled_printf(0, "TEST %lu.%02luV %s", mv / 1000, mv % 1000 / 10, batt_name[battery_state()]);
oled_text(1, motor_check[check].name);
oled_printf(2, "L%5ld R%5ld mm/s", (long)wheel_mmps(WHEEL_L), (long)wheel_mmps(WHEEL_R));
oled_printf(3, "L%5ld R%5ld mV", (long)wheel_mv(WHEEL_L), (long)wheel_mv(WHEEL_R));
if (!have_imu) oled_text(4, "no IMU");
else if (!tilt_ok()) oled_text(4, "IMU not answering");
else
{
oled_printf(4, "angle %s%ld.%02ld deg", WHOLE(a));
oled_printf(5, "rate %s%ld.%02ld deg/s", WHOLE(w));
}
oled_bar(7, (int32_t)tilt_angle(), 45);
oled_flush();
}
// Until SW2: the motor check, the display when it's free, the serial log twice a second
static void test_status(void)
{
uint32_t next_log = millis(), check = 0;
printf("%s (SW1: next)\n", motor_check[check].name);
while (!button_pressed(BTN_SW2))
{
if (button_pressed(BTN_SW1))
{
check = (check + 1) % N_CHECKS;
printf("%s\n", motor_check[check].name);
}
if (motor_check[check].kind == SPEED)
wheel_speed(motor_check[check].left, motor_check[check].right);
else
{
wheel_off();
motor_volts(motor_check[check].left, motor_check[check].right); // Every pass: the dead-man
}
if (have_oled && !oled_busy()) oled_status(check);
if ((int32_t)(millis() - next_log) < 0) continue;
next_log += 500;
uint32_t max = tick_cycles_max();
long a = CENTI(tilt_angle()), w = CENTI(tilt_rate());
print_battery();
printf(" tick %lu.%02lu%%", max * 100 / 80000, max * 10000 / 80000 % 100);
for (int wh = WHEEL_L; wh <= WHEEL_R; wh++)
printf(" %c: %ld mm %ld mm/s %ld mV err %lu", wh == WHEEL_L ? 'L' : 'R',
(long)wheel_mm(wh), (long)wheel_mmps(wh), (long)wheel_mv(wh),
(unsigned long)encoder_errors(wh));
printf("\n angle %s%ld.%02ld deg rate %s%ld.%02ld deg/s imu err %lu\n",
WHOLE(a), WHOLE(w), (unsigned long)tilt_errors());
}
wheel_off();
}
// Wait for SW1 (go on) or SW2 (give up)
static int wait_sw1(void)
{
while (1)
{
if (button_pressed(BTN_SW1)) return 1;
if (button_pressed(BTN_SW2)) return 0;
}
}
// Calibrate: the gyro's readings at rest, then the accelerometer angle at the balance point
static void calibrate(void)
{
int16_t gyro[3];
float accel;
if (!have_imu)
{
printf("no IMU\n");
return;
}
printf("lay the robot down, still, and press SW1\n");
show("CALIBRATE", "1. lay it down still", " then SW1");
if (!wait_sw1()) return;
delay_ms(500); // Let go of it first
tilt_average_start(TILT_HZ); // One second
while (!tilt_average_done()) {}
tilt_average_result(gyro, &accel);
printf("gyro at rest: %d %d %d counts\n", gyro[0], gyro[1], gyro[2]);
printf("hold the robot upright at its balance point and press SW1\n");
show("CALIBRATE", "2. hold it upright,", " balanced, SW1");
if (!wait_sw1()) return;
int16_t unused[3];
tilt_average_start(TILT_HZ);
while (!tilt_average_done()) {}
tilt_average_result(unused, &accel);
long l = CENTI(accel);
printf("balance point: %s%ld.%02ld deg\n", WHOLE(l));
for (int i = 0; i < 3; i++) cfg.gyro_bias[i] = gyro[i];
cfg.level_deg = accel;
cfg.calibrated = 1;
int err = settings_save();
printf("%s\n", err ? "EEPROM write failed" : "saved");
show("CALIBRATE", err ? "EEPROM write failed" : "saved", "SW2: menu");
while (!button_pressed(BTN_SW2)) {}
}
// A dead battery: three seconds of red, then back to the menu
static void refuse(void)
{
printf("refused: ");
print_battery();
printf(", charge it\n");
for (int i = 0; i < 6; i++)
{
led_set(i % 2 ? LED_OFF : LED_RED);
delay_ms(500);
}
}
static void run(uint32_t mode)
{
// Test and Calibrate still run on a dead battery: they don't need the motors
if (mode < MODE_CALIBRATE && battery_state() == BATT_DEAD)
{
refuse();
return;
}
printf("mode: %s\n", mode_name[mode]);
if (battery_state() == BATT_LOW) printf("battery low: charge it after this run\n");
show(mode_name[mode], 0, 0);
if (mode == MODE_TEST)
test_status();
else if (mode == MODE_CALIBRATE)
calibrate();
else
while (!button_pressed(BTN_SW2)) {} // Not written yet
printf("menu\n");
show("menu", 0, 0);
}
// Every address that answers: 3c is the display, 68 the IMU
static void i2c_scan(void)
{
printf("i2c:");
for (uint8_t a = 0x08; a < 0x78; a++)
if (i2c_probe(a) == 0) printf(" %02x", a);
printf("\n");
}
int main(void)
{
clock_init();
uart_init();
ui_init();
settings_load();
battery_init(); // Before the tick, which reads it
motor_init();
encoder_init();
tick_init();
i2c_init();
printf("\nbalance-bot: %lu MHz, built " __DATE__ " " __TIME__ "\n", (unsigned long)(CPU_HZ / 1000000));
print_battery();
printf("\n");
// After the tick: imu_init() waits with delay_ms(). Before the tick takes the bus.
i2c_scan();
have_oled = oled_init() == 0;
have_imu = imu_init() == 0;
printf("display: %s\n", have_oled ? "ok" : "not found");
if (have_imu) printf("imu: WHO_AM_I %02x%s\n", imu_id(), imu_id() == 0x68 ? "" : " (not an MPU-6050: check the ranges)");
else printf("imu: not found\n");
if (!cfg.calibrated) printf("not calibrated: run Calibrate\n");
tick_bus_start(have_imu);
show("balance-bot", have_imu ? "imu ok" : "imu not found", cfg.calibrated ? "menu" : "run Calibrate");
uint32_t mode = MODE_BALANCE;
while (1)
{
mode = ui_menu(mode_colour, N_MODES, mode);
run(mode);
}
}Notes
- Feed-forward does most of the work. A DC motor's speed is close to proportional to its voltage minus a friction offset. With
WHEEL_KVandWHEEL_KSright, the feed-forward alone gets within 10% of the target, at once and with no delay. The PI only has to fix the rest, so it can stay gentle. - I on position, not on speed. The speed estimate moves in steps of one count per 10 ms: 61 mm/s with 360 counts per turn and 70 mm wheels. Integrating that speed error is the same as comparing where the wheel is with where it should be, so the I term uses the encoder count directly, accurate to one count (0.6 mm).
- The P term is small on purpose. It works on the stepped speed estimate, so a big
WHEEL_KPturns those steps into motor noise. Raise it until the wheel hums under load, then halve it. - Anti-windup. If a wheel is held, the position error would grow without limit and the wheel would jump when let go. The error is clipped at the size where the I term alone gives full voltage, and the target position is pulled along with it.
- The friction term fades in.
WHEEL_KSis applied in full from 50 mm/s up and scaled down below, so a target near 0 doesn't flip the motor between +300 and −300 mV. That matters in Step 10, where the target crosses zero all the time.
Test
- Fill in
WHEEL_KVandWHEEL_KS. Battery on, wheels in the air, Test mode. - Step to
speed 300 mm/s: both wheels settle within ±30 mm/s of 300 in under half a second, and the two mV readings differ: that's the loop making up for the weaker motor. - Hold one wheel with your fingers, gently: its mV goes up and the speed stays near 300. Let go: no jump.
speed 800 mm/sandspeed -800 mm/s: the same, in both directions.spin 300/-300: one each way.- Leave it on
speed 300 mm/sfor 10 seconds: the twommcounts in the serial log grow by 3000 and stay within a few mm of each other. - Back at
speed 0: the wheels hold still and resist being turned by hand, then creep back to where they were.