Skip to content

Encoders ​

This step lets the robot measure its wheels. The QEI peripherals count every edge of both encoder channels in hardware, so the CPU only reads a register. The tick turns the two positions into speed every 1 ms. The speed loop in Step 8 is built on it, and Step 11 uses it to keep the balancing robot from drifting away.

Hardware: the encoder wires on both motors, the 4-pin XH cables from the motors to the carrier board.

Wire it ​

EncoderTo
VCCLaunchPad 3.3V. At 3.3 V the outputs can't exceed what the pins take
GNDGround
Left A, BPD6, PD7
Right A, BPC5, PC6

Keep the encoder cable apart from the motor's two power wires, and twist each motor's power pair: the motor's switching noise shows up as phase errors otherwise.

What you add ​

FileWhat it does
encoder.cQEI0 on PD6/PD7 (unlocking PD7) and QEI1 on PC5/PC6, counting on all four edges with the input filter on. The tick reads both, keeps a running position, and works out speed over the last 10 ms
encoder.hCounts per wheel turn, wheel diameter, which side counts backwards, counts_to_mm()
tick.cChanged: calls encoder_tick()
main.cChanged: Test prints both wheels' count, distance, speed and phase errors twice a second

battery.c, motor.c, clock.c, ui.c and uart.c are unchanged from Step 4.

c
// The wheel encoders. QEI0 counts the left wheel on PD6/PD7, QEI1 the right on PC5/PC6, on every
// edge of both channels. The tick reads both positions every 1 ms and keeps the last 10 changes,
// so speed is the count change over 10 ms.
#include "TM4C123.h"
#include "encoder.h"

#define PC5 (1U << 5)
#define PC6 (1U << 6)
#define PD6 (1U << 6)
#define PD7 (1U << 7)

#define QEI_ENABLE    (1U << 0)
#define QEI_SWAP      (1U << 1)    // Swap PhA and PhB: counts the other way
#define QEI_CAPMODE   (1U << 3)    // Count edges of both PhA and PhB (×4)
#define QEI_FILTEN    (1U << 13)   // Input filter on
#define QEI_FILTCNT   (0xFU << 16) // A level must hold for 17 clocks (212 ns) to count
#define QEI_ERROR     (1U << 3)    // RIS/ISC: both phases changed at once

static QEI0_Type *const qei[2] = { QEI0, QEI1 };

static volatile int32_t pos[2], speed[2];
static volatile uint32_t errors[2];
static uint32_t last[2];
static int16_t window[2][SPEED_WINDOW_MS];
static int32_t window_sum[2];
static uint32_t slot;

static void qei_setup(QEI0_Type *q, int reversed)
{
	q->CTL = 0;
	q->MAXPOS = 0xFFFFFFFF;          // Wrap at 2^32: differences stay right across the wrap
	q->POS = 0;
	q->CTL = QEI_CAPMODE | QEI_FILTEN | QEI_FILTCNT | (reversed ? QEI_SWAP : 0);
	q->CTL |= QEI_ENABLE;
}

void encoder_init(void)
{
	SYSCTL->RCGCGPIO |= (1U << 2) | (1U << 3);   // Ports C and D
	SYSCTL->RCGCQEI  |= (1U << 0) | (1U << 1);   // QEI0 and QEI1
	while ((SYSCTL->PRGPIO & 0xC) != 0xC) {}
	while ((SYSCTL->PRQEI & 0x3) != 0x3) {}

	// PD7 is locked (it can be NMI), like PF0 in Step 1
	GPIOD->LOCK = 0x4C4F434B;
	GPIOD->CR  |= PD7;
	GPIOD->LOCK = 0;

	// PhA0/PhB0 and PhA1/PhB1 are PCTL function 6. Pull-ups for open-collector encoders.
	GPIOD->AFSEL |= PD6 | PD7;
	GPIOD->PCTL   = (GPIOD->PCTL & ~0xFF000000U) | 0x66000000U;
	GPIOD->PUR   |= PD6 | PD7;
	GPIOD->DEN   |= PD6 | PD7;
	GPIOC->AFSEL |= PC5 | PC6;
	GPIOC->PCTL   = (GPIOC->PCTL & ~0x0FF00000U) | 0x06600000U;
	GPIOC->PUR   |= PC5 | PC6;
	GPIOC->DEN   |= PC5 | PC6;

	qei_setup(QEI0, LEFT_ENC_REVERSED);
	qei_setup(QEI1, RIGHT_ENC_REVERSED);
}

void encoder_tick(void)
{
	for (int w = 0; w < 2; w++)
	{
		uint32_t now = qei[w]->POS;
		int32_t delta = (int32_t)(now - last[w]);
		last[w] = now;
		pos[w] += delta;

		window_sum[w] += delta - window[w][slot];
		window[w][slot] = (int16_t)delta;
		speed[w] = window_sum[w] * (1000 / SPEED_WINDOW_MS);

		if (qei[w]->RIS & QEI_ERROR)
		{
			qei[w]->ISC = QEI_ERROR;
			errors[w]++;
		}
	}
	if (++slot == SPEED_WINDOW_MS) slot = 0;
}

int32_t encoder_count(int wheel)   { return pos[wheel]; }
int32_t encoder_speed(int wheel)   { return speed[wheel]; }
uint32_t encoder_errors(int wheel) { return errors[wheel]; }

