Skip to content

IMU and Display ​

This step gives the robot a sense of balance and a screen. The MPU-6050 measures how fast the robot tilts (the gyro) and which way is down (the accelerometer). Step 7 turns the two into a tilt angle, which the balance loop runs on. The OLED shows what the robot sees, without a laptop on the end of a cable. Both modules sit on one I2C bus, I2C0 on PB2 and PB3, at their own addresses.

Hardware: the GY-521 MPU-6050 module, the SSD1306 OLED, four wires to each from the carrier board.

Wire it ​

Module pinTo
VCC (both)LaunchPad 3.3V. The pull-ups on each module go to its VCC, so the bus stays at 3.3 V
GND (both)Ground
SCL (both)PB2
SDA (both)PB3
GY-521 AD0, INT, XDA, XCLNot connected. AD0 is pulled low on the module: address 0x68

Both modules already have pull-up resistors on SCL and SDA, so don't add more. Mount the GY-521 flat on the carrier board, near the axle, with its edges lined up with the robot: Step 7 assumes one of its axes points forward.

What you add ​

FileWhat it does
i2c.c, i2c.hI2C0 as master at 400 kHz. Frees a stuck bus at power-up, then blocking writes, register reads with a repeated START, a probe, and an error count
imu.c, imu.hResets the MPU-6050 and wakes it up, sets ±500 °/s, ±4 g and its 44 Hz low-pass filter, and reads all seven measurements in one 14-byte burst
oled.c, oled.hA 1 KB picture of the screen in RAM, lines of text and a centre bar, sent to the display page by page
font5x7.hThe characters, five columns each
main.cChanged: scans the bus at boot and shows the mode on the display. Test adds the IMU to the serial log and draws everything on the display ten times a second

tick.c, battery.c, motor.c, encoder.c, clock.c, ui.c and uart.c are unchanged from Step 5.

c
// The I2C bus: I2C0 as master on PB2 (SCL) and PB3 (SDA), 400 kHz. The IMU and the display share it,
// each at its own address. Each transfer is a sequence of MCS commands; after each one the code
// waits for the master's interrupt flag and then checks the error bits.
#include "TM4C123.h"
#include "i2c.h"

#define PB2 (1U << 2)
#define PB3 (1U << 3)

// MCS, written: what to do next
#define MCS_RUN     (1U << 0)    // Send or receive one byte
#define MCS_START   (1U << 1)    // A START (or repeated START) first, then the address
#define MCS_STOP    (1U << 2)    // A STOP after the byte
#define MCS_ACK     (1U << 3)    // When receiving: ACK the byte (more to come)
// MCS, read: what happened
#define MCS_ERROR   (1U << 1)    // ADRACK, DATACK or ARBLST below
#define MCS_ARBLST  (1U << 4)    // Another master won the bus

#define MCR_MFE     (1U << 4)    // Master function on
#define MRIS_RIS    (1U << 0)    // The master finished a command
#define TIMEOUT     20000U       // Polls before giving up: a few ms, against 23 µs per byte

static uint32_t errors;

// Fast mode clock: SCL period = 2 × (1 + TPR) × (6 low + 4 high) system clocks
#define MTPR_VALUE  (80000000U / (2U * 10U * I2C_HZ) - 1U)

// A device reset in the middle of a read can still be holding SDA low, waiting for the rest of its
// clock pulses. Up to nine SCL pulses by hand let it finish its byte and let go.
static void bus_recover(void)
{
	GPIOB->AFSEL &= ~(PB2 | PB3);
	GPIOB->DIR   |= PB2;                     // SCL: output, open drain, high
	GPIOB->DIR   &= ~PB3;                    // SDA: input
	GPIOB->ODR   |= PB2 | PB3;
	GPIOB->DEN   |= PB2 | PB3;
	GPIOB->DATA  |= PB2;

	for (int i = 0; i < 9 && !(GPIOB->DATA & PB3); i++)
	{
		GPIOB->DATA &= ~PB2;
		for (volatile int d = 0; d < 100; d++) {}   // About 5 µs: slower than 100 kHz
		GPIOB->DATA |= PB2;
		for (volatile int d = 0; d < 100; d++) {}
	}
}

