Skip to content

Motors ​

This step makes the wheels turn. The TB6612 goes on the carrier board between the battery and the two motors. PWM0 drives it at 20 kHz, and four GPIO pins set the directions. The driver takes a command in millivolts, not duty. It divides by the battery voltage from Step 3, so the same command gives the same speed at 8.4 V and at 7.2 V. The wheel speed loop in Step 8 depends on that.

Hardware: the TB6612 breakout, both gear motors (on the bench for now: tape them down with the wheels in the air, the frame is Step 9), a 100 µF electrolytic capacitor. Remove R9 and R10 from the LaunchPad first (Pinout).

Wire it ​

TB6612To
VMVBAT (the switched battery from Step 3), with the 100 µF to ground beside the driver
VCCLaunchPad 3.3V
GND (all)Ground
PWMA, AIN1, AIN2PB6, PA6, PA7
PWMB, BIN1, BIN2PB7, PC4, PC7
STBYPD2
AO1, AO2Left motor M1, M2
BO1, BO2Right motor M1, M2

The encoder wires on the motors stay loose until Step 5.

What you add ​

FileWhat it does
motor.cPWM0 generator 0 at 20 kHz on PB6/PB7, direction pins, STBY. motor_volts() turns millivolts into duty, capped at 6 V. A dead-man in the tick stops both motors when commands stop, and a HardFault_Handler puts the driver in standby
motor.hThe cap, the timeout, and which side is mirrored
tick.cChanged: calls motor_tick()
main.cChanged: in Test, SW1 steps through a motor check

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

c
// The robot's main program. Each step fills in a mode; Test prints the tick's health and the battery,
// and SW1 steps the motors through a check.
#include <stdio.h>
#include "TM4C123.h"
#include "battery.h"
#include "clock.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 once a second the uptime, battery 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 += 1000;
		uint32_t max = tick_cycles_max();
		printf("t=%lu s  ", millis() / 1000);
		print_battery();
		printf("  tick: max %lu cyc (%lu.%02lu%% of 1 ms)\n",
		       max, max * 100 / 80000, max * 10000 / 80000 % 100);
	}
	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();
	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 TB6612 motor driver. PWM0 generator 0 makes 20 kHz on PB6 (left, PWMA) and PB7 (right, PWMB);
// PA6/PA7 and PC4/PC7 set each motor's direction, and PD2 is STBY. The command is in millivolts:
// the duty is worked out from the battery voltage, so a command means the same speed on a full
// battery as on a tired one.
#include "TM4C123.h"
#include "battery.h"
#include "motor.h"

#define PWM_HZ     20000U                  // Above hearing
#define PWM_LOAD   (80000000U / PWM_HZ)    // 4000 counts per period at 80 MHz

#define PA6 (1U << 6)
#define PA7 (1U << 7)
#define PB6 (1U << 6)
#define PB7 (1U << 7)
#define PC4 (1U << 4)
#define PC7 (1U << 7)
#define PD2 (1U << 2)

// Masked GPIO data: address bits 9:2 select which pins a read or write touches. Only those pins
// change, with no read-modify-write, so the tick and main can't undo each other's writes.
#define GPIO_BITS(base, mask) (*(volatile uint32_t *)((base) + ((mask) << 2)))

struct side
{
	volatile uint32_t *dir;     // The side's IN1/IN2 pins, masked
	uint32_t in1, in2;
	volatile uint32_t *cmp;     // Its PWM compare register
	int reversed;
};

static const struct side LEFT  = { &GPIO_BITS(GPIOA_BASE, PA6 | PA7), PA6, PA7, &PWM0->_0_CMPA, LEFT_REVERSED };
static const struct side RIGHT = { &GPIO_BITS(GPIOC_BASE, PC4 | PC7), PC4, PC7, &PWM0->_0_CMPB, RIGHT_REVERSED };

static volatile uint32_t idle_ms;

