Skip to content

Blue Pill · Build guide

STM32 Distance Measurement System with OLED Display

Measure distance in real time with an HC-SR04 ultrasonic sensor and an STM32 Blue Pill, with live readings on an SSD1306 OLED. PlatformIO setup, wiring with the Echo voltage divider, timing explained, accuracy testing and troubleshooting.

STM32 Distance Measurement System with OLED Display
Difficulty
Beginner
Read time
14 min
Board
Blue Pill
Author
Manish Pal
Published
Oct 28, 2026
Views
11

Why Build This

Distance sensing shows up everywhere: parking assistants, liquid level monitors, obstacle-avoiding robots and smart dustbins that open when you approach. The HC-SR04 ultrasonic sensor is one of the cheapest and most forgiving ways to start measuring distance. Pairing it with an STM32 "Blue Pill" instead of an Arduino Uno gives you a 72 MHz ARM Cortex-M3 core, 3.3 V logic and a path toward professional embedded work, for about the price of an Uno clone.

This project reads live distance data from an HC-SR04 and shows it on a 128×64 SSD1306 OLED, while also streaming it over serial for debugging. You can finish it in an evening, and it teaches the ideas that matter on any microcontroller: timing a pulse, talking to an I2C display, protecting a 3.3 V pin from a 5 V signal, and handling a missing echo without crashing.

What you will learn:

  • How an ultrasonic sensor turns time into distance, and how to read that time with pulseIn()
  • Why the HC-SR04's 5 V Echo signal needs a voltage divider on the Blue Pill
  • How to set up a PlatformIO project for an STM32 and flash it over SWD with an ST-Link
  • How to read an SSD1306 OLED over I2C and show a clear "No Echo" state
  • How to test accuracy honestly and improve it with filtering and temperature compensation

Time: about two hours. Skill level: beginner, with careful wiring.

⚠️ Warning

The Blue Pill runs on 3.3 V logic, but the HC-SR04's Echo pin outputs a 5 V signal. Pin PA1 is an analog-capable pin, and on the F103 such pins are not 5 V tolerant, so feeding 5 V into it can damage the microcontroller permanently. Always use a voltage divider (a 1 kΩ and 2 kΩ pair is a common choice) to bring the Echo signal down to about 3.3 V before it reaches PA1. Some other F103 pins are marked "FT" (5 V tolerant) in the datasheet, but a divider is the safe habit.

Components

8 items
NameQtyLink
STM32F103C8T6 Blue Pill×1—
HC-SR04 ultrasonic sensor×1—
SSD1306 OLED display, 128×64, I2C×1—
ST-Link V2 programmer×1—
Breadboard and jumper wires×1—
1 kΩ resistor (Echo divider, upper)×1—
2 kΩ resistor (Echo divider, lower)×1—
USB cable (for power)×1—

Need these parts? Get this build sheet by email

Parts list with buy links, plus new builds as they're published. By subscribing you agree to our Privacy Policy. Unsubscribe anytime.

Know Your Board

The Blue Pill is a small, cheap board built around an STM32F103C8T6: a 72 MHz Cortex-M3 with 20 KB of RAM and, officially, 64 KB of flash (many boards actually carry 128 KB). It has 3.3 V logic, an SWD programming header, and no hardware floating-point unit, which matters later.

Three practical facts save a lot of frustration:

  • Clones are common. Many "Blue Pills" use clone chips (CKS32, CS32, GD32 and others). They usually run this project fine, but the ST-Link may report a different chip ID. The troubleshooting table shows the fix.
  • Boot jumpers. For programming over SWD and for normal running, both BOOT0 and BOOT1 stay at 0. Setting BOOT0 to 1 starts the built-in serial bootloader instead of your program, which is a different way of flashing.
  • Power. The board's 5V pin is connected to USB power. The HC-SR04 needs real 5 V, so power the Blue Pill from its USB port (or feed 5 V into the 5V pin). Powering it from the ST-Link's 3.3 V alone leaves the sensor underpowered.

How an Ultrasonic Sensor Measures Distance

