Back to Blog

Building a Self Balancing Robot With an STM32

Embedded SystemsSTM32RoboticsFirmware

Full Specifications: https://docs.google.com/document/d/1Oy3eVqCZ4Oq2Mm3snnbUVZMDKufbxnAgHCzB2ccyURE/edit?usp=sharing

Github Link: https://github.com/sarbagyag/stm32-self-balancing-robot.git

This project marked my first serious attempt at embedded firmware, and I chose something with an immediate, physical payoff: a robot that has to balance on two wheels using nothing but its own sensors and a microcontroller.

Talking Directly to the Hardware

I wrote everything in bare metal C for an STM32 microcontroller built around an ARM Cortex M core, using both the HAL and Low Layer drivers depending on how much direct control I needed over a given peripheral. That level of access matters here, because balancing a robot is fundamentally a timing problem, and timing problems do not forgive sloppy code.

Learning to Trust Noisy Sensors

An MPU6050 sensor gives raw accelerometer and gyroscope readings over I2C, but neither signal is trustworthy on its own. The accelerometer is noisy in the short term, while the gyroscope drifts over time. I implemented a real time complementary filter that blends the two together, leaning on the gyroscope for fast changes and the accelerometer to correct long term drift, which produces a single stable estimate of the robot's tilt angle.

Closing the Loop

Motor control runs through hardware PWM timers, with UART over USB CDC streaming live telemetry back to my laptop so I can actually see what the robot thinks its own angle is while it moves. Right now I am in the middle of the final piece: wiring in an L298N motor driver and tuning a discrete PID controller so the robot can hold itself upright without me catching it every few seconds. It is not fully balancing on its own yet, but it is close, and that gap between almost and actually working has taught me more about control systems than any textbook did.