void i2c_init(void)
{
	SYSCTL->RCGCGPIO |= (1U << 1);     // Port B
	SYSCTL->RCGCI2C  |= (1U << 0);     // I2C0
	while (!(SYSCTL->PRGPIO & (1U << 1))) {}
	while (!(SYSCTL->PRI2C & (1U << 0))) {}

	bus_recover();

	// I2C0SCL and I2C0SDA are PCTL function 3. Only SDA is open drain: the I2C block drives SCL
	// itself. The pull-ups are on the modules.
	GPIOB->PCTL   = (GPIOB->PCTL & ~0x0000FF00U) | 0x00003300U;
	GPIOB->ODR    = (GPIOB->ODR & ~PB2) | PB3;
	GPIOB->AFSEL |= PB2 | PB3;

	I2C0->MCR  = MCR_MFE;
	I2C0->MTPR = MTPR_VALUE;
}

// Start one command and wait for it. The interrupt flag, not BUSY: at 80 MHz BUSY can still read 0
// for a few cycles after the write to MCS.
static int command(uint32_t mcs)
{
	I2C0->MICR = MRIS_RIS;
	I2C0->MCS = mcs;
	for (uint32_t t = 0; !(I2C0->MRIS & MRIS_RIS); t++)
		if (t == TIMEOUT) return -1;

	uint32_t status = I2C0->MCS;
	if (!(status & MCS_ERROR)) return 0;
	if (!(status & MCS_ARBLST)) command(MCS_STOP);   // No ACK: end the transfer and free the bus
	return -1;
}

static int fail(void)
{
	errors++;
	return -1;
}

int i2c_write(uint8_t addr, const uint8_t *buf, uint32_t n)
{
	I2C0->MSA = (uint32_t)addr << 1;            // R/S = 0: write
	for (uint32_t i = 0; i < n; i++)
	{
		I2C0->MDR = buf[i];
		uint32_t mcs = MCS_RUN | (i == 0 ? MCS_START : 0) | (i == n - 1 ? MCS_STOP : 0);
		if (command(mcs)) return fail();
	}
	return 0;
}

// Write the register number, then a repeated START and read n bytes from there on. The device
// moves to the next register by itself after each byte.
int i2c_read_reg(uint8_t addr, uint8_t reg, uint8_t *buf, uint32_t n)
{
	I2C0->MSA = (uint32_t)addr << 1;
	I2C0->MDR = reg;
	if (command(MCS_START | MCS_RUN)) return fail();

	I2C0->MSA = ((uint32_t)addr << 1) | 1U;     // R/S = 1: read
	for (uint32_t i = 0; i < n; i++)
	{
		// ACK every byte but the last; the NACK on the last one tells the device to stop sending
		uint32_t mcs = MCS_RUN | (i == 0 ? MCS_START : 0) | (i == n - 1 ? MCS_STOP : MCS_ACK);
		if (command(mcs)) return fail();
		buf[i] = (uint8_t)I2C0->MDR;
	}
	return 0;
}

// Read one byte: a device that's there ACKs its address. Reading changes nothing in it.
int i2c_probe(uint8_t addr)
{
	I2C0->MSA = ((uint32_t)addr << 1) | 1U;
	if (command(MCS_START | MCS_RUN | MCS_STOP)) return -1;
	(void)I2C0->MDR;
	return 0;
}

uint32_t i2c_errors(void) { return errors; }
c
#pragma once
#include <stdint.h>

#define I2C_HZ  400000U     // Fast mode: the most the MPU-6050 takes