The HC-SR04 is a small speaker and microphone in one module. It measures distance in four steps:

  1. Your code pulls Trig HIGH for 10 microseconds.
  2. The sensor sends a burst of eight ultrasonic pulses at 40 kHz.
  3. The sensor raises Echo HIGH and keeps it HIGH until the reflection comes back.
  4. Your code measures how long Echo stayed HIGH. That is the round-trip time of the sound.

Sound travels at about 343 m/s in air at room temperature, which is 0.0343 cm per microsecond. Because the pulse travels to the object and back, you halve the result:

Output
distance (cm) = echo time (µs) × 0.0343 ÷ 2

A useful rule of thumb follows from that: about 58 µs of echo per centimetre. The timing diagram shows the signals, and the graph shows how echo time grows with distance, including the 30 ms timeout used in the sketch.

Timing diagram: 10 µs trigger pulse, eight ultrasonic bursts, and the echo pulse whose width is the round-trip time
Graph: echo pulse width versus distance, with the 2 cm minimum, 400 cm rated range and the 30 ms timeout marked

Wiring the Circuit

HC-SR04 pinConnects to
VCC5V pin of the Blue Pill (live when powered by USB)
GNDGND
TrigPA0
EchoPA1, through the voltage divider

Building the divider. Connect Echo to one end of the 1 kΩ resistor, connect the other end of that resistor to PA1, and connect the 2 kΩ resistor from PA1 to GND. The two resistors scale 5 V by 2/3, which gives about 3.3 V. Trig is an output from the STM32 at 3.3 V, which the HC-SR04 accepts as a valid HIGH, so it needs no protection.

SSD1306 pinConnects to
VCC3V3
GNDGND
SDAPB7 (I2C1 SDA)
SCLPB6 (I2C1 SCL)

I2C1 on the Blue Pill uses PB6 for the clock and PB7 for the data line. If your board or a custom package remaps those pins, follow your own pinout. If the display stays blank, run an I2C scanner before suspecting the OLED.

Wiring diagram: HC-SR04 with a 1 kΩ and 2 kΩ divider on Echo, SSD1306 OLED on PB6 and PB7, and the ST-Link programming header

Setting Up the PlatformIO Project

This project uses PlatformIO instead of the Arduino IDE. It gives you proper dependency management, repeatable builds and cleaner version control, which matter once a project grows past a single sketch. Install the PlatformIO extension in VS Code, create a project for the board genericSTM32F103C8 with the Arduino framework, and use this platformio.ini:

INI
; PlatformIO Project Configuration File
; https://docs.platformio.org/page/projectconf.html

[env:genericSTM32F103C8]
platform = ststm32
board = genericSTM32F103C8
framework = arduino
upload_protocol = stlink

monitor_speed = 115200

build_flags =
    -D PIO_FRAMEWORK_ARDUINO_ENABLE_CDC
    -D ENABLE_HWSERIAL1

lib_deps =
    adafruit/Adafruit SSD1306
    adafruit/Adafruit GFX Library

What each part does:

  • platform = ststm32 downloads the STM32 toolchain.
  • framework = arduino lets you use the familiar digitalWrite, pinMode and Serial calls through the STM32duino core.
  • upload_protocol = stlink flashes over SWD with your ST-Link.
  • PIO_FRAMEWORK_ARDUINO_ENABLE_CDC makes Serial appear as a USB serial port instead of a hardware UART. If the Serial Monitor shows nothing, remember that USB serial on many Blue Pills needs a correct USB pull-up (many boards ship with a wrong resistor on the USB D+ line). The OLED and the sketch work without it, so the serial output is a convenience.
  • ENABLE_HWSERIAL1 keeps the hardware serial port on USART1 (PA9 and PA10) available as Serial1, which is handy for a USB-to-serial adapter when Serial is taken by USB.
  • lib_deps fetches Adafruit's SSD1306 driver and the GFX library it needs.