// One count is π × diameter / counts per turn. In 64 bits: a few metres of counts × µm overflow 32.
int32_t counts_to_mm(int32_t counts)
{
	const int64_t circ_um = (int64_t)(3.14159265 * WHEEL_DIAMETER_MM * 1000);
	return (int32_t)(counts * circ_um / ENC_COUNTS_PER_REV / 1000);
}
c
#pragma once
#include <stdint.h>

// Measure these on your robot (Step 5's test): counts for one wheel turn, and the tyre's diameter
#define ENC_COUNTS_PER_REV  360          // Encoder CPR × gear ratio, counted on all four edges
#define WHEEL_DIAMETER_MM   70

// Flip one if that wheel counts down when it turns forward (the motors face opposite ways)
#define LEFT_ENC_REVERSED   0
#define RIGHT_ENC_REVERSED  1

#define SPEED_WINDOW_MS     10           // Speed is the count change over the last 10 ticks

enum { WHEEL_L, WHEEL_R };

void encoder_init(void);
void encoder_tick(void);                 // Called every 1 ms from the tick
int32_t encoder_count(int wheel);        // Position in counts, + forward
int32_t encoder_speed(int wheel);        // Counts per second
uint32_t encoder_errors(int wheel);      // Phase errors since boot: should stay 0
int32_t counts_to_mm(int32_t counts);
c
// The robot's main program. Each step fills in a mode; Test prints the tick's health, the battery and
// the encoders, and SW1 steps the motors through a check.
#include <stdio.h>
#include "TM4C123.h"
#include "battery.h"
#include "clock.h"
#include "encoder.h"
#include "motor.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 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])

// Until SW2: the motor check, and twice a second the battery, encoders and tick cost
static void test_status(void)
{
	uint32_t next = 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 ((int32_t)(millis() - next) < 0) continue;
		next += 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");
	}
	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 (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");
}

int main(void)
{
	clock_init();
	uart_init();
	ui_init();
	battery_init();                     // Before the tick, which reads it
	motor_init();
	encoder_init();
	tick_init();

	printf("\nbalance-bot: %lu MHz, built " __DATE__ " " __TIME__ "\n", (unsigned long)(CPU_HZ / 1000000));
	print_battery();
	printf("\n");

	uint32_t mode = MODE_BALANCE;
	while (1)
	{
		mode = ui_menu(mode_colour, N_MODES, mode);
		run(mode);
	}
}
c
// The 1 kHz system tick. Everything periodic runs from SysTick_Handler:
// buttons, the battery, the motors' dead-man and the encoders now, then the IMU and balance loop in later steps.
#include "TM4C123.h"
#include "battery.h"
#include "clock.h"
#include "cycles.h"
#include "encoder.h"
#include "motor.h"
#include "tick.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;

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 SysTick_Handler(void)
{
	uint32_t start = cycles();

	ms++;
	ui_tick();
	battery_tick();
	motor_tick();
	encoder_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;
}

Notes ​

  • ×4 counting. CAPMODE counts every rising and falling edge of A and B, four counts per encoder line. A 12 CPR motor encoder (the Pololu one, already ×4) on a 30:1 gearbox gives 360 counts per wheel turn; a 7-line N20 hall encoder on 30:1 gives 840. Gear ratios are rarely whole numbers, so measure instead of multiplying.
  • The position wraps, and that's fine. MAXPOS is 2^32 − 1. The tick subtracts readings as uint32_t and casts to int32_t, which is right across the wrap, and keeps its own signed position.
  • Why a 10 ms window. At 1 ms, a wheel at a few turns a second moves only a handful of counts per tick, so speed would jump in steps of 1000 counts/s. Summing the last 10 changes gives steps of 100 counts/s, at the cost of 5 ms of delay. Step 8 revisits this trade-off.
  • The input filter ignores any pulse shorter than 17 clocks (212 ns). Real edges are tens of microseconds apart even at full speed, so it only removes noise.
  • Phase errors mean A and B changed at the same moment, which a real encoder never does. A count that climbs while the motors run means noise from the motor wiring.
  • Mirrored again. Like the motors, the right encoder counts down for forward. RIGHT_ENC_REVERSED sets the QEI's SWAP bit so both wheels count up going forward.

Test ​

  1. Battery off, USB on, Test mode. Turn the left wheel forward by hand: L: counts up. Backward: it counts down. Same for R:. If a wheel counts the wrong way, flip its *_ENC_REVERSED.
  2. Counts per turn: mark the tyre and the frame, reset, and turn the wheel exactly 10 times. Set ENC_COUNTS_PER_REV to the count / 10. Measure the tyre with calipers for WHEEL_DIAMETER_MM.
  3. Roll the robot (or the wheel against a ruler) 500 mm: mm should read 500 ± 5.
  4. Battery on, wheels in the air. Step the motor check with SW1: on left forward the left speed is positive and the right stays at 0. Write down both wheels' speed at 3 V and on both forward at 6 V. The two motors won't match exactly; the difference is what the speed loop will remove.
  5. Run both forward for a minute: err stays at 0 on both wheels.
  6. Compare the tick's cost with Step 4's.

Balance Bot Bootcamp