// Every call blocks until its transfer ends. 0 = done, -1 = no ACK, lost the bus, or timed out.
void i2c_init(void);                                   // I2C0 on PB2 (SCL) / PB3 (SDA)
int i2c_write(uint8_t addr, const uint8_t *buf, uint32_t n);
int i2c_read_reg(uint8_t addr, uint8_t reg, uint8_t *buf, uint32_t n);
int i2c_probe(uint8_t addr);                           // 0 if a device answers at addr
uint32_t i2c_errors(void);                             // Failed transfers since boot
c
// The MPU-6050 gyro and accelerometer, on the I2C bus at 0x68. imu_init() wakes it from sleep and
// sets its ranges and filter; imu_read() fetches all seven measurements in one burst, starting at
// ACCEL_XOUT_H, so they all come from the same sample.
#include "i2c.h"
#include "imu.h"
#include "tick.h"

// Register numbers, from the MPU-6050 register map
#define SMPLRT_DIV    0x19
#define CONFIG        0x1A
#define GYRO_CONFIG   0x1B
#define ACCEL_CONFIG  0x1C
#define ACCEL_XOUT_H  0x3B   // Then ACCEL_Y, ACCEL_Z, TEMP, GYRO_X, GYRO_Y, GYRO_Z: 14 bytes
#define PWR_MGMT_1    0x6B
#define WHO_AM_I      0x75

static uint8_t id;

static int write_reg(uint8_t reg, uint8_t value)
{
	uint8_t buf[2] = { reg, value };
	return i2c_write(IMU_ADDR, buf, 2);
}

int imu_init(void)
{
	if (i2c_read_reg(IMU_ADDR, WHO_AM_I, &id, 1)) return -1;

	if (write_reg(PWR_MGMT_1, 0x80)) return -1;   // DEVICE_RESET: every register to its default
	delay_ms(100);
	// Wake it first, then set it up
	if (write_reg(PWR_MGMT_1, 0x01)) return -1;   // Out of sleep, clocked from the X gyro (steadier than its RC)
	if (write_reg(CONFIG, 0x03)) return -1;       // Low-pass at 44 Hz (accel) / 42 Hz (gyro), about 5 ms delay
	if (write_reg(SMPLRT_DIV, 0x00)) return -1;   // A new sample every 1 ms
	if (write_reg(GYRO_CONFIG, 0x08)) return -1;  // ±500 °/s
	if (write_reg(ACCEL_CONFIG, 0x08)) return -1; // ±4 g
	return 0;
}

uint8_t imu_id(void) { return id; }

int imu_read(struct imu_raw *r)
{
	uint8_t b[14];
	if (i2c_read_reg(IMU_ADDR, ACCEL_XOUT_H, b, sizeof b)) return -1;

	// Big-endian: the high byte comes first
	int16_t v[7];
	for (int i = 0; i < 7; i++) v[i] = (int16_t)((b[2 * i] << 8) | b[2 * i + 1]);
	r->ax = v[0]; r->ay = v[1]; r->az = v[2];
	r->temp = v[3];
	r->gx = v[4]; r->gy = v[5]; r->gz = v[6];
	return 0;
}
c
#pragma once
#include <stdint.h>

#define IMU_ADDR        0x68     // AD0 low (the GY-521 pulls it low). 0x69 if AD0 is high

// The ranges imu_init() sets, and what one count is worth in each
#define IMU_ACCEL_LSB_G   8192   // ±4 g
#define IMU_GYRO_LSB_DPS  65.5   // ±500 °/s

struct imu_raw
{
	int16_t ax, ay, az;          // Accelerometer, counts
	int16_t temp;                // Die temperature, counts
	int16_t gx, gy, gz;          // Gyro, counts
};

int imu_init(void);              // 0 = found and set up, -1 = no answer
uint8_t imu_id(void);            // WHO_AM_I as read by imu_init(): 0x68 on a real MPU-6050
int imu_read(struct imu_raw *r); // All seven values in one 14-byte read: 0 = done

// For printing: milli-g, tenths of a degree per second, hundredths of a degree C
static inline int32_t imu_mg(int16_t a)    { return (int32_t)a * 1000 / IMU_ACCEL_LSB_G; }
static inline int32_t imu_ddps(int16_t g)  { return (int32_t)g * 100 / 655; }
static inline int32_t imu_temp_cc(int16_t t) { return (int32_t)t * 100 / 340 + 3653; }
c
// 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() sends one page at a time with the controller's page addressing, which the
// SH1106 on 1.3 inch modules understands too.
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include "font5x7.h"
#include "i2c.h"
#include "oled.h"