Connect the ST-Link to the Blue Pill's four-pin SWD header: SWDIO to DIO, SWCLK to DCLK, GND to GND and 3.3 V to 3.3 V. Keep the board's USB cable connected too, so the 5V pin is live for the sensor.

The Code

Here is the complete src/main.cpp. Compared with the simplest version, it checks that the display actually started, instead of drawing into a display that is not there, and it uses float literals, which suit a processor without a floating-point unit.

sketch.ino
#include <Arduino.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

#define TRIG_PIN PA0
#define ECHO_PIN PA1

float distance;

// Returns the distance in cm, or -1 when no echo arrives within 30 ms
float measureDistance()
{
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);

  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);

  digitalWrite(TRIG_PIN, LOW);

  long duration = pulseIn(ECHO_PIN, HIGH, 30000);

  if (duration == 0)
  return -1;

  return duration * 0.0343f / 2.0f;
}

void setup()
{
  Serial.begin(115200);

  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);

  Wire.begin();

  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C))
  {
    Serial.println("SSD1306 not found: check wiring and I2C address");
    while (true)
    delay(1000);
  }

  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE);

  display.setTextSize(2);
  display.setCursor(10, 20);
  display.println("START");
  display.display();

  delay(1500);
}

void loop()
{
  distance = measureDistance();

  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  display.clearDisplay();

  display.setTextSize(1);
  display.setCursor(0, 0);
  display.println("Ultrasonic Sensor");

  display.drawLine(0, 12, 128, 12, SSD1306_WHITE);

  display.setTextSize(2);
  display.setCursor(5, 30);

  if (distance < 0)
  {
    display.print("No Echo");
  }
  else
  {
    display.print(distance, 1);
    display.print(" cm");
  }

  display.display();

  delay(100);
}

How the Code Works

The measurement function

sketch.ino
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);

The 2 µs LOW guarantees a clean starting level. The 10 µs HIGH is the trigger the HC-SR04 datasheet specifies, so shortening it can make triggering unreliable and lengthening it gains nothing.

sketch.ino
long duration = pulseIn(ECHO_PIN, HIGH, 30000);

pulseIn() waits for Echo to go HIGH, then measures how long it stays HIGH, in microseconds. The third argument is a timeout of 30,000 µs. Without it, a missing echo would block the program for a very long time. A 30 ms echo corresponds to about 5 m of distance, comfortably beyond the sensor's rated 4 m, so every real measurement fits inside it.

sketch.ino
if (duration == 0) return -1;
return duration * 0.0343f / 2.0f;

A timeout makes pulseIn() return 0. The function converts that into -1, a sentinel that cannot be a real distance. The f suffixes matter on this chip. The Cortex-M3 has no floating-point hardware, so float maths is done in software, and a plain 0.0343 literal is a double that would make each calculation slower still. It makes no difference at 10 readings per second, but it is a good habit for faster loops.

Starting the display

Wire.begin() starts I2C1. display.begin(SSD1306_SWITCHCAPVCC, 0x3C) tells the driver that the display makes its own panel voltage with an internal charge pump (true of nearly all small modules) and gives its I2C address. Most modules answer at 0x3C, and some at 0x3D. If begin() fails, the sketch prints a message and stops, so a wiring or address fault is obvious instead of silent.

The loop

Each pass takes a reading, prints it, clears the screen, draws a header with a divider line and then shows either the distance with one decimal or the words No Echo. Showing text for the error case, instead of a negative number, is a small detail that makes a project feel finished. One decimal place also matches the sensor's real accuracy, since more digits would imply precision it does not have.

The closing delay(100) limits the update to about 10 Hz. The HC-SR04 datasheet recommends a measurement cycle of at least 60 ms, so that one echo cannot be mistaken for the next.

Upload and First Run

Steps

  1. 1Connect the ST-Link to the SWD header (SWDIO, SWCLK, GND, 3.3 V) and plug the Blue Pill into USB for power.
  2. 2Check that BOOT0 and BOOT1 are both set to 0.
  3. 3In PlatformIO, click Build first to confirm that both libraries download and the project compiles.
  4. 4Click Upload. PlatformIO flashes the board over SWD.
  5. 5Watch the OLED: it shows START for 1.5 seconds and then the live distance.
  6. 6Open the Serial Monitor at 115200 baud to see the same readings, if your USB serial is working.
  7. 7Point the sensor at a wall and move it closer and further away. The reading should follow smoothly.

