Holding Position
This step stops the drift. The balance loop holds whatever angle it's given; until now that was 0°, and any error in the balance point made the robot roll away. An outer loop now picks the angle from how fast the robot is moving and how far it is from where it started. Moving forward, it leans back to stop. Pushed away, it comes back.
Hardware: nothing new.
What you add
| File | What it does |
|---|---|
balance.c, balance.h | Changed: home is set when it takes over; target = −(kv × speed + kx × position), clipped to ±8°; the balance loop holds the target instead of 0° |
settings.c, settings.h | Changed: kv and kx, in EEPROM and on the console |
main.c | Changed: the display and the log show the target angle and the distance from home |
c
// The balance loop. The robot is an inverted pendulum on wheels: to stop it falling forward, the
// wheels must accelerate forward, under it. The loop sets a wheel acceleration from the tilt and
// how fast it's changing,
// acceleration = kp × angle + kd × rate
// and integrates it into the speed target for Step 8's wheel loop. The wheel loop makes the motors
// follow that speed whatever the battery voltage and friction, so kp and kd only have to deal with
// the pendulum.
#include "battery.h"
#include "balance.h"
#include "settings.h"
#include "tilt.h"
#include "wheel.h"
#define DT (1.0f / BALANCE_HZ)
static volatile int state;
static volatile float speed, target, position;
static float home;
static volatile uint32_t falls;
static uint32_t upright_ticks;
static float clip(float x, float lo, float hi) { return x < lo ? lo : x > hi ? hi : x; }
void balance_start(void)
{
upright_ticks = 0;
falls = 0;
state = BAL_WAIT;
}
void balance_stop(void)
{
state = BAL_OFF;
wheel_off();
}
static void give_up(void)
{
wheel_off();
upright_ticks = 0;
state = BAL_WAIT; // Pick it up again and it starts over
}
void balance_tick(void)
{
if (state == BAL_OFF) return;
float angle = tilt_angle();
if (!tilt_ok() || battery_state() == BATT_DEAD)
{
if (state == BAL_RUN) give_up();
return;
}
if (state == BAL_WAIT)
{
float a = angle < 0 ? -angle : angle;
upright_ticks = a < BALANCE_START_DEG ? upright_ticks + 1 : 0;
if (upright_ticks < BALANCE_START_MS * BALANCE_HZ / 1000) return;
speed = 0.0f;
home = (wheel_mm(WHEEL_L) + wheel_mm(WHEEL_R)) / 2; // Where it's held up is home
state = BAL_RUN;
}
if (angle > TILT_FALLEN || angle < -TILT_FALLEN)
{
falls++;
give_up();
return;
}
// The outer loop uses the speed command, not the measured speed: they're the same once the wheel
// loop has caught up, and the command has none of the encoder's 10 ms steps.
position = (wheel_mm(WHEEL_L) + wheel_mm(WHEEL_R)) / 2 - home;
target = clip(-(cfg.kv * speed + cfg.kx * position), -BALANCE_MAX_LEAN, BALANCE_MAX_LEAN);
float accel = cfg.kp * (angle - target) + cfg.kd * tilt_rate();
speed = clip(speed + accel * DT, -WHEEL_MAX_MMPS, WHEEL_MAX_MMPS);
wheel_speed(speed, speed);
}
int balance_state(void) { return state; }
float balance_speed(void) { return speed; }
float balance_target(void) { return target; }
float balance_position(void) { return position; }
uint32_t balance_falls(void) { return falls; }c
#pragma once
#include <stdint.h>
#define BALANCE_HZ 500 // balance_tick() rate: the tick's control slot
#define BALANCE_START_DEG 3.0f // Held this close to upright...
#define BALANCE_START_MS 300 // ...for this long, and it takes over
#define BALANCE_MAX_LEAN 8.0f // The position loop never asks for more lean than this
enum { BAL_OFF, BAL_WAIT, BAL_RUN };
void balance_start(void); // Waits until the robot is held upright, then balances
void balance_stop(void); // Motors off
void balance_tick(void); // From the tick: after the angle, before the wheel loop
int balance_state(void);
float balance_speed(void); // The wheel speed command, mm/s
float balance_target(void); // The lean the position loop asks for, degrees
float balance_position(void); // mm from where it started balancing, + forward
uint32_t balance_falls(void); // Times it went past TILT_FALLEN since balance_start()c
// The settings in EEPROM. The TM4C123 has 2 KB of it, in blocks of 16 words; the settings take
// the first block. Each word is written on its own: the EEPROM controller erases and programs it,
// and EEDONE says when it has finished.
#include <string.h>
#include "TM4C123.h"
#include "settings.h"
#define EEDONE_WORKING (1U << 0)
#define EESUPP_ERRORS ((1U << 2) | (1U << 3)) // ERETRY, PRETRY: the last erase or program failed
#define WORDS ((sizeof(struct settings) + 3) / 4)
struct settings cfg;
static const struct settings defaults = {
.version = SETTINGS_VERSION,
.gyro_bias = { 0, 0, 0 },
.calibrated = 0,
.level_deg = 0.0f,
.kp = 600.0f,
.kd = 60.0f,
.kv = 0.01f,
.kx = 0.005f,
};
const struct param params[] = {
{ "kp", &cfg.kp, "mm/s2 per deg" },
{ "kd", &cfg.kd, "mm/s2 per deg/s" },
{ "kv", &cfg.kv, "deg per mm/s" },
{ "kx", &cfg.kx, "deg per mm" },
};
const uint32_t n_params = sizeof params / sizeof params[0];
_Static_assert(sizeof(struct settings) <= 64, "settings must fit in one 16-word EEPROM block");
static int eeprom_init(void)
{
SYSCTL->RCGCEEPROM |= 1U;
while (!(SYSCTL->PREEPROM & 1U)) {}
while (EEPROM->EEDONE & EEDONE_WORKING) {} // Finishing anything a reset interrupted
return (EEPROM->EESUPP & EESUPP_ERRORS) ? -1 : 0;
}
void settings_load(void)
{
uint32_t words[WORDS];
cfg = defaults;
if (eeprom_init()) return;
EEPROM->EEBLOCK = 0;
EEPROM->EEOFFSET = 0;
for (uint32_t i = 0; i < WORDS; i++) words[i] = EEPROM->EERDWRINC; // The offset moves on by itself
struct settings stored;
memcpy(&stored, words, sizeof stored);
if (stored.version == SETTINGS_VERSION)
cfg = stored;
else if (stored.version >= 7 && stored.version < 100) // An older layout: the calibration is still where it was
{
for (int i = 0; i < 3; i++) cfg.gyro_bias[i] = stored.gyro_bias[i];
cfg.calibrated = stored.calibrated;
cfg.level_deg = stored.level_deg;
}
}
void settings_defaults(void)
{
struct settings keep = cfg;
cfg = defaults;
for (int i = 0; i < 3; i++) cfg.gyro_bias[i] = keep.gyro_bias[i];
cfg.calibrated = keep.calibrated;
cfg.level_deg = keep.level_deg;
}
int settings_save(void)
{
uint32_t words[WORDS] = { 0 };
cfg.version = SETTINGS_VERSION;
memcpy(words, &cfg, sizeof cfg);
EEPROM->EEBLOCK = 0;
EEPROM->EEOFFSET = 0;
for (uint32_t i = 0; i < WORDS; i++)
{
EEPROM->EERDWRINC = words[i];
while (EEPROM->EEDONE & EEDONE_WORKING) {} // About 0.1 ms per word, more when it erases
if (EEPROM->EEDONE) return -1; // Any other bit set: the write failed
}
return 0;
}c
#pragma once
#include <stdint.h>
// Everything the robot measures once and keeps: saved in the chip's EEPROM, loaded at boot.
// Change SETTINGS_VERSION whenever the struct changes: a stored copy with another version is
// ignored and the defaults are used instead, except for the calibration: add new fields at the end,
// so the first four never move.
#define SETTINGS_VERSION 11
struct settings
{
uint32_t version;
int16_t gyro_bias[3]; // Gyro reading at rest, counts, x y z
int16_t calibrated; // 1 once Calibrate has run
float level_deg; // Accelerometer angle at the balance point
float kp; // Balance: mm/s² of wheel acceleration per degree of tilt
float kd; // Balance: mm/s² per degree per second
float kv; // Position: degrees of lean per mm/s of speed
float kx; // Position: degrees of lean per mm away from home
};
extern struct settings cfg;
// The settings the console can show and change, by name
struct param
{
const char *name;
float *value;
const char *unit;
};
extern const struct param params[];
extern const uint32_t n_params;
void settings_load(void); // The stored copy, or the defaults
void settings_defaults(void); // Back to the defaults, keeping the calibration
int settings_save(void); // 0 = writtenc
// The robot's main program. Each step fills in a mode. Balance stands the robot up when you hold it
// upright and keeps it where it started, with the serial console for tuning. 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 "balance.h"
#include "battery.h"
#include "clock.h"
#include "console.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();
}
static const char *const bal_name[] = { "off", "WAIT: hold upright", "BALANCING" };
static void oled_balance(void)
{
uint32_t mv = battery_mv();
long a = CENTI(tilt_angle());
oled_printf(0, "BALANCE %lu.%02luV", mv / 1000, mv % 1000 / 10);
oled_text(1, bal_name[balance_state()]);
oled_printf(3, "angle %s%ld.%02ld", WHOLE(a));
long t = CENTI(balance_target());
oled_printf(2, "target %s%ld.%02ld", WHOLE(t));
oled_printf(4, "speed %5ld mm/s", (long)balance_speed());
oled_printf(5, "from home %5ld mm", (long)balance_position());
oled_printf(6, "falls %lu", (unsigned long)balance_falls());
oled_bar(7, (int32_t)tilt_angle(), 15);
oled_flush();
}
// Until SW2: balance whenever it's held upright. The console changes the gains as it runs.
static void balance_mode(void)
{
if (!have_imu || !cfg.calibrated)
{
printf("needs the IMU and a Calibrate first\n");
return;
}
printf("hold it upright and let go when it takes over. Console: list, kp 650, save, log\n");
printf("# log: ms, angle x0.01 deg, target x0.01 deg, rate x0.1 deg/s, speed cmd mm/s, position mm\n");
balance_start();
uint32_t next_log = millis();
while (!button_pressed(BTN_SW2))
{
console_poll();
int running = balance_state() == BAL_RUN;
led_set(running || millis() / 250 % 2 ? LED_GREEN : LED_OFF);
if (have_oled && !oled_busy()) oled_balance();
if ((int32_t)(millis() - next_log) < 0) continue;
next_log += 20; // 50 Hz
if (console_logging())
printf("%lu,%ld,%ld,%ld,%ld,%ld\n", (unsigned long)millis(), CENTI(tilt_angle()),
CENTI(balance_target()), (long)(tilt_rate() * 10.0f), (long)balance_speed(),
(long)balance_position());
}
balance_stop();
}
// 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_BALANCE)
balance_mode();
else 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
- Lean back to stop. To brake, the robot has to lean back first, and to lean back the wheels must first speed up under it. So a robot moving forward is asked for a negative angle, and its first reaction is to accelerate. It looks wrong in the log and it's right.
- Speed command, not measured speed. The outer loop uses the speed the balance loop asked for. Once the wheel loop has caught up they're the same, and the command is smooth, where the measured speed moves in 61 mm/s steps. Position comes from the encoders, accurate to a count.
- The lean limit.
BALANCE_MAX_LEANkeeps the outer loop from asking for an angle the robot can't come back from. A hard push saturates it: the robot rolls with the push, then comes back at the limit's pace. - The balance point sorts itself out. If the calibration is a degree off, the robot drifts, the position error grows, and the target settles a degree the other way. The angle in the log shows exactly how far off Calibrate was.
- Slow outer, fast inner. The outer loop has to be several times slower than the balance loop, or the two fight.
kv0.01 andkx0.005 are gentle: 100 mm/s asks for 1° of lean, 100 mm away for 0.5°.
Test
- Balance mode,
logon. Let it take over and let go: it stays within 20 mm of where it started for a minute. - Push it 10 cm by the top plate and hold it there: it leans against your hand. Let go: it rolls back to within 20 mm of home and stops without overshooting by more than about 5 cm.
- Tune with the log:
- It comes back but swings past home several times: raise
kv(more braking). - It comes back too slowly, or still drifts: raise
kx. - It rocks back and forth slowly, about once a second, more each time: both are too high; halve them.
save.
- It comes back but swings past home several times: raise
- Read
targetin the log while it holds still: that steady angle is how far off the balance point from Calibrate was. - Push it hard: it rolls, the target sits at ±8°, and it comes back without falling.
- Put it on a gentle slope: it holds position, leaning slightly uphill.