Driving
This step lets you drive the robot. The position loop from Step 11 already holds the robot to a point; driving moves that point along at the drive speed, ramped so the robot leans into the start and out of the stop. A steering loop splits the wheel speeds to turn at the rate you ask for, checked against the gyro. Keys come in from a phone or laptop over an HC-05 Bluetooth module on UART1.
Hardware: the HC-05 module, four wires from the carrier board.
Wire it
| HC-05 | To |
|---|---|
VCC | 5 V from the buck (the module has its own 3.3 V regulator) |
GND | Ground |
TXD | PB0 (U1RX). Its output is 3.3 V |
RXD | PB1 (U1TX) |
EN, STATE | Not connected |
Pair your phone or laptop with it (PIN 1234 on most modules) and open a Bluetooth serial terminal. On a phone, give the app's buttons the keys below. iPhones don't support the HC-05's classic Bluetooth: use a laptop, or an Android phone.
What you add
| File | What it does |
|---|---|
bt.c, bt.h | UART1 on PB0/PB1 at 9600 baud, the HC-05's default |
drive.c, drive.h | Keys to drive speed and turn rate: w a s d, q e, x stops. Each lasts 500 ms |
balance.c, balance.h | Changed: balance_drive(), a ramped drive speed that moves home along, a limit on how far home can be left behind, and steering |
tilt.c, tilt.h | Changed: the yaw rate from the gyro's vertical axis |
settings.c, settings.h | Changed: ky, vmax and wmax |
main.c | Changed: Drive mode, which is Balance mode plus the Bluetooth keys; the LED blinks blue |
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 "balance.h"
#include "battery.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 float drive_target, yaw_target;
static float drive; // The drive speed, ramped toward drive_target
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_drive(float mmps, float yaw_dps)
{
drive_target = mmps;
yaw_target = yaw_dps;
}
void balance_start(void)
{
drive_target = yaw_target = 0.0f;
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 = drive = 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.
float step = DRIVE_ACCEL * DT;
drive = clip(drive_target, drive - step, drive + step);
home += drive * DT;
position = (wheel_mm(WHEEL_L) + wheel_mm(WHEEL_R)) / 2 - home;
if (position > BALANCE_MAX_AWAY) { home += position - BALANCE_MAX_AWAY; position = BALANCE_MAX_AWAY; }
if (position < -BALANCE_MAX_AWAY) { home += position + BALANCE_MAX_AWAY; position = -BALANCE_MAX_AWAY; }
target = clip(-(cfg.kv * (speed - drive) + 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);
// Turning left at w deg/s, each wheel travels w × π × track / 360 mm/s off the middle speed
float yaw = yaw_target;
float diff = yaw * 3.14159265f * TRACK_MM / 360.0f + cfg.ky * (yaw - tilt_yaw_rate());
wheel_speed(speed - diff, speed + diff);
}
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
#define BALANCE_MAX_AWAY 300.0f // mm: pushed further than this, home moves along with it
#define DRIVE_ACCEL 400.0f // mm/s²: how fast the drive speed ramps up and down
#define TRACK_MM 100.0f // Between the middles of the two tyres: measure yours
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_drive(float mmps, float yaw_dps); // Drive at this speed and turn rate (+ left)
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 remote. A key sets a drive speed and turn rate for DRIVE_HOLD_MS; after that the robot stops
// by itself. Holding a key on a keyboard repeats it, so the robot drives while the key is down. If
// the Bluetooth link drops, the keys stop coming and the robot stops: there's no "stop" to lose.
#include "balance.h"
#include "drive.h"
#include "settings.h"
#include "tick.h"
static uint32_t until;
static int moving;
void drive_key(char c)
{
float v = 0.0f, w = 0.0f;
switch (c)
{
case 'w': v = cfg.vmax; break;
case 's': v = -cfg.vmax; break;
case 'a': w = cfg.wmax; break;
case 'd': w = -cfg.wmax; break;
case 'q': v = cfg.vmax; w = cfg.wmax / 2; break;
case 'e': v = cfg.vmax; w = -cfg.wmax / 2; break;
case 'x': case ' ': break;
default: return; // Anything else (the end of a line, say) changes nothing
}
balance_drive(v, w);
moving = v != 0.0f || w != 0.0f;
until = millis() + DRIVE_HOLD_MS;
}
void drive_update(void)
{
if (moving && (int32_t)(millis() - until) >= 0)
{
balance_drive(0.0f, 0.0f);
moving = 0;
}
}c
#pragma once
#include <stdint.h>
#define DRIVE_HOLD_MS 500 // Each key drives for this long: hold it (or keep tapping)
// Keys from the Bluetooth terminal:
// w forward s backward a turn left d turn right
// q forward and left e forward and right x or space: stop
void drive_key(char c);
void drive_update(void); // From main's loop: stops the robot once a key has run outc
// The Bluetooth link: an HC-05 module on UART1, PB0 (U1RX) and PB1 (U1TX), 9600 8N1. The module
// turns the phone's Bluetooth serial connection into plain UART bytes, so this is the same UART
// setup as Step 2's, on another port.
#include "TM4C123.h"
#include "bt.h"
#include "clock.h"
#define RCGC_UART1 (1U << 1)
#define RCGC_GPIOB (1U << 1)
#define U1RX (1U << 0) // PB0
#define U1TX (1U << 1) // PB1
#define PCTL_PB01_M 0xFFU
#define PCTL_PB01_U1 0x11U // Function 1 on PB0 and PB1: U1RX, U1TX
#define BRD_X64 ((CPU_HZ * 4U + BT_BAUD / 2) / BT_BAUD)
#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 bt_init(void)
{
SYSCTL->RCGCUART |= RCGC_UART1;
SYSCTL->RCGCGPIO |= RCGC_GPIOB;
while ((SYSCTL->PRGPIO & RCGC_GPIOB) == 0) {}
while ((SYSCTL->PRUART & RCGC_UART1) == 0) {}
GPIOB->AFSEL |= U1RX | U1TX;
GPIOB->PCTL = (GPIOB->PCTL & ~PCTL_PB01_M) | PCTL_PB01_U1;
GPIOB->DEN |= U1RX | U1TX;
UART1->CTL = 0;
UART1->IBRD = BRD_X64 / 64; // 80 MHz, 9600: 520
UART1->FBRD = BRD_X64 % 64; // 53
UART1->LCRH = LCRH_WLEN_8 | LCRH_FEN;
UART1->CC = 0;
UART1->CTL = CTL_UARTEN | CTL_TXE | CTL_RXE;
}
int bt_getc(void)
{
if (UART1->FR & FR_RXFE) return -1;
return (int)(UART1->DR & 0xFF);
}
void bt_puts(const char *s)
{
for (; *s; s++)
{
while (UART1->FR & FR_TXFF) {}
UART1->DR = *s;
}
}c
#pragma once
#include <stdint.h>
#define BT_BAUD 9600U // The HC-05's default
void bt_init(void); // UART1 on PB0 (RX) / PB1 (TX), to the HC-05
int bt_getc(void); // -1 if nothing has arrived
void bt_puts(const char *s);c
// The tilt angle, from the MPU-6050. The gyro is accurate over short times but its integral drifts;
// the accelerometer knows where down is but also feels every bump. A complementary filter takes the
// gyro's changes and the accelerometer's long-term average:
// angle = k × (angle + rate × dt) + (1 − k) × accelerometer angle
#include "settings.h"
#include "tilt.h"
#define DT (1.0f / TILT_HZ)
#define K (TILT_TAU_S / (TILT_TAU_S + DT)) // 0.996 at 500 Hz
#define RAD_TO_DEG 57.29578f
static volatile float angle, rate, yaw_rate;
static volatile int started, ok, fails;
static volatile uint32_t errors;
static volatile uint32_t avg_left, avg_n;
static int32_t avg_gyro[3];
static float avg_accel;
// atan2 in degrees, without libm: a polynomial for atan on [0, 1], then the octants.
// Error under 0.001°, and about 1 µs with the FPU.
static float atan2_deg(float y, float x)
{
float ax = x < 0 ? -x : x, ay = y < 0 ? -y : y;
if (ax == 0.0f && ay == 0.0f) return 0.0f;
float z = ax > ay ? ay / ax : ax / ay;
float z2 = z * z;
float a = z * (0.99997726f + z2 * (-0.33262347f + z2 * (0.19354346f +
z2 * (-0.11643287f + z2 * (0.05265332f + z2 * -0.01172120f)))));
if (ay > ax) a = 1.57079633f - a;
if (x < 0) a = 3.14159265f - a;
if (y < 0) a = -a;
return a * RAD_TO_DEG;
}
static float accel_angle(const int16_t a[3])
{
return atan2_deg(FWD_SIGN * (float)a[FWD_AXIS], UP_SIGN * (float)a[UP_AXIS]);
}
void tilt_update(const struct imu_raw *r)
{
const int16_t a[3] = { r->ax, r->ay, r->az };
const int16_t g[3] = { r->gx, r->gy, r->gz };
float acc = accel_angle(a);
if (avg_left)
{
for (int i = 0; i < 3; i++) avg_gyro[i] += g[i];
avg_accel += acc;
avg_left--;
}
acc -= cfg.level_deg;
float w = PITCH_SIGN * (g[PITCH_AXIS] - cfg.gyro_bias[PITCH_AXIS]) / (float)IMU_GYRO_LSB_DPS;
if (!started)
{
angle = acc; // The first reading: start from the accelerometer
started = 1;
}
else
angle = K * (angle + w * DT) + (1.0f - K) * acc;
rate = w;
yaw_rate = YAW_SIGN * (g[YAW_AXIS] - cfg.gyro_bias[YAW_AXIS]) / (float)IMU_GYRO_LSB_DPS;
ok = 1;
fails = 0;
}
// One failed read can be noise on the bus. Five in a row (10 ms): the IMU is gone.
void tilt_read_failed(void)
{
errors++;
if (++fails >= 5) ok = 0;
}
float tilt_angle(void) { return angle; }
float tilt_rate(void) { return rate; }
float tilt_yaw_rate(void) { return yaw_rate; }
int tilt_ok(void) { return ok; }
uint32_t tilt_errors(void) { return errors; }
void tilt_average_start(uint32_t n)
{
avg_left = 0; // Stop the tick adding while the sums are cleared
for (int i = 0; i < 3; i++) avg_gyro[i] = 0;
avg_accel = 0;
avg_n = n;
avg_left = n;
}
int tilt_average_done(void) { return avg_left == 0; }
void tilt_average_result(int16_t gyro[3], float *accel_deg)
{
for (int i = 0; i < 3; i++) gyro[i] = (int16_t)(avg_gyro[i] / (int32_t)avg_n);
*accel_deg = avg_accel / avg_n;
}c
#pragma once
#include <stdint.h>
#include "imu.h"
#define TILT_HZ 500 // How often the tick reads the IMU and updates the angle
#define TILT_TAU_S 0.5f // Complementary filter time constant
#define TILT_FALLEN 45.0f // Past this, the robot is lying down
// How the IMU sits in the robot, from Step 6's Test: 0 = x, 1 = y, 2 = z. Each sign is +1 if that
// reading goes up when the robot tips forward (UP: when it stands upright), -1 if it goes down.
#define FWD_AXIS 0 // Accelerometer axis that points forward
#define FWD_SIGN (-1)
#define UP_AXIS 2 // Accelerometer axis that points up
#define UP_SIGN 1
#define PITCH_AXIS 1 // Gyro axis the robot tips about
#define PITCH_SIGN 1
#define YAW_AXIS 2 // Gyro axis that points up: the robot turns about it
#define YAW_SIGN 1 // +1 if it reads + when the robot turns left
void tilt_update(const struct imu_raw *r); // From the tick, with each new IMU reading
void tilt_read_failed(void); // From the tick, when the IMU didn't answer
float tilt_angle(void); // Degrees, + forward, 0 at the balance point
float tilt_rate(void); // Degrees per second, + tipping forward
float tilt_yaw_rate(void); // Degrees per second, + turning left
int tilt_ok(void); // 1 while the IMU answers
uint32_t tilt_errors(void); // Failed IMU reads since boot
// Calibrate: average n readings in the tick, then the results
void tilt_average_start(uint32_t n);
int tilt_average_done(void);
void tilt_average_result(int16_t gyro[3], float *accel_deg);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,
.ky = 1.0f,
.vmax = 300.0f,
.wmax = 120.0f,
};
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" },
{ "ky", &cfg.ky, "mm/s per deg/s" },
{ "vmax", &cfg.vmax, "mm/s" },
{ "wmax", &cfg.wmax, "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 12
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
float ky; // Steering: mm/s of wheel speed difference per deg/s of turn error
float vmax; // Driving speed, mm/s
float wmax; // Turning speed, deg/s
};
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. Balance stands the robot up when you hold it upright and keeps it where
// it started, with the serial console for tuning; Drive does the same and takes keys from the
// Bluetooth remote. 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 "bt.h"
#include "clock.h"
#include "console.h"
#include "drive.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(int driving)
{
uint32_t mv = battery_mv();
long a = CENTI(tilt_angle());
oled_printf(0, "%s %lu.%02luV", driving ? "DRIVE" : "BALANCE", 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; in
// Drive, the Bluetooth keys move it.
static void balance_mode(int driving)
{
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");
if (driving)
{
printf("drive: w a s d, q e, x stops. Each key lasts %d ms\n", DRIVE_HOLD_MS);
bt_puts("\r\nbalance-bot: w a s d, q e, x stops\r\n");
}
balance_start();
uint32_t next_log = millis();
while (!button_pressed(BTN_SW2))
{
console_poll();
if (driving)
{
int c;
while ((c = bt_getc()) >= 0) drive_key((char)c);
drive_update();
}
int running = balance_state() == BAL_RUN;
uint32_t colour = driving ? LED_BLUE : LED_GREEN;
led_set(running || millis() / 250 % 2 ? colour : LED_OFF);
if (have_oled && !oled_busy()) oled_balance(driving);
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 || mode == MODE_DRIVE)
balance_mode(mode == MODE_DRIVE);
else if (mode == MODE_TEST)
test_status();
else if (mode == MODE_CALIBRATE)
calibrate();
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();
bt_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
- Driving is a moving home. The outer loop compares the speed with the drive speed and the position with a home that moves at the drive speed. Holding still and driving are the same loop; Step 11's gains carry over.
- The ramp. A jump from 0 to 300 mm/s would ask for a sudden lean and could tip the robot.
DRIVE_ACCELramps the drive speed at 400 mm/s², so it takes 0.75 s to get to speed. - Steering. Turning at w degrees per second, each wheel runs w × π × track / 360 mm/s faster or slower than the middle. That's the feed-forward, from
TRACK_MM.kycorrects it with the gyro: tyres slip, and one motor lags the other. - No stop button to lose. Every key lasts 500 ms. Holding a key on a keyboard repeats it about 30 times a second, so the robot drives while it's held and stops half a second after it's let go. If the link drops, the keys stop and so does the robot.
- Pushed too far. If the robot is held back, home keeps moving and the position error would grow without limit.
BALANCE_MAX_AWAYmoves home along once it's 300 mm ahead, so letting go doesn't fire the robot forward.
Test
- Fill in
YAW_AXISandYAW_SIGNintilt.h(turn the robot left on the bench: the axis that reads + is the one, sign +1) andTRACK_MMfrom Step 9. Pair the HC-05 and open the terminal. - Drive mode: the terminal shows
balance-bot: w a s d, q e, x stops. Let the robot take over. - Hold
w: it leans forward, speeds up smoothly to 300 mm/s and drives straight. Let go: it stops within about 20 cm and holds position. - Hold
a: it turns on the spot to the left at about 120°/s;dto the right. Time four full turns: about 12 seconds. If it turns slower, raiseky. - Drive forward and turn off the phone's Bluetooth: the robot stops within half a second and keeps balancing.
- Raise
vmax100 at a time until it gets hard to stop, then go back one step andsave. That's the robot's top speed with these gains.