Skip to content

Logging ​

From now on, each test prints its numbers. This step routes printf to UART0, which reaches the laptop through the debug USB cable. It also uses the cycle counter to time the 1 kHz tick handler. That handler is about to take on the encoders, the IMU and the balance loop, and it must always finish well inside its 1 ms (80,000 cycles).

Hardware: the LaunchPad alone.

What you add ​

FileWhat it does
uart.cUART0 at 115200 8N1 on PA0/PA1. _write() sends printf output there, and stubs cover newlib's other calls
cycles.hDWT CYCCNT, a cycle counter running at 80 MHz (12.5 ns per count)
tick.cChanged: the handler times itself and keeps its last and worst cost
main.cChanged: prints a boot line and the selected mode. Test mode prints the tick's cost once a second

clock.c and ui.c are unchanged from Step 1.

c
// The robot's main program. Each step fills in a mode; Test now prints the tick's health.
#include <stdio.h>
#include "TM4C123.h"
#include "clock.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" };

// Once a second until SW2: uptime and how much of each 1 ms tick the handler uses
static void test_status(void)
{
	uint32_t next = millis();
	while (!button_pressed(BTN_SW2))
	{
		if ((int32_t)(millis() - next) < 0) continue;
		next += 1000;
		uint32_t max = tick_cycles_max();
		printf("t=%lu s  tick: last %lu cyc, max %lu cyc (%lu.%02lu%% of 1 ms)\n",
		       millis() / 1000, tick_cycles_last(), max,
		       max * 100 / 80000, max * 10000 / 80000 % 100);
	}
}

static void run(uint32_t mode)
{
	printf("mode: %s\n", mode_name[mode]);
	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();
	tick_init();

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

	uint32_t mode = MODE_BALANCE;
	while (1)
	{
		mode = ui_menu(mode_colour, N_MODES, mode);
		run(mode);
	}
}
c
// UART0 to the LaunchPad's USB serial port, and printf on top of it
#include <stdio.h>
#include <sys/stat.h>
#include "TM4C123.h"
#include "clock.h"
#include "uart.h"

#define RCGC_UART0   (1U << 0)
#define RCGC_GPIOA   (1U << 0)
#define U0RX         (1U << 0)           // PA0
#define U0TX         (1U << 1)           // PA1
#define PCTL_PA01_M  0xFFU
#define PCTL_PA01_U0 0x11U               // Function 1 on PA0 and PA1: U0RX, U0TX

#define BAUD         115200U
#define BRD_X64      ((CPU_HZ * 4U + BAUD / 2) / BAUD)   // 64 * CPU_HZ / (16 * BAUD), rounded
#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_TXFF      (1U << 5)

void uart_init(void)
{
	SYSCTL->RCGCUART |= RCGC_UART0;
	SYSCTL->RCGCGPIO |= RCGC_GPIOA;
	while ((SYSCTL->PRGPIO & RCGC_GPIOA) == 0) {}
	while ((SYSCTL->PRUART & RCGC_UART0) == 0) {}

	GPIOA->AFSEL |= U0RX | U0TX;
	GPIOA->PCTL = (GPIOA->PCTL & ~PCTL_PA01_M) | PCTL_PA01_U0;
	GPIOA->DEN |= U0RX | U0TX;

	UART0->CTL = 0;                      // Off while it's set up
	UART0->IBRD = BRD_X64 / 64;          // 80 MHz: 43
	UART0->FBRD = BRD_X64 % 64;          //         26  (43.406 vs 43.403: 0.008% off)
	UART0->LCRH = LCRH_WLEN_8 | LCRH_FEN;   // Writing LCRH latches the divisor
	UART0->CC = 0;                       // Clocked from the system clock
	UART0->CTL = CTL_UARTEN | CTL_TXE | CTL_RXE;

	setvbuf(stdout, NULL, _IONBF, 0);    // printf sends at once, no buffer to flush
}

void uart_putc(char c)
{
	while (UART0->FR & FR_TXFF) {}       // 16-byte FIFO: waits only when it's full
	UART0->DR = c;
}

// newlib calls this for printf and puts. "\n" goes out as "\r\n" for terminals.
int _write(int fd, const char *buf, int len)
{
	(void)fd;
	for (int i = 0; i < len; i++)
	{
		if (buf[i] == '\n') uart_putc('\r');
		uart_putc(buf[i]);
	}
	return len;
}

// The rest of the calls newlib's stdio makes. There is no file system: only stdout.
int _close(int fd) { (void)fd; return -1; }
int _read(int fd, char *buf, int len) { (void)fd; (void)buf; (void)len; return 0; }
int _lseek(int fd, int off, int whence) { (void)fd; (void)off; (void)whence; return 0; }
int _isatty(int fd) { (void)fd; return 1; }
int _fstat(int fd, struct stat *st) { (void)fd; st->st_mode = S_IFCHR; return 0; }
c
#pragma once
#include <stdint.h>

void uart_init(void);                    // UART0 on PA0/PA1, 115200 8N1, through the debug USB port
void uart_putc(char c);
c
#pragma once
#include "TM4C123.h"

// The Cortex-M4 cycle counter (DWT CYCCNT): 12.5 ns per count at 80 MHz, wraps every 53 s.
// Subtracting two readings as uint32_t is right across one wrap.
static inline void cycles_init(void)
{
	CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;   // Turn the trace blocks on
	DWT->CYCCNT = 0;
	DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
}

static inline uint32_t cycles(void) { return DWT->CYCCNT; }
c
// The 1 kHz system tick. Everything periodic runs from SysTick_Handler:
// buttons now, then the IMU, encoders and balance loop in later steps.
#include "TM4C123.h"
#include "clock.h"
#include "cycles.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();

	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);
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 it

Notes ​

  • Baud divisor: 80 MHz / (16 × 115200) = 43.403. That's IBRD = 43, and FBRD = 0.403 × 64 ≈ 26. BRD_X64 works both out from CPU_HZ. The divisor only takes effect when LCRH is written, so write LCRH after IBRD and FBRD.
  • printf costs about 5 KB of flash (newlib-nano), out of 256 KB. It blocks only when the 16-byte FIFO is full. A full status line takes about 6 ms at 115200 baud, so never call it from the tick. Printing floats would need -u _printf_float in LDFLAGS. The code prints integers instead.
  • Stdout is unbuffered (setvbuf), so a line goes out as it's printed, even without a \n.
  • The tick's cost is measured from inside the handler, so it leaves out the roughly 12 cycles of interrupt entry and exit. tick_cycles_max() resets the worst case each time it's read, so each status line shows the worst tick of the last second.

Test ​

  1. Open a terminal on the LaunchPad's serial port at 115200 baud: screen /dev/tty.usbmodem* 115200 on macOS, or picocom -b 115200 /dev/ttyACM0 on Linux.
  2. Press the board's RESET button. You should see balance-bot: 80 MHz, built ….
  3. Pick a mode with SW1 and start it with SW2. The terminal prints mode: …, and menu when SW2 takes you back.
  4. Start Test (magenta). Every second it prints t=… s tick: last … cyc, max … cyc (…% of 1 ms). The handler only debounces the buttons so far, so expect well under 1%. Write the max down: it's the baseline that each later step adds to.

Balance Bot Bootcamp