static void side_set(const struct side *s, int32_t mv, uint32_t bat_mv)
{
	if (s->reversed) mv = -mv;
	if (mv >  MOTOR_MAX_MV) mv =  MOTOR_MAX_MV;
	if (mv < -MOTOR_MAX_MV) mv = -MOTOR_MAX_MV;

	uint32_t counts = (uint32_t)(mv < 0 ? -mv : mv) * PWM_LOAD / bat_mv;
	if (counts > PWM_LOAD - 1) counts = PWM_LOAD - 1;

	// The output goes high at LOAD and low when the count falls to CMP: high for (LOAD - 1 - CMP)
	*s->cmp = PWM_LOAD - 1 - counts;
	if (mv > 0)      *s->dir = s->in1;     // IN1 high, IN2 low: forward
	else if (mv < 0) *s->dir = s->in2;     // IN1 low, IN2 high: backward
	else             *s->dir = 0;          // Both low: coast, whatever the PWM does
}

void motor_init(void)
{
	SYSCTL->RCGCGPIO |= (1U << 0) | (1U << 1) | (1U << 2) | (1U << 3);   // Ports A to D
	SYSCTL->RCGCPWM  |= (1U << 0);                                       // PWM0
	while ((SYSCTL->PRGPIO & 0xF) != 0xF) {}
	while (!(SYSCTL->PRPWM & (1U << 0))) {}

	// Direction pins and STBY: outputs, low (both motors coasting, driver in standby)
	GPIOA->DIR |= PA6 | PA7;  GPIOA->DEN |= PA6 | PA7;
	GPIOC->DIR |= PC4 | PC7;  GPIOC->DEN |= PC4 | PC7;   // PC0-3 are JTAG: leave them alone
	GPIOD->DIR |= PD2;        GPIOD->DEN |= PD2;
	GPIO_BITS(GPIOA_BASE, PA6 | PA7) = 0;
	GPIO_BITS(GPIOC_BASE, PC4 | PC7) = 0;
	GPIO_BITS(GPIOD_BASE, PD2) = 0;

	// PB6 and PB7 to M0PWM0 and M0PWM1 (PCTL function 4)
	GPIOB->AFSEL |= PB6 | PB7;
	GPIOB->PCTL   = (GPIOB->PCTL & ~0xFF000000U) | 0x44000000U;
	GPIOB->DEN   |= PB6 | PB7;

	SYSCTL->RCC &= ~(1U << 20);       // USEPWMDIV off: the PWM counts at the 80 MHz system clock

	PWM0->_0_CTL  = 0;                // Generator off, count down
	PWM0->_0_GENA = (3U << 2) | (2U << 6);    // A: high at LOAD, low at CMPA going down
	PWM0->_0_GENB = (3U << 2) | (2U << 10);   // B: high at LOAD, low at CMPB going down
	PWM0->_0_LOAD = PWM_LOAD - 1;
	PWM0->_0_CMPA = PWM_LOAD - 1;
	PWM0->_0_CMPB = PWM_LOAD - 1;
	PWM0->_0_CTL  = 1;                // Generator on
	PWM0->ENABLE |= (1U << 0) | (1U << 1);

	GPIO_BITS(GPIOD_BASE, PD2) = PD2; // Out of standby
}

void motor_volts(int32_t left_mv, int32_t right_mv)
{
	uint32_t bat = battery_mv();
	if (bat < BATT_USB_MV || battery_state() == BATT_DEAD)
		left_mv = right_mv = 0;       // No battery, or a flat one: nothing moves
	if (bat < BATT_USB_MV) bat = BATT_USB_MV;   // No divide by 0

	side_set(&LEFT, left_mv, bat);
	side_set(&RIGHT, right_mv, bat);
	idle_ms = 0;
}

void motor_stop(void) { motor_volts(0, 0); }