#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];

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;
}

int oled_flush(void)
{
	uint8_t buf[1 + WIDTH];
	for (uint32_t p = 0; p < OLED_ROWS; p++)
	{
		uint32_t col = OLED_COL_OFFSET;
		const uint8_t at[] = { 0xB0 | p, 0x00 | (col & 0xF), 0x10 | (col >> 4) };   // Page p, column
		if (commands(at, sizeof at)) return -1;

		buf[0] = CTRL_DATA;
		memcpy(buf + 1, fb[p], WIDTH);
		if (i2c_write(OLED_ADDR, buf, sizeof buf)) return -1;
	}
	return 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.
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);                                   // About 25 ms for the whole screen
c
#pragma once
#include <stdint.h>

// A 5×7 font for ' ' to '~'. Five bytes per character, one per column, left to right;
// bit 0 is the top row. The display adds a blank column after each character.
static const uint8_t font5x7[95][5] = {
	{ 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0x00, 0x00, 0x5F, 0x00, 0x00 }, { 0x00, 0x07, 0x00, 0x07, 0x00 }, // ' ' ! "
	{ 0x14, 0x7F, 0x14, 0x7F, 0x14 }, { 0x24, 0x2A, 0x7F, 0x2A, 0x12 }, { 0x23, 0x13, 0x08, 0x64, 0x62 }, // # $ %
	{ 0x36, 0x49, 0x55, 0x22, 0x50 }, { 0x00, 0x05, 0x03, 0x00, 0x00 }, { 0x00, 0x1C, 0x22, 0x41, 0x00 }, // & ' (
	{ 0x00, 0x41, 0x22, 0x1C, 0x00 }, { 0x08, 0x2A, 0x1C, 0x2A, 0x08 }, { 0x08, 0x08, 0x3E, 0x08, 0x08 }, // ) * +
	{ 0x00, 0x50, 0x30, 0x00, 0x00 }, { 0x08, 0x08, 0x08, 0x08, 0x08 }, { 0x00, 0x60, 0x60, 0x00, 0x00 }, // , - .
	{ 0x20, 0x10, 0x08, 0x04, 0x02 }, { 0x3E, 0x51, 0x49, 0x45, 0x3E }, { 0x00, 0x42, 0x7F, 0x40, 0x00 }, // / 0 1
	{ 0x42, 0x61, 0x51, 0x49, 0x46 }, { 0x21, 0x41, 0x45, 0x4B, 0x31 }, { 0x18, 0x14, 0x12, 0x7F, 0x10 }, // 2 3 4
	{ 0x27, 0x45, 0x45, 0x45, 0x39 }, { 0x3C, 0x4A, 0x49, 0x49, 0x30 }, { 0x01, 0x71, 0x09, 0x05, 0x03 }, // 5 6 7
	{ 0x36, 0x49, 0x49, 0x49, 0x36 }, { 0x06, 0x49, 0x49, 0x29, 0x1E }, { 0x00, 0x36, 0x36, 0x00, 0x00 }, // 8 9 :
	{ 0x00, 0x56, 0x36, 0x00, 0x00 }, { 0x08, 0x14, 0x22, 0x41, 0x00 }, { 0x14, 0x14, 0x14, 0x14, 0x14 }, // ; < =
	{ 0x00, 0x41, 0x22, 0x14, 0x08 }, { 0x02, 0x01, 0x51, 0x09, 0x06 }, { 0x32, 0x49, 0x79, 0x41, 0x3E }, // > ? @
	{ 0x7E, 0x11, 0x11, 0x11, 0x7E }, { 0x7F, 0x49, 0x49, 0x49, 0x36 }, { 0x3E, 0x41, 0x41, 0x41, 0x22 }, // A B C
	{ 0x7F, 0x41, 0x41, 0x22, 0x1C }, { 0x7F, 0x49, 0x49, 0x49, 0x41 }, { 0x7F, 0x09, 0x09, 0x09, 0x01 }, // D E F
	{ 0x3E, 0x41, 0x49, 0x49, 0x7A }, { 0x7F, 0x08, 0x08, 0x08, 0x7F }, { 0x00, 0x41, 0x7F, 0x41, 0x00 }, // G H I
	{ 0x20, 0x40, 0x41, 0x3F, 0x01 }, { 0x7F, 0x08, 0x14, 0x22, 0x41 }, { 0x7F, 0x40, 0x40, 0x40, 0x40 }, // J K L
	{ 0x7F, 0x02, 0x0C, 0x02, 0x7F }, { 0x7F, 0x04, 0x08, 0x10, 0x7F }, { 0x3E, 0x41, 0x41, 0x41, 0x3E }, // M N O
	{ 0x7F, 0x09, 0x09, 0x09, 0x06 }, { 0x3E, 0x41, 0x51, 0x21, 0x5E }, { 0x7F, 0x09, 0x19, 0x29, 0x46 }, // P Q R
	{ 0x46, 0x49, 0x49, 0x49, 0x31 }, { 0x01, 0x01, 0x7F, 0x01, 0x01 }, { 0x3F, 0x40, 0x40, 0x40, 0x3F }, // S T U
	{ 0x1F, 0x20, 0x40, 0x20, 0x1F }, { 0x3F, 0x40, 0x38, 0x40, 0x3F }, { 0x63, 0x14, 0x08, 0x14, 0x63 }, // V W X
	{ 0x07, 0x08, 0x70, 0x08, 0x07 }, { 0x61, 0x51, 0x49, 0x45, 0x43 }, { 0x00, 0x7F, 0x41, 0x41, 0x00 }, // Y Z [
	{ 0x02, 0x04, 0x08, 0x10, 0x20 }, { 0x00, 0x41, 0x41, 0x7F, 0x00 }, { 0x04, 0x02, 0x01, 0x02, 0x04 }, // \ ] ^
	{ 0x40, 0x40, 0x40, 0x40, 0x40 }, { 0x00, 0x01, 0x02, 0x04, 0x00 }, { 0x20, 0x54, 0x54, 0x54, 0x78 }, // _ ` a
	{ 0x7F, 0x48, 0x44, 0x44, 0x38 }, { 0x38, 0x44, 0x44, 0x44, 0x20 }, { 0x38, 0x44, 0x44, 0x48, 0x7F }, // b c d
	{ 0x38, 0x54, 0x54, 0x54, 0x18 }, { 0x08, 0x7E, 0x09, 0x01, 0x02 }, { 0x0C, 0x52, 0x52, 0x52, 0x3E }, // e f g
	{ 0x7F, 0x08, 0x04, 0x04, 0x78 }, { 0x00, 0x44, 0x7D, 0x40, 0x00 }, { 0x20, 0x40, 0x44, 0x3D, 0x00 }, // h i j
	{ 0x7F, 0x10, 0x28, 0x44, 0x00 }, { 0x00, 0x41, 0x7F, 0x40, 0x00 }, { 0x7C, 0x04, 0x18, 0x04, 0x78 }, // k l m
	{ 0x7C, 0x08, 0x04, 0x04, 0x78 }, { 0x38, 0x44, 0x44, 0x44, 0x38 }, { 0x7C, 0x14, 0x14, 0x14, 0x08 }, // n o p
	{ 0x08, 0x14, 0x14, 0x18, 0x7C }, { 0x7C, 0x08, 0x04, 0x04, 0x08 }, { 0x48, 0x54, 0x54, 0x54, 0x20 }, // q r s
	{ 0x04, 0x3F, 0x44, 0x40, 0x20 }, { 0x3C, 0x40, 0x40, 0x20, 0x7C }, { 0x1C, 0x20, 0x40, 0x20, 0x1C }, // t u v
	{ 0x3C, 0x40, 0x30, 0x40, 0x3C }, { 0x44, 0x28, 0x10, 0x28, 0x44 }, { 0x0C, 0x50, 0x50, 0x50, 0x3C }, // w x y
	{ 0x44, 0x64, 0x54, 0x4C, 0x44 }, { 0x00, 0x08, 0x36, 0x41, 0x00 }, { 0x00, 0x00, 0x7F, 0x00, 0x00 }, // z { |
	{ 0x00, 0x41, 0x36, 0x08, 0x00 }, { 0x02, 0x01, 0x02, 0x04, 0x02 },                                   // } ~
};
c
// The robot's main program. Each step fills in a mode; Test shows the tick's health, the battery, the
// encoders and the IMU on the serial log and the display, and SW1 steps the motors through a check.
#include <stdio.h>
#include "TM4C123.h"
#include "battery.h"
#include "clock.h"
#include "cycles.h"
#include "encoder.h"
#include "i2c.h"
#include "imu.h"
#include "motor.h"
#include "oled.h"
#include "tick.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;

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()]);
}

