Try Embedded

Nucleo-F401RE line follower in bare-metal C

The two-wheel robot on a Nucleo-F401RE, registers only: ADC1 reads the five IR sensors in turn, TIM2 makes the two motors' PWM, and TIM3 and TIM1 count the…

Control · Advanced

In a real product: Line-following robot (Robotics): A production robot's motor controller counts its encoders in a timer, not in interrupts: no edge is lost at any speed.

A PD line follower on an STM32, in bare-metal C with CMSIS registers only. Everything the Arduino core did is yours: the ADC conversions, the PWM timer and, best of all, the wheel encoders, which two timers count in hardware. Open the World tool's Arena view to watch it.

What you'll learn

  • ADC1 single conversions by software start (SQR3, SWSTART, EOC) on five channels
  • TIM2 CH2 and CH3 in PWM mode 1 at 20 kHz, on alternate-function pins
  • TIM3 and TIM1 in encoder mode 3: four counts a cycle, the direction from A against B, no CPU time at all
  • Turning 16-bit timer counts into 32-bit totals that never wrap
  • A 5 ms control loop paced by SysTick

How it works

The IR sensors are on A0–A4 (PA0, PA1, PA4, PB0, PC1: ADC1 channels 0, 1, 4, 8 and 11), in analog mode. Every 5 ms the loop converts each in turn: write its channel to SQR3, set SWSTART, wait for EOC, read DR. At 3.3 V the readings run from about 250 over the mat to 3690 over the tape.

TIM2 runs at 16 MHz / 800 = 20 kHz; CCR2 and CCR3 set the left and right duty on PB3 and PB10 (AF1). The encoders' A and B go to TIM3's CH1 and CH2 (PA6, PA7) and TIM1's (PA8, PA9): with SMCR SMS = 3 the counters count every edge of both inputs, up when A leads, down when B does. The robot's encoders are on the motor shafts, 210 cycles a wheel turn: 840 counts. Each loop adds the signed 16-bit difference since the last one to a 32-bit total, so the counts survive the counters wrapping every 78 wheel turns.

Try this

  • Run it with the Arena view open and compare the totals it prints with the counts in the robot's HUD.
  • Work out each wheel's speed from the change in its total every 5 ms (840 counts a turn, a 42 mm wheel).
  • Change the scene to line-sharp: can you find gains that take its right angles?
  • Use the speeds: a slower BASE on the bends (when |pos| is large) and a faster one on the straights.

main.c

// A line follower in bare-metal C on the Nucleo-F401RE: PD on the line's position. No HAL and no Arduino core: CMSIS
// registers only.
//   IR1..IR5 on A0 PA0, A1 PA1, A2 PA4, A3 PB0, A4 PC1 (ADC1 channels 0, 1, 4, 8, 11), converted one after the other
//   every 5 ms (SysTick).
//   PWMA on PB3 (D3, TIM2 CH2) and PWMB on PB10 (D6, TIM2 CH3), AF1, 20 kHz. AIN1 PB5 (D4) and BIN1 PA10 (D2) high;
//   AIN2, BIN2 to GND and STBY to 3V3, so the wheels only go forwards.
//   Left encoder on PA6/PA7 (D12/D11, TIM3 CH1/CH2, AF2), right on PA8/PA9 (D7/D8, TIM1 CH1/CH2, AF1): both in
//   encoder mode 3, four counts a cycle; the 16-bit counters' changes are added up into 32-bit totals.
//   Every 250 ms it prints "ir3 <raw> l <left> r <right>" on USART2 (PA2, AF7) at 115200.
#include "stm32f4xx.h"

#define BASE 530        // duty out of 800
#define KP 38.0f        // duty per mm
#define KD 470.0f       // duty per mm of change in 5 ms

static volatile uint32_t ticks;
static const uint8_t channels[5] = {0, 1, 4, 8, 11};

void SysTick_Handler(void) { ticks++; }

static void print(const char *s) {
  while (*s) {
    while (!(USART2->SR & USART_SR_TXE)) {}
    USART2->DR = *s++;
  }
}

static void print_int(long n) {
  char buf[12];
  int i = 11;
  int negative = n < 0;
  unsigned long u = negative ? -n : n;
  buf[i] = 0;
  do { buf[--i] = '0' + u % 10; u /= 10; } while (u);
  if (negative) buf[--i] = '-';
  print(&buf[i]);
}

static int adc_read(uint8_t channel) {
  ADC1->SQR3 = channel;
  ADC1->CR2 |= ADC_CR2_SWSTART;
  while (!(ADC1->SR & ADC_SR_EOC)) {}
  return (int)ADC1->DR;
}

static int clamp(int x, int lo, int hi) { return x < lo ? lo : x > hi ? hi : x; }

