Try Embedded

Nucleo-F401RE cart-pole in bare-metal C

Balance the cart-pole on a Nucleo-F401RE with registers only: TIM3 and TIM1 count both encoders in hardware, in encoder mode, TIM2 makes the motor's PWM, and…

Control · Advanced

In a real product: Inverted pendulum (Robotics): A motion controller counts its encoders in timers and runs its loop on a tick: no edge is lost, and the timing never drifts.

The same balance loop as the Uno's, in bare-metal C on an STM32 with CMSIS registers only. The encoders are counted by two timers in encoder mode, four counts a cycle, with no interrupts at all, and the loop runs on SysTick. Open the World tool's Cart-pole view to watch it.

What you'll learn

  • Timer encoder mode (SMCR = 3): a quadrature encoder counted in hardware, both edges of both channels
  • Keeping a 32-bit total from a 16-bit counter by adding up its signed changes
  • PWM from TIM2 at 20 kHz, and the direction pins of a TB6612FNG
  • A fixed-rate loop on SysTick, with floating point on the Cortex-M4F
  • Wrapping the pole's angle to ±180° after it swings right round

How it works

The pole's encoder is on PA6/PA7 (D12/D11, TIM3 CH1/CH2) and the cart's on PA8/PA9 (D7/D8, TIM1 CH1/CH2), both in encoder mode 3: 2400 counts a pole turn, 400 a motor turn. Every 2 ms the loop adds each counter's change since the last pass to its total, so a counter that wraps at 65536 never upsets the count.

From the counts it works out the angle (wrapped to ±180°), the cart's place, and their rates, and drives u = KP·angle + KD·rate + KX·x + KV·speed volts: the sign sets AIN1 (PB5) and AIN2 (PB4), the size TIM2's CCR2 on PB3 (D3) out of 800. Past 30° it lets go until the pole is back within 5°. Every 100 ms it prints the angle (in hundredths of a degree), the cart's place (in tenths of a mm) and both counts on USART2.

Try this

  • Run with the Cart-pole view open, and nudge the pole: the timers count every edge however fast it swings.
  • Halve KD and run it again: the pole wobbles before it settles.
  • Change the loop to every 10 ms (nextRun += 10): how much worse does it hold?
  • Compare the cart's count with the model's in the Cart-pole view: the timer counts four a cycle, as the rig does.

main.c

// Bare-metal C on the Nucleo-F401RE balancing the cart-pole. No HAL and no Arduino core:
// CMSIS registers only.
//   TB6612FNG: PWMA on PB3 (D3, TIM2 CH2, AF1, 20 kHz), AIN1 PB5 (D4), AIN2 PB4 (D5); STBY to 3V3, VM from 12 V.
//   Pole encoder on PA6/PA7 (D12/D11, TIM3 CH1/CH2, AF2), cart encoder on PA8/PA9 (D7/D8, TIM1 CH1/CH2, AF1): both
//   in encoder mode 3, four counts a cycle: 2400 a pole turn (600 PPR), 400 a motor turn (100 PPR, 62.8 mm of belt).
//   Every 2 ms (SysTick): u = KP·angle + KD·rate + KX·x + KV·speed, in volts of the 12 V supply. Past 30° it lets go.
//   Every 100 ms on USART2 (PA2, AF7, 115200): "angle <0.01 deg> x <0.1 mm> pole <counts> cart <counts>".
#include "stm32f4xx.h"

#define KP 1.5f      // volts per degree
#define KD 0.08f     // volts per degree a second
#define KX 0.08f     // volts per mm
#define KV 0.02f     // volts per mm a second
#define DT 0.002f
#define POLE_PER_DEG (2400.0f / 360.0f)
#define CART_PER_MM (400.0f / 62.83f)

static volatile uint32_t ticks;

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