// 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])

// One IMU read, timed: Step 7 has to fit it into the tick
static int imu_sample(struct imu_raw *r, uint32_t *us)
{
	uint32_t t0 = cycles();
	int err = imu_read(r);
	*us = (cycles() - t0) / 80;
	return err;
}

static void oled_status(uint32_t check, const struct imu_raw *r, uint32_t us)
{
	uint32_t mv = battery_mv();
	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(3, "no IMU");
		oled_flush();
		return;
	}
	oled_printf(3, "a %5ld%5ld%5ld", (long)imu_mg(r->ax), (long)imu_mg(r->ay), (long)imu_mg(r->az));
	oled_printf(4, "g %5ld%5ld%5ld", (long)imu_ddps(r->gx), (long)imu_ddps(r->gy), (long)imu_ddps(r->gz));
	oled_printf(5, "%ld.%01ldC read %luus", (long)(imu_temp_cc(r->temp) / 100),
	            (long)(imu_temp_cc(r->temp) / 10 % 10), (unsigned long)us);
	oled_text(6, "ax:");
	oled_bar(7, imu_mg(r->ax), 1000);
	oled_flush();
}

// Until SW2: the motor check, the display ten times a second, the serial log twice a second
static void test_status(void)
{
	uint32_t next_log = millis(), next_oled = millis(), check = 0;
	struct imu_raw r = { 0 };
	uint32_t us = 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 && (int32_t)(millis() - next_oled) >= 0)
		{
			next_oled += 100;
			if (have_imu) imu_sample(&r, &us);
			oled_status(check, &r, us);
		}

		if ((int32_t)(millis() - next_log) < 0) continue;
		next_log += 500;
		uint32_t max = tick_cycles_max();
		print_battery();
		printf("  tick %lu.%02lu%%", max * 100 / 80000, max * 10000 / 80000 % 100);
		for (int w = WHEEL_L; w <= WHEEL_R; w++)
			printf("  %c: %ld cnt %ld mm %ld cnt/s err %lu", w == WHEEL_L ? 'L' : 'R',
			       (long)encoder_count(w), (long)counts_to_mm(encoder_count(w)),
			       (long)encoder_speed(w), (unsigned long)encoder_errors(w));
		printf("\n");

		if (have_imu && imu_sample(&r, &us) == 0)
			printf("  accel %ld %ld %ld mg  gyro %ld %ld %ld x0.1 deg/s  %ld C  read %lu us  i2c err %lu\n",
			       (long)imu_mg(r.ax), (long)imu_mg(r.ay), (long)imu_mg(r.az),
			       (long)imu_ddps(r.gx), (long)imu_ddps(r.gy), (long)imu_ddps(r.gz),
			       (long)(imu_temp_cc(r.temp) / 100), (unsigned long)us, (unsigned long)i2c_errors());
	}
	motor_stop();
}

