Tilt Angle
This step gives the robot its most important number: how far it leans, in degrees, 500 times a second. The tick takes over the I2C bus, so the IMU is read at a fixed rate and the display and IMU never cut into each other's transfers. A complementary filter mixes the gyro and the accelerometer into the angle. Calibrate mode measures the gyro's offsets and the angle of the balance point and saves them in the chip's EEPROM.
Hardware: nothing new.
Set the axes
Fill in tilt.h from what you wrote down in Step 6's Test, step 4:
| Define | What it is |
|---|---|
FWD_AXIS, FWD_SIGN | The accelerometer axis that changed when you tipped the robot forward, and +1 if it went up, −1 if it went down |
UP_AXIS, UP_SIGN | The axis that read ±1000 mg flat, and +1 if it read +1000 with the robot upright |
PITCH_AXIS, PITCH_SIGN | The gyro axis that turned as you tipped it, and +1 if it read + while tipping forward |
What you add
| File | What it does |
|---|---|
tilt.c, tilt.h | The complementary filter, the accelerometer angle (atan2 without libm), the IMU health check, and the averaging Calibrate uses |
settings.c, settings.h | The calibration in the first block of the EEPROM: loaded at boot, saved by Calibrate, ignored if its version doesn't match |
oled.c, oled.h | Changed: a second frame buffer, sent 16 bytes at a time from the tick |
tick.c, tick.h | Changed: once the tick owns the bus, odd ticks read the IMU and update the angle, even ticks send a piece of the display |
main.c | Changed: Calibrate mode, the angle in Test, the display only redrawn when the last frame has gone |
imu.c, i2c.c and the rest are unchanged from Step 6.
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;
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;
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; }
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
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
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,
};
_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;
}
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.
#define SETTINGS_VERSION 7
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
};
extern struct settings cfg;
void settings_load(void); // The stored copy, or the defaults
int settings_save(void); // 0 = writtenc
// The SSD1306 OLED, 128×64 pixels on the I2C bus at 0x3C. The picture lives in a 1 KB buffer here:
// eight pages of 128 bytes, each byte a column of 8 pixels with bit 0 on top. Drawing writes the
// buffer; oled_flush() copies it to a second buffer that goes out a page at a time, with the
// controller's page addressing, which the SH1106 on 1.3 inch modules understands too.
// Once the tick owns the bus, the frame goes out from the tick, 16 bytes per call, so no transfer
// is ever cut in half by another one.
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include "font5x7.h"
#include "i2c.h"
#include "oled.h"
#define PIECE 16 // Bytes per oled_tick(): 0.5 ms of bus time
#define WIDTH 128
#define CTRL_CMD 0x00 // First byte of a transfer: the rest are commands
#define CTRL_DATA 0x40 // The rest are pixel data
static uint8_t fb[OLED_ROWS][WIDTH]; // What main() draws on
static uint8_t tx[OLED_ROWS][WIDTH]; // The frame going out
static volatile int sending, async;
static uint32_t at_page, at_col;
static int commands(const uint8_t *list, uint32_t n)
{
uint8_t buf[32];
buf[0] = CTRL_CMD;
memcpy(buf + 1, list, n);
return i2c_write(OLED_ADDR, buf, n + 1);
}
int oled_init(void)
{
static const uint8_t init[] = {
0xAE, // Display off while setting up
0xD5, 0x80, // Clock divider: the default
0xA8, OLED_HEIGHT - 1, // Multiplex: how many rows the panel has
0xD3, 0x00, // No vertical offset
0x40, // Start at RAM line 0
0x8D, 0x14, // Charge pump on: the panel's high voltage from 3.3 V
0xA1, // Column 127 on the left: with C8, the picture the right way up
0xC8, // Scan rows bottom to top
0xDA, OLED_HEIGHT == 64 ? 0x12 : 0x02, // How the row pins are wired on this panel size
0x81, 0xCF, // Contrast
0xD9, 0xF1, // Pre-charge period, for the internal charge pump
0xDB, 0x40, // VCOMH level
0xA4, // Show the RAM (A5 would light every pixel)
0xA6, // Not inverted
};
static const uint8_t on[] = { 0xAF };
if (commands(init, sizeof init)) return -1;
oled_clear();
if (oled_flush()) return -1;
return commands(on, sizeof on); // On only once the RAM is blank: no flash of noise
}
void oled_clear(void) { memset(fb, 0, sizeof fb); }
void oled_text(uint32_t row, const char *s)
{
if (row >= OLED_ROWS) return;
memset(fb[row], 0, WIDTH);
for (uint32_t c = 0; c < OLED_COLS && s[c]; c++)
{
char ch = s[c];
if (ch < ' ' || ch > '~') ch = '?';
memcpy(&fb[row][c * 6], font5x7[ch - ' '], 5); // The 6th column stays blank
}
}
void oled_printf(uint32_t row, const char *fmt, ...)
{
char line[OLED_COLS + 1];
va_list ap;
va_start(ap, fmt);
vsnprintf(line, sizeof line, fmt, ap);
va_end(ap);
oled_text(row, line);
}
// A tick at the centre, and a 6-pixel-high bar from it to the value's side
void oled_bar(uint32_t row, int32_t value, int32_t full)
{
if (row >= OLED_ROWS || full <= 0) return;
if (value > full) value = full;
if (value < -full) value = -full;
int32_t mid = WIDTH / 2, end = mid + value * (WIDTH / 2 - 1) / full;
memset(fb[row], 0, WIDTH);
for (int32_t x = (end < mid ? end : mid); x <= (end < mid ? mid : end); x++) fb[row][x] = 0x7E;
fb[row][mid] = 0xFF;
}
static int set_page(uint32_t p)
{
uint32_t col = OLED_COL_OFFSET;
const uint8_t at[] = { 0xB0 | p, 0x00 | (col & 0xF), 0x10 | (col >> 4) }; // Page p, column 0
return commands(at, sizeof at);
}
static int send(const uint8_t *data, uint32_t n)
{
uint8_t buf[1 + WIDTH];
buf[0] = CTRL_DATA;
memcpy(buf + 1, data, n);
return i2c_write(OLED_ADDR, buf, n + 1);
}
int oled_flush(void)
{
while (sending) {}
memcpy(tx, fb, sizeof tx);
if (async)
{
at_page = 0;
at_col = 0;
sending = 1; // The tick takes it from here
return 0;
}
for (uint32_t p = 0; p < OLED_ROWS; p++)
if (set_page(p) || send(tx[p], WIDTH)) return -1;
return 0;
}
int oled_busy(void) { return sending; }
void oled_async(void) { async = 1; }
void oled_tick(void)
{
if (!sending) return;
if (at_col == 0 && set_page(at_page)) { sending = 0; return; } // A failed piece drops the frame
if (send(&tx[at_page][at_col], PIECE)) { sending = 0; return; }
at_col += PIECE;
if (at_col == WIDTH)
{
at_col = 0;
if (++at_page == OLED_ROWS) sending = 0;
}
}c
#pragma once
#include <stdint.h>
#define OLED_ADDR 0x3C // 0x3D on some modules (a jumper on the back)
#define OLED_HEIGHT 64 // 32 for the 0.91 inch 128×32 modules
#define OLED_COL_OFFSET 0 // 2 for SH1106 controllers (most 1.3 inch modules)
#define OLED_COLS 21 // Characters per line: 128 / 6
#define OLED_ROWS (OLED_HEIGHT / 8)
// Drawing only changes the copy in RAM; oled_flush() sends it to the display. Before the tick takes
// the bus (oled_async()) it sends the whole screen at once; after, the tick sends it in pieces.
int oled_init(void); // 0 = found and set up
void oled_clear(void);
void oled_text(uint32_t row, const char *s); // One line, cut at 21 characters
void oled_printf(uint32_t row, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
void oled_bar(uint32_t row, int32_t value, int32_t full); // A bar from the middle: -full to +full
int oled_flush(void); // Waits for the frame before it to finish, then sends this one
int oled_busy(void); // 1 while a frame is still going out: draw only when it's 0
void oled_async(void); // From now on the tick sends the frames
void oled_tick(void); // From the tick: one piece of the frame, 16 bytesc
// 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 (500 Hz), and 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"
#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)
{
struct imu_raw r;
if (imu_read(&r) == 0)
tilt_update(&r);
else
tilt_read_failed();
}
void SysTick_Handler(void)
{
uint32_t start = cycles();
ms++;
ui_tick();
battery_tick();
motor_tick();
encoder_tick();
if (bus)
{
if (ms & 1) { if (read_imu) 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
#pragma once
#include <stdint.h>
#define TICK_HZ 1000U
void tick_init(void);
void tick_bus_start(int with_imu); // From now on the tick owns the I2C bus: the display, and the IMU too
uint32_t millis(void);
void delay_ms(uint32_t ms);
// The tick handler's own cost, in CPU cycles (80,000 = the whole 1 ms)
uint32_t tick_cycles_last(void);
uint32_t tick_cycles_max(void); // Worst case since the last call; reading resets itc
// 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, encoders and tilt angle on the serial log
// and the display, and SW1 steps the motors through a check.
#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"
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.
static const struct { const char *name; int32_t left_mv, right_mv; } motor_check[] = {
{ "motors off", 0, 0 },
{ "left forward", 3000, 0 },
{ "left backward", -3000, 0 },
{ "right forward", 0, 3000 },
{ "right backward", 0, -3000 },
{ "both forward", MOTOR_MAX_MV, MOTOR_MAX_MV },
};
#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%6ld R%6ld", (long)encoder_count(WHEEL_L), (long)encoder_count(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);
}
motor_volts(motor_check[check].left_mv, motor_check[check].right_mv); // 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 cnt %ld mm %ld cnt/s err %lu", wh == WHEEL_L ? 'L' : 'R',
(long)encoder_count(wh), (long)counts_to_mm(encoder_count(wh)),
(long)encoder_speed(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());
}
motor_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_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 two sensors. Integrating the gyro gives a smooth angle that drifts a little every second, and more as the chip warms up. The accelerometer gives an angle that never drifts but jumps with every bump and every wheel acceleration. The filter trusts the gyro over a fraction of a second and the accelerometer over seconds.
- The time constant.
TILT_TAU_S0.5 s means k = 0.996: each update takes 0.4% of the accelerometer's angle. Shorter and wheel accelerations start to tilt the angle; longer and gyro drift takes longer to wash out. - Who owns the bus. After
tick_bus_start(), only the tick touches I2C. The IMU read takes about 0.4 ms in odd ticks; a 16-byte display piece takes about 0.5 ms in even ones. A full frame takes 128 ms, about 8 frames a second, and main() only draws whenoled_busy()says the last one has gone. - Floats in the tick. The TM4C123 has a single-precision FPU, and the Cortex-M4 saves its registers on interrupt entry only if the interrupt uses them (lazy stacking).
floatin the handler is cheap;doubleis done in software and isn't. - The balance point isn't 0°. The IMU is never mounted perfectly square, and the centre of mass is never exactly over the axle. Calibrate measures the accelerometer angle while you hold the robot where it feels weightless, and subtracts it. A degree off there and the robot leans and rolls away; Step 11 takes care of what's left.
- EEPROM, not flash. The TM4C123 has 2 KB of EEPROM with its own controller, so saving doesn't mean erasing a 1 KB flash page from inside the program. Each word takes about 0.1 ms.
Test
- Build with the axes filled in. Test mode, USB only. Tip the board forward by hand:
anglegoes positive, the bar on the display moves right. Backward: negative. If not, fix the signs intilt.h. - Calibrate: lay the board flat and still, SW1, then hold it upright the way it will sit in the robot, SW1. The log prints the gyro readings at rest (close to what you wrote down in Step 6) and
saved. Reset: the boot line no longer saysnot calibrated. You'll do this again once the board is in the frame (Step 9). - Board still on the bench:
angleholds within ±0.1° andratewithin ±0.2°/s for a minute. - Tilt it to about 30° and hold it there: the angle reads 30 ± 1°. Shake it gently while holding the angle: the angle moves less than 2°.
- Unplug the IMU's SDA: the display shows
IMU not answeringwithin a few ms, andimu errcounts up. Plug it back in: the angle comes back. - Compare the tick's cost with Step 6's: odd ticks now carry the IMU read, about 50% of a tick at worst.