Check the Accuracy Properly

A number on a screen is not a measurement until you have checked it. Use a ruler and a flat, hard target such as a book or a wall, and keep the sensor facing it squarely.

True distanceEcho time you should see (20 °C)Your reading (cm)
10 cmabout 583 µs
20 cmabout 1166 µs
50 cmabout 2915 µs
100 cmabout 5831 µs

The echo times are calculated from 343 m/s, so they show what a perfect sensor would measure. Fill in your own readings. On a flat, perpendicular target you should expect agreement of roughly a centimetre. How to read the results:

  • The same offset at every distance points to where you measured from. The reference is the front face of the transducers, not the edge of the PCB.
  • An error that grows with distance suggests the speed of sound is wrong for your room temperature. Compensation fixes this.
  • Readings that jump around point to a soft, angled or tiny target, or reflections from nearby objects.

What the sensor cannot do well

The HC-SR04 sends a cone of roughly 15 degrees, so it "sees" the nearest object anywhere in that cone, not just the one in front of it. Soft materials such as fabric and foam absorb sound, steeply angled surfaces reflect the echo away from the sensor, and objects closer than about 2 cm are inside its blind zone. Keep the area in front of the sensor clear, and mount it rigidly.

Improving the Readings

A median filter

Ultrasonic readings occasionally spike. Taking the median of five readings throws away one-off glitches without blurring real changes. Add this function and call it from loop():

sketch.ino
float measureDistanceMedian()
{
  float v[5];
  for (int i = 0; i < 5; i++)
  {
    v[i] = measureDistance();
    delay(60);                     // respect the 60 ms measurement cycle
  }
  // insertion sort (-1 "no echo" values sort to the front)
  for (int i = 1; i < 5; i++)
  {
    float key = v[i];
    int j = i - 1;
    while (j >= 0 && v[j] > key)
    {
      v[j + 1] = v[j];
      j--;
    }
    v[j + 1] = key;
  }
  return v[2];                       // the median
}

// in loop():  distance = measureDistanceMedian();   (and drop the 100 ms delay)

Temperature compensation

The speed of sound rises by about 0.6 m/s for every degree Celsius, which is about 0.17% per degree. Over a 20-degree change that is more than 3%, or 3 cm at 100 cm. If accuracy matters, add a temperature sensor and use the real speed of sound:

sketch.ino
// Speed of sound in air: 331.3 + 0.606 * T  (m/s, T in degrees C)
float measureDistanceCompensated(float tempC)
{
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  long duration = pulseIn(ECHO_PIN, HIGH, 30000);
  if (duration == 0) return -1;

  float cmPerUs = (331.3f + 0.606f * tempC) / 10000.0f;   // m/s to cm/us
  return duration * cmPerUs / 2.0f;
}

How Big Is the Temperature Error?

The main sketch assumes 343 m/s, which is right at about 20 °C. This table shows what it reports for a target that is really 100 cm away, using the speed of sound formula 331.3 + 0.606 × T. The values are calculated, not measured.

Air temperatureSpeed of soundReading for a true 100 cmError
0 °C331.3 m/s103.5 cm+3.5 cm
10 °C337.4 m/s101.7 cm+1.7 cm
20 °C343.4 m/s99.9 cm−0.1 cm
30 °C349.5 m/s98.1 cm−1.9 cm
40 °C355.5 m/s96.5 cm−3.5 cm

The error is the same fraction at any distance, about 0.17% per °C, so it scales. At 200 cm the 0 °C error doubles to about 7 cm. A cold garage or a hot enclosure matters, while a room that stays near 20 °C does not.

Chart: HC-SR04 reading error for a target 100 cm away from 0 to 40 °C when the sketch assumes 343 m/s

Troubleshooting