// 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 still runs on a dead battery, so you can watch the voltage
	if (mode != MODE_TEST && battery_state() == BATT_DEAD)
	{
		refuse();
		return;
	}
	printf("mode: %s\n", mode_name[mode]);
	if (have_oled)
	{
		oled_clear();
		oled_printf(0, "mode: %s", mode_name[mode]);
		oled_flush();
	}
	if (battery_state() == BATT_LOW) printf("battery low: charge it after this run\n");

	if (mode == MODE_TEST)
		test_status();
	else
		while (!button_pressed(BTN_SW2)) {}   // Not written yet
	printf("menu\n");
	if (have_oled)
	{
		oled_clear();
		oled_text(0, "menu");
		oled_flush();
	}
}

// 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();
	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()
	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 (have_oled)
	{
		oled_text(0, "balance-bot");
		oled_text(2, have_imu ? "imu ok" : "imu not found");
		oled_text(4, "menu");
		oled_flush();
	}

	uint32_t mode = MODE_BALANCE;
	while (1)
	{
		mode = ui_menu(mode_colour, N_MODES, mode);
		run(mode);
	}
}

Notes ​

  • One transfer is several commands. The master sends one byte per write to MCS, and the bits in that write say whether a START goes before it and a STOP after it. A register read is a write of the register number, then a repeated START with the read bit set, then one command per byte, with ACK on every byte except the last.
  • Wait on MRIS, not on BUSY. At 80 MHz the BUSY bit in MCS can still read 0 for a few cycles after the write that starts a command, so a loop on it can fall straight through. The master's raw interrupt flag only sets when the command has finished.
  • Every wait has a timeout. A missing module, a loose wire or a device holding the bus would otherwise hang the robot inside an I2C call, motors included. On a timeout or a missing ACK the driver sends a STOP, counts an error and returns -1.
  • A stuck bus. If the LaunchPad resets in the middle of a read, the MPU-6050 is still in the middle of sending a byte and holds SDA low. Nothing on the bus works until it finishes. i2c_init() clocks SCL by hand, up to nine times, until SDA goes high.
  • Why ±500 °/s and ±4 g. A falling robot turns at a few hundred degrees a second, more than ±250 covers. A bump in the wheels can go over 2 g. Each range is the smallest one that doesn't clip, so it keeps the most resolution.
  • The low-pass filter at 44 Hz removes most of the motors' vibration from the accelerometer, at the cost of about 5 ms of delay. Step 7 trusts the gyro for fast changes, so that delay matters less than the noise.
  • Not every board says 0x68. Clones with an MPU-6500 or similar chip answer WHO_AM_I with 0x70 or 0x98. The registers this step uses are the same on those, so the boot line only warns.
  • The display is slow. A full screen is 1 KB, about 25 ms at 400 kHz. That's fine for ten frames a second from main(), but the tick can't wait that long.
  • One bus, one user at a time. In this step only main() uses the bus. In Step 7 the tick reads the IMU, and a tick that interrupts a display transfer would mix its bytes into it. Step 7 deals with that.

Test ​

  1. USB only. The boot log shows i2c: 3c 68 (or 3d for the display), display: ok and imu: WHO_AM_I 68. The display shows balance-bot and imu ok. If a module is missing from the scan, check its four wires before the code.
  2. Unplug the IMU's SDA and reset: the boot line says imu: not found and the menu still works, nothing hangs. Plug it back in.
  3. Test mode, board flat and still. The accelerometer reads about 0, 0 and 1000 mg (or −1000, depending on which way up the module is), and the gyro within a few tenths of a degree per second of 0 on all three axes. Write down the gyro readings: Step 7 subtracts them.
  4. Tilt the board forward by hand. Write down which accelerometer axis changes and with which sign, and which gyro axis turns: those are the forward axis and the tilt axis for Step 7. The bar on the display follows ax.
  5. Note the read time on the display. A 14-byte read should take about 0.4 ms. Step 7 has to fit it into the tick.
  6. Battery on, wheels in the air, both forward in the motor check. The i2c err count stays at 0 for a minute, and the gyro still reads near 0 with the board held still, apart from the vibration.

Balance Bot Bootcamp