int main(void) {
  RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN | RCC_AHB1ENR_GPIOBEN | RCC_AHB1ENR_GPIOCEN;
  RCC->APB1ENR |= RCC_APB1ENR_USART2EN | RCC_APB1ENR_TIM2EN | RCC_APB1ENR_TIM3EN;
  RCC->APB2ENR |= RCC_APB2ENR_TIM1EN | RCC_APB2ENR_ADC1EN;

  // PA0, PA1, PA4 analog; PA2 AF7; PA6, PA7 AF2; PA8, PA9 AF1; PA10 output.
  GPIOA->MODER = (GPIOA->MODER & ~(GPIO_MODER_MODER0 | GPIO_MODER_MODER1 | GPIO_MODER_MODER2 | GPIO_MODER_MODER4
                                   | GPIO_MODER_MODER6 | GPIO_MODER_MODER7 | GPIO_MODER_MODER8 | GPIO_MODER_MODER9
                                   | GPIO_MODER_MODER10))
                 | GPIO_MODER_MODER0 | GPIO_MODER_MODER1 | GPIO_MODER_MODER4
                 | GPIO_MODER_MODER2_1 | GPIO_MODER_MODER6_1 | GPIO_MODER_MODER7_1
                 | GPIO_MODER_MODER8_1 | GPIO_MODER_MODER9_1 | GPIO_MODER_MODER10_0;
  GPIOA->AFR[0] = (GPIOA->AFR[0] & ~0xFF000F00u) | (7u << 8) | (2u << 24) | (2u << 28);
  GPIOA->AFR[1] = (GPIOA->AFR[1] & ~0xFFu) | (1u << 0) | (1u << 4);
  // PB0 analog; PB3, PB10 AF1; PB5 output.
  GPIOB->MODER = (GPIOB->MODER & ~(GPIO_MODER_MODER0 | GPIO_MODER_MODER3 | GPIO_MODER_MODER5 | GPIO_MODER_MODER10))
                 | GPIO_MODER_MODER0 | GPIO_MODER_MODER3_1 | GPIO_MODER_MODER5_0 | GPIO_MODER_MODER10_1;
  GPIOB->AFR[0] = (GPIOB->AFR[0] & ~0xF000u) | (1u << 12);
  GPIOB->AFR[1] = (GPIOB->AFR[1] & ~0xF00u) | (1u << 8);
  // PC1 analog.
  GPIOC->MODER |= GPIO_MODER_MODER1;

  USART2->BRR = SystemCoreClock / 115200;   // 16 MHz HSI after reset
  USART2->CR1 = USART_CR1_TE | USART_CR1_UE;

  // Both motors forwards.
  GPIOB->BSRR = GPIO_BSRR_BS5;
  GPIOA->BSRR = GPIO_BSRR_BS10;

  // TIM2 CH2 and CH3: PWM mode 1 at 16 MHz / 800 = 20 kHz.
  TIM2->PSC = 0;
  TIM2->ARR = 799;
  TIM2->CCMR1 = (6u << TIM_CCMR1_OC2M_Pos) | TIM_CCMR1_OC2PE;
  TIM2->CCMR2 = (6u << TIM_CCMR2_OC3M_Pos) | TIM_CCMR2_OC3PE;
  TIM2->CCER = TIM_CCER_CC2E | TIM_CCER_CC3E;
  TIM2->EGR = TIM_EGR_UG;
  TIM2->CR1 = TIM_CR1_ARPE | TIM_CR1_CEN;

  // TIM3 and TIM1: encoder mode 3, TI1 and TI2 mapped to themselves, the full 16-bit range.
  TIM_TypeDef *encoders[2] = {TIM3, TIM1};
  for (int i = 0; i < 2; i++) {
    encoders[i]->CCMR1 = TIM_CCMR1_CC1S_0 | TIM_CCMR1_CC2S_0;
    encoders[i]->CCER = 0;
    encoders[i]->SMCR = 3u;
    encoders[i]->ARR = 0xFFFF;
    encoders[i]->CNT = 0;
    encoders[i]->CR1 = TIM_CR1_CEN;
  }

  // ADC1: 12 bits, 84 cycles a sample on the five channels, single conversions started by software.
  ADC1->SMPR2 = (4u << ADC_SMPR2_SMP0_Pos) | (4u << ADC_SMPR2_SMP1_Pos) | (4u << ADC_SMPR2_SMP4_Pos) | (4u << ADC_SMPR2_SMP8_Pos);
  ADC1->SMPR1 = 4u << ADC_SMPR1_SMP11_Pos;
  ADC1->CR2 = ADC_CR2_ADON;

  SysTick_Config(SystemCoreClock / 1000);
  uint16_t last[2] = {0, 0};
  long total[2] = {0, 0};
  float lastPos = 0;
  int raw3 = 0;
  uint32_t nextRun = 5, nextPrint = 250;
  for (;;) {
    while (ticks < nextRun) {}
    nextRun += 5;
    float sum = 0, weighted = 0;
    for (int i = 0; i < 5; i++) {
      int raw = adc_read(channels[i]);
      if (i == 2) raw3 = raw;
      // About 250 over the mat and 3690 over the tape at the robot's 3.3 V.
      float c = (raw - 250) / 3440.0f;
      c = c < 0 ? 0 : c > 1 ? 1 : c;
      sum += c;
      weighted += c * (2 - i) * 12.0f;
    }
    float pos = sum > 0.2f ? weighted / sum : (lastPos > 0 ? 30.0f : -30.0f);
    float u = KP * pos + KD * (pos - lastPos);
    lastPos = pos;
    TIM2->CCR2 = clamp((int)(BASE - u), 0, 800);
    TIM2->CCR3 = clamp((int)(BASE + u), 0, 800);
    for (int i = 0; i < 2; i++) {
      uint16_t now = (uint16_t)encoders[i]->CNT;
      total[i] += (int16_t)(now - last[i]);
      last[i] = now;
    }
    if (ticks >= nextPrint) {
      nextPrint += 250;
      print("ir3 ");
      print_int(raw3);
      print(" l ");
      print_int(total[0]);
      print(" r ");
      print_int(total[1]);
      print("\r\n");
    }
  }
}

Lessons behind it