// The dead-man: whoever drives the motors must keep commanding them
void motor_tick(void)
{
	if (idle_ms < MOTOR_TIMEOUT_MS)
	{
		if (++idle_ms == MOTOR_TIMEOUT_MS)
		{
			GPIO_BITS(GPIOA_BASE, PA6 | PA7) = 0;
			GPIO_BITS(GPIOC_BASE, PC4 | PC7) = 0;
		}
	}
}

// Replaces the startup file's endless loop: a crash stops the tick, so cut the motors here
void HardFault_Handler(void)
{
	GPIO_BITS(GPIOD_BASE, PD2) = 0;   // Standby: both outputs off
	PWM0->ENABLE = 0;
	while (1) {}
}
c
#pragma once
#include <stdint.h>

#define MOTOR_MAX_MV      6000     // The motors' rated voltage: the duty cap (8400 for 12 V N20s)
#define MOTOR_TIMEOUT_MS  100U     // No command for this long: both motors stop

// Flip one if that wheel turns backwards on "forward" (the motors face opposite ways)
#define LEFT_REVERSED     0
#define RIGHT_REVERSED    1

void motor_init(void);
void motor_tick(void);                          // Called every 1 ms from the tick
void motor_volts(int32_t left_mv, int32_t right_mv);   // + forward, - backward, 0 coast
void motor_stop(void);
c
// The 1 kHz system tick. Everything periodic runs from SysTick_Handler:
// buttons, the battery and the motors' dead-man now, then the IMU, encoders and balance loop in later steps.
#include "TM4C123.h"
#include "battery.h"
#include "clock.h"
#include "cycles.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();

	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 ​

  • 20 kHz is above hearing and well under the TB6612's 100 kHz. At 80 MHz that's 4000 counts per period, so one count is about 2 mV at 8 V: finer than the speed loop will ever need.
  • Millivolts, capped at 6 V. The motors are rated 6 V. Full duty on a full battery is 8.4 V, which overspeeds them and wears the brushes. MOTOR_MAX_MV makes the cap the motor's rating, whatever the battery reads. With 12 V N20s the battery can never overdrive them, so set it to 8400.
  • Coast and brake. With both IN pins low the outputs float and the motor coasts. While driving, the PWM's low part shorts the motor through the driver (brake), which keeps speed close to proportional to the voltage command.
  • Masked GPIO writes. On the TM4C123, address bits 9:2 of a port's data register pick which pins a write touches. GPIO_BITS() writes PA6/PA7 without a read-modify-write, so a write from the tick can't be lost to one from main.
  • The dead-man. Whoever drives the motors has to command them at least every 100 ms, or the tick lets them coast. A hung main loop stops the robot. A crash stops the tick too, so HardFault_Handler (which replaces the startup file's weak one) pulls STBY low.
  • Mirrored motors. The two motors face opposite ways, so "forward" spins them in opposite directions. RIGHT_REVERSED flips the right side in software. Fix wiring mistakes the same way, rather than by re-soldering.
  • Stalls. A stalled motor draws more than the TB6612's 1.2 A continuous rating. Don't hold a wheel at full command for long.

Test ​

  1. With R9 and R10 removed, the multimeter shows no continuity between PB6 and PD0, or between PB7 and PD1.
  2. USB only, battery off: start Test and press SW1. The terminal prints each check, but nothing turns: motor_volts() refuses without a battery.
  3. Battery on, wheels in the air. Step through the checks with SW1. On left forward the left wheel turns the way that would drive the robot forward. Same for right forward. If a wheel runs backwards, flip its *_REVERSED in motor.h.
  4. Logic analyser on PB6 during left forward: 20 kHz, high for 3.0 V / battery voltage of each period (37.5% at 8.0 V). The duty rises as the battery drains.
  5. Dead-man check: in test_status(), move the motor_volts() line inside the if (button_pressed(BTN_SW1)) block. Now each SW1 press turns the wheels for 100 ms, then they coast. Put the line back.
  6. On both forward, compare the tick's max cost with Step 3's.

Balance Bot Bootcamp