// Drives the motor at volts (of 12), forwards or back.
static void drive(float volts) {
  if (volts > 12) volts = 12;
  if (volts < -12) volts = -12;
  if (volts >= 0) GPIOB->BSRR = GPIO_BSRR_BS5 | GPIO_BSRR_BR4;
  else GPIOB->BSRR = GPIO_BSRR_BR5 | GPIO_BSRR_BS4;
  TIM2->CCR2 = (uint32_t)((volts < 0 ? -volts : volts) / 12.0f * 800.0f);
}

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

  // PA2 AF7 (USART2 TX); PA6, PA7 AF2 (TIM3); PA8, PA9 AF1 (TIM1).
  GPIOA->MODER = (GPIOA->MODER & ~(GPIO_MODER_MODER2 | GPIO_MODER_MODER6 | GPIO_MODER_MODER7 | GPIO_MODER_MODER8 | GPIO_MODER_MODER9))
                 | GPIO_MODER_MODER2_1 | GPIO_MODER_MODER6_1 | GPIO_MODER_MODER7_1 | GPIO_MODER_MODER8_1 | GPIO_MODER_MODER9_1;
  GPIOA->AFR[0] = (GPIOA->AFR[0] & ~0xFF000F00u) | (7u << 8) | (2u << 24) | (2u << 28);
  GPIOA->AFR[1] = (GPIOA->AFR[1] & ~0xFFu) | (1u << 0) | (1u << 4);
  // PB3 AF1 (TIM2 CH2); PB4, PB5 outputs (AIN2, AIN1).
  GPIOB->MODER = (GPIOB->MODER & ~(GPIO_MODER_MODER3 | GPIO_MODER_MODER4 | GPIO_MODER_MODER5))
                 | GPIO_MODER_MODER3_1 | GPIO_MODER_MODER4_0 | GPIO_MODER_MODER5_0;
  GPIOB->AFR[0] = (GPIOB->AFR[0] & ~0xF000u) | (1u << 12);

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

  // TIM2 CH2: 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->CCER = TIM_CCER_CC2E;
  TIM2->EGR = TIM_EGR_UG;
  TIM2->CR1 = TIM_CR1_ARPE | TIM_CR1_CEN;

  // TIM3 (pole) and TIM1 (cart): encoder mode 3, the full 16-bit range, counting from where the rig powers up.
  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;
  }

  SysTick_Config(SystemCoreClock / 1000);
  float lastAngle = 0, lastX = 0, rate = 0, speed = 0;
  int holding = 1;
  uint32_t nextRun = 2, nextPrint = 100;
  uint16_t last[2] = {0, 0};
  long total[2] = {0, 0};
  for (;;) {
    while (ticks < nextRun) {}
    nextRun += 2;
    // The 16-bit counters' changes added up into 32-bit totals, so a pole that swings round many times still counts.
    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;
    }
    long pole = total[0], cart = total[1];
    // The pole can swing right round: wrap its count to within half a turn of upright.
    long wrapped = pole % 2400;
    if (wrapped > 1200) wrapped -= 2400;
    if (wrapped < -1200) wrapped += 2400;
    float angle = wrapped / POLE_PER_DEG, x = cart / CART_PER_MM;
    float change = angle - lastAngle;
    if (change > 180) change -= 360;
    if (change < -180) change += 360;
    rate += (change / DT - rate) * 0.5f;
    speed += ((x - lastX) / DT - speed) * 0.3f;
    lastAngle = angle;
    lastX = x;
    float a = angle < 0 ? -angle : angle;
    if (holding && a > 30) holding = 0;
    if (!holding && a < 5) holding = 1;
    drive(holding ? KP * angle + KD * rate + KX * x + KV * speed : 0);
    if (ticks >= nextPrint) {
      nextPrint += 100;
      print("angle ");
      print_int((long)(angle * 100));
      print(" x ");
      print_int((long)(x * 10));
      print(" pole ");
      print_int(pole);
      print(" cart ");
      print_int(cart);
      print("\r\n");
    }
  }
}

Lessons behind it