SymptomLikely causeFix
Upload fails with an "UNEXPECTED idcode" errorClone chip with a different IDAdd upload_flags = -c set CPUTAPID 0x2ba01477 to platformio.ini, using the ID printed in the error message.
ST-Link not detectedDriver, cable or wiringCheck SWDIO and SWCLK are not swapped, install the ST-Link driver, and try another USB port.
Board runs old code after uploadBOOT0 set to 1Set both BOOT jumpers to 0 and press reset.
OLED stays blankWrong address or wiringCheck SDA on PB7 and SCL on PB6, try 0x3D, and run an I2C scanner. The sketch prints a message if the display is not found.
Always shows "No Echo"Sensor unpowered, or Echo not reaching PA1Confirm 5 V on VCC, the Trig and Echo wires, and the divider. Powering from the ST-Link 3.3 V alone will not work.
Readings jump aroundSoft or angled target, or reflectionsAim at a flat surface, clear the cone, and use the median filter.
Readings stuck at one valueLoop running too fast, or echo from the previous pulseKeep at least 60 ms between triggers.
Serial Monitor emptyUSB CDC not enumeratingCheck the USB pull-up on your board, or use a USB-to-serial adapter on PA9 and PA10 with Serial1.
Microcontroller gets hot or fails5 V on a 3.3 V pinFit the voltage divider on Echo before powering up.
Distance wrong by a constant amountMeasurement referenceMeasure from the transducer face, and subtract any constant offset in code.

Ideas to Extend This Project

  • Proximity alert. Add a buzzer that beeps faster as the distance drops, to build a parking sensor.
  • Log the data. Stream readings over serial to a PC or store them on an SD card to graph them later.
  • Two sensors. Add a second HC-SR04 on other pins for front and rear detection on a robot.
  • Non-blocking measurement. Replace pulseIn() with an input-capture timer or interrupts, so the processor can do other work while it waits for the echo.
  • Battery power. The Blue Pill and OLED are low power, so a small Li-ion cell with a regulator makes the project portable.
  • Use a waterproof probe. Sensors such as the JSN-SR04T suit wet environments, with a larger minimum distance.

Frequently Asked Questions

Can I power the HC-SR04 from 3.3 V? Not reliably. It is a 5 V module, and at 3.3 V triggering and the Echo level become unreliable. Power it from 5 V and divide the Echo signal.

Why not just connect Echo directly? Because PA1 is not 5 V tolerant. A divider costs two resistors and protects the chip.

Can I use an Arduino Uno code instead? The measurement logic is identical, but the Blue Pill uses different pin names (PA0, PA1) and I2C pins, and has 3.3 V logic.

Does it work with the Arduino IDE? Yes, with the STM32duino board package installed. This guide uses PlatformIO for its dependency handling.

How far can it measure? The sensor is rated for 2 cm to 400 cm. Real-world range depends on the target, and the sketch waits up to 30 ms for an echo.

Summary

FeatureDetail
MicrocontrollerSTM32F103C8T6 (Blue Pill)
FrameworkArduino, through PlatformIO
SensorHC-SR04 ultrasonic
DisplaySSD1306 128×64 OLED over I2C
Trig pinPA0
Echo pinPA1, through a 1 kΩ and 2 kΩ divider
I2C pinsPB6 (SCL) and PB7 (SDA)
Range2 to 400 cm rated, with a 30 ms echo timeout
Update rateAbout 10 Hz

You built a complete distance meter and learned the habits that carry to larger projects: time a pulse carefully, treat a missing echo as a normal case, protect 3.3 V pins from 5 V signals, and test your readings against a ruler before you trust them. With the filter and temperature compensation above, the same build becomes a dependable sensing module for robots, level monitors and alarms.

Related: the HC-SR04 sensor page covers the sensor itself, the Blue Pill pinout guide shows every pin on this board, and the HC-SR04 with Arduino guide shows the same measurement on an Uno.

Topicsstm32blue-pillhc-sr04ultrasonic-sensoroledssd1306platformiost-link

Questions & Answers