Standing Up
This step makes the robot stand. The balance loop runs in the tick at 500 Hz, right after the angle: if the robot leans forward, the wheels accelerate forward to get back under it. The output is a wheel speed for Step 8's loop, so the gains don't change with the battery or the motors. A serial console sets the gains while the robot balances and saves them to EEPROM. The robot will stand but wander: holding its position is Step 11.
Hardware: nothing new. A soft floor or a rug for the first tries.
What you add
| File | What it does |
|---|---|
balance.c, balance.h | The balance loop: waits until the robot is held upright, then wheel acceleration = kp × angle + kd × rate, integrated into a speed; gives up past 45°, on a dead battery or a silent IMU |
console.c, console.h | Commands from the serial terminal: list, kp 650, save, defaults, log |
settings.c, settings.h | Changed: kp and kd join the calibration in EEPROM, with a table of names for the console |
uart.c, uart.h | Changed: uart_getc(), without waiting |
tick.c | Changed: balance_tick() between the angle and the wheel loop |
main.c | Changed: Balance mode, with the display, the LED and a 50 Hz CSV log |
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;
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;
state = BAL_RUN;
}
if (angle > TILT_FALLEN || angle < -TILT_FALLEN)
{
falls++;
give_up();
return;
}
float accel = cfg.kp * angle + 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; }
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
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
uint32_t balance_falls(void); // Times it went past TILT_FALLEN since balance_start()c
// The serial console: change the balance gains while the robot runs, without rebuilding. Characters
// are collected into a line; Enter runs it. Nothing here blocks, so main() can poll it in its loop.
#include <stdio.h>
#include <string.h>
#include "console.h"
#include "settings.h"
#include "uart.h"
#define LINE_MAX 32
static char line[LINE_MAX];
static uint32_t len;
static int logging;
void print_fixed(float x, int decimals)
{
int32_t scale = 1;
for (int i = 0; i < decimals; i++) scale *= 10;
int32_t v = (int32_t)(x * scale + (x < 0 ? -0.5f : 0.5f));
if (v < 0) { putchar('-'); v = -v; }
printf("%ld", (long)(v / scale));
if (decimals) printf(".%0*ld", decimals, (long)(v % scale));
}
// A decimal number like -12.5. No exponents; 0 = parsed.
static int parse_float(const char *s, float *out)
{
float sign = 1.0f, v = 0.0f, place = 0.0f;
int digits = 0;
if (*s == '-') { sign = -1.0f; s++; }
for (; *s; s++)
{
if (*s == '.' && place == 0.0f) place = 1.0f;
else if (*s >= '0' && *s <= '9')
{
if (place == 0.0f) v = v * 10.0f + (*s - '0');
else { place *= 0.1f; v += (*s - '0') * place; }
digits++;
}
else return -1;
}
if (!digits) return -1;
*out = sign * v;
return 0;
}
static void list(void)
{
for (uint32_t i = 0; i < n_params; i++)
{
printf("%-4s ", params[i].name);
print_fixed(*params[i].value, 3);
printf(" %s\n", params[i].unit);
}
}
static void run(char *cmd)
{
char *arg = strchr(cmd, ' ');
if (arg) *arg++ = '\0';
if (!strcmp(cmd, "list")) { list(); return; }
if (!strcmp(cmd, "save")) { printf(settings_save() ? "EEPROM write failed\n" : "saved\n"); return; }
if (!strcmp(cmd, "defaults")) { settings_defaults(); list(); return; }
if (!strcmp(cmd, "log")) { logging = !logging; printf("log %s\n", logging ? "on" : "off"); return; }
for (uint32_t i = 0; i < n_params; i++)
{
if (strcmp(cmd, params[i].name)) continue;
float v;
if (arg && parse_float(arg, &v) == 0) *params[i].value = v; // One 32-bit store: the tick sees old or new
printf("%s ", params[i].name);
print_fixed(*params[i].value, 3);
printf("\n");
return;
}
printf("? list, <name> <value>, save, defaults, log\n");
}
void console_poll(void)
{
int c;
while ((c = uart_getc()) >= 0)
{
if (c == '\r' || c == '\n')
{
if (!len) continue;
line[len] = '\0';
len = 0;
putchar('\n');
run(line);
}
else if ((c == '\b' || c == 0x7F) && len)
{
len--;
printf("\b \b");
}
else if (c >= ' ' && c < 0x7F && len < LINE_MAX - 1)
{
line[len++] = (char)c;
putchar(c); // Echo, so you see what you type
}
}
}
int console_logging(void) { return logging; }c
#pragma once
#include <stdint.h>
// Commands typed into the serial terminal, one per line:
// list every setting and its value
// kp 650 change a setting (it takes effect at once)
// save write the settings to EEPROM
// defaults every setting back to its default, calibration kept
// log start or stop the 50 Hz CSV log
void console_poll(void); // Reads what has arrived; runs a command when a line is complete
int console_logging(void); // 1 while the log is on
void print_fixed(float x, int decimals);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,
};
const struct param params[] = {
{ "kp", &cfg.kp, "mm/s2 per deg" },
{ "kd", &cfg.kd, "mm/s2 per deg/s" },
};
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 10
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
};
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
// UART0 to the LaunchPad's USB serial port, printf on top of it, and the console's input
#include <stdio.h>
#include <sys/stat.h>
#include "TM4C123.h"
#include "clock.h"
#include "uart.h"
#define RCGC_UART0 (1U << 0)
#define RCGC_GPIOA (1U << 0)
#define U0RX (1U << 0) // PA0
#define U0TX (1U << 1) // PA1
#define PCTL_PA01_M 0xFFU
#define PCTL_PA01_U0 0x11U // Function 1 on PA0 and PA1: U0RX, U0TX
#define BAUD 115200U
#define BRD_X64 ((CPU_HZ * 4U + BAUD / 2) / BAUD) // 64 * CPU_HZ / (16 * BAUD), rounded
#define CTL_UARTEN (1U << 0)
#define CTL_TXE (1U << 8)
#define CTL_RXE (1U << 9)
#define LCRH_FEN (1U << 4)
#define LCRH_WLEN_8 (0x3U << 5)
#define FR_RXFE (1U << 4)
#define FR_TXFF (1U << 5)
void uart_init(void)
{
SYSCTL->RCGCUART |= RCGC_UART0;
SYSCTL->RCGCGPIO |= RCGC_GPIOA;
while ((SYSCTL->PRGPIO & RCGC_GPIOA) == 0) {}
while ((SYSCTL->PRUART & RCGC_UART0) == 0) {}
GPIOA->AFSEL |= U0RX | U0TX;
GPIOA->PCTL = (GPIOA->PCTL & ~PCTL_PA01_M) | PCTL_PA01_U0;
GPIOA->DEN |= U0RX | U0TX;
UART0->CTL = 0; // Off while it's set up
UART0->IBRD = BRD_X64 / 64; // 80 MHz: 43
UART0->FBRD = BRD_X64 % 64; // 26 (43.406 vs 43.403: 0.008% off)
UART0->LCRH = LCRH_WLEN_8 | LCRH_FEN; // Writing LCRH latches the divisor
UART0->CC = 0; // Clocked from the system clock
UART0->CTL = CTL_UARTEN | CTL_TXE | CTL_RXE;
setvbuf(stdout, NULL, _IONBF, 0); // printf sends at once, no buffer to flush
}
void uart_putc(char c)
{
while (UART0->FR & FR_TXFF) {} // 16-byte FIFO: waits only when it's full
UART0->DR = c;
}
// The next received character, or -1 if none has come in. The 16-byte FIFO holds a line typed
// between two calls; main() calls this every pass.
int uart_getc(void)
{
if (UART0->FR & FR_RXFE) return -1;
return (int)(UART0->DR & 0xFF);
}
// newlib calls this for printf and puts. "\n" goes out as "\r\n" for terminals.
int _write(int fd, const char *buf, int len)
{
(void)fd;
for (int i = 0; i < len; i++)
{
if (buf[i] == '\n') uart_putc('\r');
uart_putc(buf[i]);
}
return len;
}
// The rest of the calls newlib's stdio makes. There is no file system: only stdout.
int _close(int fd) { (void)fd; return -1; }
int _read(int fd, char *buf, int len) { (void)fd; (void)buf; (void)len; return 0; }
int _lseek(int fd, int off, int whence) { (void)fd; (void)off; (void)whence; return 0; }
int _isatty(int fd) { (void)fd; return 1; }
int _fstat(int fd, struct stat *st) { (void)fd; st->st_mode = S_IFCHR; return 0; }c
#pragma once
#include <stdint.h>
void uart_init(void); // UART0 on PA0/PA1, 115200 8N1, through the debug USB port
void uart_putc(char c);
int uart_getc(void); // -1 if nothing has arrivedc
// 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 balance loop and 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 "balance.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();
}
balance_tick();
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. Balance stands the robot up when you hold it
// upright, 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));
oled_printf(4, "speed %5ld mm/s", (long)balance_speed());
oled_printf(5, "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, rate x0.1 deg/s, speed cmd mm/s, left mm/s, right mm/s\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()),
(long)(tilt_rate() * 10.0f), (long)balance_speed(),
(long)wheel_mmps(WHEEL_L), (long)wheel_mmps(WHEEL_R));
}
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
- Why acceleration. A pendulum on a cart is steered by the cart's acceleration: leaning at angle θ, it needs the wheels to accelerate at about g × tan θ just to stop tipping further. g is 9810 mm/s², 171 mm/s² per degree, so
kphas to be well above 171 or the robot can't catch any fall.kddamps it: without it the robot overshoots and swings around upright faster and faster. - The starting gains (
kp600,kd60) balanced a simulated robot with L from 50 to 180 mm and a wheel loop that settles in 20 ms. Your robot will differ; they're a place to start, not an answer. - Starting and stopping. Balance mode waits until the angle has stayed within 3° of upright for 300 ms, so you lift the robot off its kickstand, hold it upright and feel it take over. Past 45° it cuts the motors and waits to be picked up again. It also stops on a dead battery or an IMU that has stopped answering.
- Live tuning. A gain changes in one 32-bit store, so the tick sees the old value or the new one, never half of each. Type
kp 700while it balances and see the difference at once;savewhen you like it. - The log.
logprints a CSV line every 20 ms: time, angle, rate, speed command and both wheel speeds. Paste it into a spreadsheet or a serial plotter to see an oscillation's frequency instead of guessing.
Test
- Battery on, robot on its kickstand, Balance mode. The LED blinks green, the display says
WAIT: hold upright. - Lift it upright by the top plate: the LED goes solid and the wheels move under it. Hold it loosely and let it push against your fingers before you let go.
- Tune, in this order, with
logon:- It falls over slowly, the wheels too lazy to catch it: raise
kpby 100. - It shakes fast (10 Hz or more), wheels buzzing back and forth: lower
kd, or the wheel loop'sWHEEL_KP. - It swings back and forth a few times a second, more each time: raise
kdby 10. - It stands, rocking gently: done.
save.
- It falls over slowly, the wheels too lazy to catch it: raise
- It stands for 30 seconds, drifting slowly in one direction. Note which way: that's the balance point being slightly off, and Step 11 removes it.
- Push it gently at the top: it rolls a little, catches itself and stays up.
- Tip it past 45°: the motors stop at once and the display counts a fall. Pick it up again: it takes over again.