ESP32 Bluetooth Parking Sensor (HC-SR04)
Measure the distance to an obstacle with an HC-SR04 and watch it on your phone; the buzzer beeps faster as it gets closer. No internet needed. This is the step-by-step guide to the Parking sensor Bluetooth template in the app, built with an ESP32. Go to Workshop › Devices › Add a device › Bluetooth, pick Parking sensor and upload the code with Get the code. The Set up as a Bluetooth panel button on this page opens the wizard with this template too.

Video
Circuit Diagram

Source Code
1// ┌───────────────────────────┐
2// │ BlueGrays · bluegrays.com │
3// │ Bluetooth · ESP32 │
4// │ BG-Park │
5// └───────────────────────────┘
6// Parking sensor
7// Arduino IDE board: ESP32 Dev Module
8// the BLE library comes with the ESP32 board package, nothing extra to install
9
10#include <BLEDevice.h>
11#include <BLEServer.h>
12#include <BLE2902.h>
13
14const char BLE_NAME[] = "BG-Park"; // the board advertises with this name, the app finds it in the list by it
15
16// Pins: change them here if you wired differently
17const int TRIG_PIN = 5, ECHO_PIN = 18; // ECHO outputs 5 V: connect it through a 1k/2k divider
18const int BUZZER_PIN = 19;
19const int ALARM_FROM_CM = 100; // Alarm: under 100 cm it beeps faster as the obstacle gets closer, continuous under 10 cm
20
21void btWrite(const char *text);
22void onValue(const char *key, const char *value);
23void sendAll();
24void onLinkLost();
25
26// ── The app sends "key=value" lines; on "?" the board sends all its values ──
27char line[65];
28uint8_t lineLen = 0;
29unsigned long lastRxMs = 0;
30
31bool is(const char *a, const char *b) { return strcmp(a, b) == 0; }
32bool isOn(const char *v) { return v[0] == '1'; }
33
34void sendText(const char *key, const char *value) {
35 char out[72];
36 snprintf(out, sizeof(out), "%s=%s\n", key, value);
37 btWrite(out);
38}
39
40void sendInt(const char *key, long value) {
41 char text[12];
42 snprintf(text, sizeof(text), "%ld", value);
43 sendText(key, text);
44}
45
46void sendFloat(const char *key, float value) {
47 char text[16];
48 dtostrf(value, 1, 1, text);
49 sendText(key, text);
50}
51
52void handleLine(char *text) {
53 char *eq = strchr(text, '=');
54 if (eq == nullptr) {
55 if (text[strlen(text) - 1] == '?') {
56 btWrite("@v=1.0\n"); // the "@v" line tells the app the code version
57 sendAll();
58 }
59 return;
60 }
61 *eq = '\0';
62 onValue(text, eq + 1);
63}
64
65void feed(char c) {
66 lastRxMs = millis();
67 if (c == '\n' || c == '\r') {
68 if (lineLen == 0) return;
69 line[lineLen] = '\0';
70 lineLen = 0;
71 handleLine(line);
72 } else if (lineLen < sizeof(line) - 1) {
73 line[lineLen++] = c;
74 }
75}
76
77// ── Bluetooth (Nordic UART) ──
78#define UART_SERVICE "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"
79#define UART_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
80#define UART_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
81
82BLECharacteristic *txChar = nullptr;
83volatile bool linked = false;
84volatile bool linkLost = false;
85// incoming bytes move from the Bluetooth task to loop() through a small ring buffer
86const int RX_SIZE = 256;
87volatile uint8_t rxBuf[RX_SIZE];
88volatile int rxHead = 0, rxTail = 0;
89
90class ServerEvents : public BLEServerCallbacks {
91 void onConnect(BLEServer *server) override { linked = true; }
92 void onDisconnect(BLEServer *server) override { linked = false; linkLost = true; }
93};
94
95class RxEvents : public BLECharacteristicCallbacks {
96 void onWrite(BLECharacteristic *c) override {
97 auto v = c->getValue();
98 for (size_t i = 0; i < v.length(); i++) {
99 int next = (rxHead + 1) % RX_SIZE;
100 if (next == rxTail) break;
101 rxBuf[rxHead] = (uint8_t)v[i];
102 rxHead = next;
103 }
104 }
105};
106
107// lines go out in 20-byte packets (works with every phone)
108void btWrite(const char *text) {
109 if (!linked || txChar == nullptr) return;
110 size_t n = strlen(text);
111 for (size_t i = 0; i < n; i += 20) {
112 size_t len = n - i < 20 ? n - i : 20;
113 txChar->setValue((uint8_t *)text + i, len);
114 txChar->notify();
115 delay(4);
116 }
117}
118
119void btBegin() {
120 BLEDevice::init(BLE_NAME);
121 BLEServer *server = BLEDevice::createServer();
122 server->setCallbacks(new ServerEvents());
123 BLEService *uart = server->createService(UART_SERVICE);
124 txChar = uart->createCharacteristic(UART_TX, BLECharacteristic::PROPERTY_NOTIFY);
125 txChar->addDescriptor(new BLE2902());
126 BLECharacteristic *rx = uart->createCharacteristic(UART_RX, BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_WRITE_NR);
127 rx->setCallbacks(new RxEvents());
128 uart->start();
129 BLEAdvertisementData adv;
130 adv.setFlags(0x06);
131 adv.setCompleteServices(BLEUUID(UART_SERVICE));
132 BLEAdvertisementData scan;
133 scan.setName(BLE_NAME);
134 BLEAdvertising *advertising = BLEDevice::getAdvertising();
135 advertising->setAdvertisementData(adv);
136 advertising->setScanResponseData(scan);
137 BLEDevice::startAdvertising();
138}
139
140void btPoll() {
141 while (rxTail != rxHead) {
142 char c = (char)rxBuf[rxTail];
143 rxTail = (rxTail + 1) % RX_SIZE;
144 feed(c);
145 }
146 if (linkLost) {
147 linkLost = false;
148 onLinkLost();
149 delay(100);
150 BLEDevice::startAdvertising();
151 }
152}
153
154// ── ESP32 ──
155bool alarmOn = true;
156bool buzzing = false;
157int distanceCm = -1, sentCm = -100;
158unsigned long lastMeasureMs = 0, lastSentMs = 0, lastBeepMs = 0;
159
160int measureCm() {
161 digitalWrite(TRIG_PIN, LOW);
162 delayMicroseconds(2);
163 digitalWrite(TRIG_PIN, HIGH);
164 delayMicroseconds(10);
165 digitalWrite(TRIG_PIN, LOW);
166 unsigned long us = pulseIn(ECHO_PIN, HIGH, 25000UL);
167 if (us == 0) return 400; // no echo: nothing within 4 m
168 return min(400UL, us / 58);
169}
170
171void buzz(bool on) {
172 if (on == buzzing) return;
173 buzzing = on;
174 if (on) tone(BUZZER_PIN, 2000);
175 else noTone(BUZZER_PIN);
176}
177
178void onValue(const char *key, const char *value) {
179 if (is(key, "alarm")) alarmOn = isOn(value);
180}
181
182void sendAll() {
183 if (distanceCm >= 0) sendInt("mesafe", distanceCm);
184 sendInt("alarm", alarmOn);
185}
186
187void onLinkLost() {
188}
189
190void setup() {
191 Serial.begin(115200);
192 pinMode(TRIG_PIN, OUTPUT);
193 pinMode(ECHO_PIN, INPUT);
194 pinMode(BUZZER_PIN, OUTPUT);
195 btBegin();
196 Serial.print(F("BlueGrays Bluetooth: "));
197 Serial.println(BLE_NAME);
198}
199
200void loop() {
201 btPoll();
202 if (millis() - lastMeasureMs >= 100) {
203 lastMeasureMs = millis();
204 distanceCm = measureCm();
205 if ((distanceCm != sentCm && millis() - lastSentMs >= 250) || millis() - lastSentMs >= 2000) {
206 sendInt("mesafe", distanceCm);
207 sentCm = distanceCm;
208 lastSentMs = millis();
209 }
210 }
211 if (!alarmOn || distanceCm < 0 || distanceCm > ALARM_FROM_CM) {
212 buzz(false);
213 } else if (distanceCm <= 10) {
214 buzz(true);
215 } else if (millis() - lastBeepMs >= (unsigned long)map(distanceCm, 10, ALARM_FROM_CM, 60, 600)) {
216 lastBeepMs = millis();
217 buzz(!buzzing);
218 }
219}
220FAQ
Does it work with an iPhone?
Yes. The ESP32's built-in Bluetooth Low Energy (BLE) talks to both iPhone and Android. An iPhone cannot connect to classic Bluetooth modules like the HC-05 and HC-06, and this project does not need them. Do not try to pair the board in your phone's Bluetooth settings; BLE boards may not show up there, which is normal. The BlueGrays app makes the connection.
Why do I need the voltage divider? Can I wire ECHO straight to the board?
The HC-SR04 runs on 5 V and its ECHO pin outputs a 5 V signal. ESP32 pins work at 3.3 V and are not 5 V tolerant. The 1 kΩ and 2 kΩ resistors divide that signal so about 3.3 V reaches GPIO 18. Wired directly, the circuit may seem to work, but you can damage the pin; do not skip the divider. TRIG needs no divider, because there the board is the one sending the signal. If you have no 2 kΩ resistor, put two 1 kΩ resistors one after the other (in series).
Can I fit this to my real car?
No, this is a learning and model project. It does its job on a desk, on a toy car or when you try approaching a garage wall. The HC-SR04 and a breadboard are not made for rain, mud and vibration; readings go wrong on soft or slanted surfaces and the Bluetooth link can drop. It is not a parking system for driving safety in a real vehicle, so do not rely on it there.
Does it beep when no phone is connected?
Yes. Measuring and beeping happen on the board; the phone is only there to show the distance and to turn the sound off and on. The board starts with Alert sound on every time it powers up, so on a power bank it beeps from 100 cm without any phone. If the link drops, measuring and beeping carry on. If you muted it with the switch in the panel, it stays silent until you turn the switch back on or the board restarts. Internet and Wi-Fi are never needed.
