Community project

Ultrasonic Distance Meter

Photo of Ultrasonic Distance Meter
Generated with AI

Mürka Eestis

Published November 30, 2026

This ultrasonic distance meter uses an HC-SR04 sensor connected to an ESP32 to measure distances and display them on an OLED screen. The project includes four buttons for user interaction and stores configuration settings in the device's non-volatile memory. The guide provides a complete wiring diagram, parts list, and step-by-step assembly instructions to get the meter up and running.

The firmware includes WiFi connectivity for remote monitoring and data logging capabilities, along with a recovery mode for network troubleshooting. Builders will learn how to interface the ultrasonic sensor with the ESP32, manage button inputs with debouncing, drive an OLED display, and implement WiFi features for IoT applications.

Wiring diagram

Wiring diagram for Ultrasonic Distance Meter
Loading diagram…

Gather all the parts

QtyComponent
1

HC-SR04 ultrasonic sensor

Classic 5 V HC-SR04 with TTL trigger input and 5 V echo output. Echo is divided by 1 kohm and 2 kohm resistors before reaching the 3.3 V input.

1

Resistor

1 kohm

Through-hole resistor (current-limiting in series with an LED)

1

Resistor

2 kohm

Through-hole resistor (current-limiting in series with an LED)

1

OKYN-G5335 OLED with four buttons

128x64 SSD1306 I2C OLED, powered at 3.3 V, with independent K1-K4 button signals.

Assemble it in 4 steps

1. Prepare the breadboard

Keep power unplugged. Put the XIAO across the centre gap with its two pin rows on opposite sides. Each a-e group in one numbered row is connected; each f-j group is separate. Use the left plus rail for 3.3 V, right plus rail for 5 V, and minus rails for ground. Join both minus rails to XIAO GND. Check for breaks in the rails.

  • Never connect the 3.3 V and 5 V plus rails together.

2. Connect the screen and buttons

Follow the printed pin labels, not pin position. VCC goes to XIAO 3V3 and GND to ground. SDA goes to D4 (GPIO6, data); SCL to D5 (GPIO7, clock). K1 goes to D3 (GPIO5, set closed distance), K2 to D10 (GPIO10, reserved), K3 to D7 (GPIO20, decrease tolerance), and K4 to D6 (GPIO21, increase tolerance). Buttons are read with internal pull-ups; verify with power off that each button closes its K signal to GND when pressed before powering the build.

3. Protect the sensor return signal

Connect HC-SR04 VCC to XIAO 5V and GND to ground. TRIG goes to D1 (GPIO3, trigger). ECHO goes through the 1 kohm resistor to a free row. Connect that row to D2 (GPIO4, echo input), and connect the 2 kohm resistor between that row and ground. This lowers the sensor's 5 V return pulse to about 3.33 V. Keep resistor leads in separate rows so they are not shorted.

  • Never connect ECHO directly to the XIAO; 5 V can damage its input.

4. Check power and operation

Keep the existing USB power wiring. Battery operation is not documented in this project power design. Mount the sensor firmly facing the closed door, protected from moisture and condensation. Connect a laptop to Door-Collector with password DoorSetup2026 and open http://192.168.4.1. Set the closed-door distance (default 13 cm) and tolerance (default +/-3 cm), then save. Optionally configure a 2.4 GHz hotspot and use the IP shown on the OLED. K1 sets the closed distance to the current valid reading; close the door first. K2 is reserved. K3 decreases tolerance and K4 increases it. Settings survive restart. Three consecutive readings confirm CLOSED within the band or OPEN outside it; missing echoes give UNKNOWN. Test fully and partly open positions. No model, CSV collection, or TagoIO notifications are installed.

  • Do not connect a 9 V battery directly to any XIAO or sensor pin.

Review all connections

1. Connections between "sonar" and "ESP32"

FunctionsonarESP32
powerVCCVIN
groundGNDGND
digitalTRIGGPIO 3
digitalECHO → Resistor P1EXT

2. Connections between "echo_top" and "ESP32"

Functionecho_topESP32
digitalP2GPIO 4
digitalP2 → Resistor P1EXT

3. Connections between "echo_bottom" and "ESP32"

Functionecho_bottomESP32
groundP2GND

4. Connections between "screen" and "ESP32"

FunctionscreenESP32
powerVCC3V3
groundGNDGND
i2cSDAGPIO 6
i2cSCLGPIO 7
digitalK1GPIO 5
digitalK2GPIO 10
digitalK3 → XIAO D7 pad (GPIO20), used as digital input with UART disabledEXT
digitalK4 → XIAO D6 pad (GPIO21), used as digital input with UART disabledEXT

Deploy the firmware

#include <Arduino.h>
#include <Wire.h>
#include <WiFi.h>
#include <WebServer.h>
#include <Preferences.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <time.h>
#include "tago_ca.h"
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
Adafruit_SSD1306 oled(128,64,&Wire,-1);
WebServer server(80);
Preferences prefs;
const int keys[]={5,10,20,21};
bool raw[4]={},stable[4]={},ready=false,dirty=true;
uint32_t changed[4]={},lastPing=0,reconnectAt=0;
int target=13,tolerance=3,distanceCm=-1;
bool recoveryMode=false;
bool wifiStartPending=false;
uint32_t wifiStoppedAt=0;
void scheduleWiFi(){
 // Disable the station interface to cancel any in-flight connection.
 // disconnect alone can leave the driver connecting when begin runs again.
 WiFi.mode(WIFI_AP);
 wifiStoppedAt=millis();
 wifiStartPending=true;
}
void serviceWiFi(uint32_t now){
 if(recoveryMode)return;
 if(wifiStartPending){
  if(now-wifiStoppedAt<250)return;
  wifiStartPending=false;
  String ssid=prefs.getString("ssid","");
  String pass=prefs.getString("pass","");
  reconnectAt=now;
  if(ssid.length()){
   WiFi.mode(WIFI_AP_STA);
   if(pass.length())WiFi.begin(ssid.c_str(),pass.c_str());
   else WiFi.begin(ssid.c_str());
  }
 }else if(WiFi.status()!=WL_CONNECTED && now-reconnectAt>=30000 && prefs.getString("ssid","").length()){
  scheduleWiFi();
 }
}
uint32_t recoveryHeldAt=0;
void recoverWiFi(){
 recoveryMode=true;
 wifiStartPending=false;
 WiFi.disconnect(false,false);
 WiFi.mode(WIFI_AP);
 WiFi.softAP("Door-Collector","DoorSetup2026");
 dirty=true;
 Serial.println("Wi-Fi recovery: join Door-Collector, open http://192.168.4.1");
}
// 0 unknown, 1 closed, 2 open. Require three consecutive matching readings.
int state=0,candidate=0,streak=0;
// Only a continuously confirmed OPEN state can complete the alert timer.
uint32_t openSince=0;
bool timingOpen=false;
int eventState=0,sentEvent=-1;
void updateDoorEvent(uint32_t now){
 if(state!=2){timingOpen=false;eventState=state;return;}
 if(!timingOpen){timingOpen=true;openSince=now;}
 eventState=(now-openSince>15000u)?2:3; // 3 = PENDING
}
const char* stateName(){return state==1?"CLOSED":state==2?"OPEN":"UNKNOWN";}
// The network task owns TLS; queues keep preferences and sensor state on the main loop.
struct Upload { char token[65]; char region[8]; int state,event,cm,target,tol; bool transition; };
struct UploadResult { int code; };
QueueHandle_t uploads,results;
String uploadStatus="Waiting for Wi-Fi and saved token";
bool uploading=false; uint32_t lastAttempt=0,lastSuccess=0; int sentState=-1,sentTarget=-1,sentTol=-1;
Upload activeUpload;
void uploadWorker(void*){
 Upload u;
 for(;;){
  if(xQueueReceive(uploads,&u,portMAX_DELAY)!=pdTRUE)continue;
  int code=-100;
  if(WiFi.status()==WL_CONNECTED && time(nullptr)>1700000000){
   WiFiClientSecure tls; tls.setCACert(tagoCA); tls.setHandshakeTimeout(8);
   HTTPClient http; http.setConnectTimeout(5000);http.setTimeout(5000);
   String url="https://api."+String(u.region)+".tago.io/data";
   if(http.begin(tls,url)){
    http.addHeader("Content-Type","application/json");http.addHeader("Device-Token",u.token);
    const char* name=u.state==1?"CLOSED":u.state==2?"OPEN":"UNKNOWN";
    String body="[{\"variable\":\"door_state\",\"value\":\""+String(name)+"\"},{\"variable\":\"closed_distance_cm\",\"value\":"+String(u.target)+",\"unit\":\"cm\"},{\"variable\":\"tolerance_cm\",\"value\":"+String(u.tol)+",\"unit\":\"cm\"},{\"variable\":\"echo_valid\",\"value\":"+String(u.cm>=0?"true":"false")+"}";
    if(u.cm>=0)body+=",{\"variable\":\"distance_cm\",\"value\":"+String(u.cm)+",\"unit\":\"cm\"}";
    const char* eventName=u.event==1?"CLOSED":u.event==2?"OPEN":u.event==3?"PENDING":"UNKNOWN";
    if(u.transition)body+=",{\"variable\":\"door_event\",\"value\":\""+String(eventName)+"\"}";
    body+="]";code=http.POST(body);http.end();
   }else code=-101;
  }
  UploadResult result{code};xQueueSend(results,&result,portMAX_DELAY);
 }
}
void serviceUploads(uint32_t now){
 UploadResult r;
 if(xQueueReceive(results,&r,0)==pdTRUE){
  uploading=false;
  if(r.code>=200&&r.code<300){
   uploadStatus="Upload accepted (HTTP "+String(r.code)+")";lastSuccess=now;
   sentState=activeUpload.state;sentEvent=activeUpload.event;sentTarget=activeUpload.target;sentTol=activeUpload.tol;
  }else if(r.code==-100)uploadStatus="Waiting for internet time sync / Wi-Fi";
  else if(r.code==401||r.code==403)uploadStatus="Token rejected: check token and account region";
  else if(r.code>0)uploadStatus="Upload failed (HTTP "+String(r.code)+")";
  else uploadStatus="HTTPS connection failed ("+String(r.code)+"); check internet / time / certificate";
 }
 if(uploading)return;
 String token=prefs.getString("tago","");
 if(!token.length()){uploadStatus="No saved device token";return;}
 if(WiFi.status()!=WL_CONNECTED){uploadStatus="Wi-Fi disconnected; local detection continues";return;}
 bool changed=state!=sentState||eventState!=sentEvent||target!=sentTarget||tolerance!=sentTol;
 bool failed=uploadStatus.startsWith("Upload failed")||uploadStatus.startsWith("HTTPS")||uploadStatus.startsWith("Token rejected")||uploadStatus.startsWith("Waiting for internet");
 if(now<1500 || (lastAttempt && now-lastAttempt<(failed?30000u:2000u)))return;
 if(!changed && now-lastSuccess<60000)return;
 activeUpload={};token.toCharArray(activeUpload.token,sizeof(activeUpload.token));
 prefs.getString("region","us-e1").toCharArray(activeUpload.region,sizeof(activeUpload.region));
 activeUpload.state=state;activeUpload.event=eventState;activeUpload.cm=distanceCm;activeUpload.target=target;activeUpload.tol=tolerance;
 activeUpload.transition=eventState!=sentEvent;
 if(xQueueSend(uploads,&activeUpload,0)==pdTRUE){uploading=true;lastAttempt=now;uploadStatus="Uploading...";}
}
void resetDecision(){timingOpen=false;eventState=0;state=0;candidate=0;streak=0;dirty=true;}
void saveSettings(){prefs.putInt("target",target);prefs.putInt("tol",tolerance);resetDecision();}
bool number(const String& s,int& out){
 if(!s.length() || s.length()>3)return false;
 for(unsigned i=0;i<s.length();i++)if(s[i]<'0'||s[i]>'9')return false;
 out=s.toInt();return true;
}
void redirect(){server.sendHeader("Location","/");server.send(303);}
void tokenConfirmation(const char* message){
 server.sendHeader("Cache-Control","no-store");
 server.send(200,"application/json",String("{\"message\":\"")+message+".\"}");
}
void webSetup(){
 prefs.begin("doorwifi",false);
 target=prefs.getInt("target",13);tolerance=prefs.getInt("tol",3);
 if(target<2||target>400)target=13;
 if(tolerance<1||tolerance>100)tolerance=3;
 WiFi.setAutoReconnect(false);
 WiFi.mode(WIFI_AP_STA);WiFi.softAP("Door-Collector","DoorSetup2026");
 String ssid=prefs.getString("ssid","");
 if(ssid.length())scheduleWiFi();
 server.on("/",HTTP_GET,[]{
 String p="<!doctype html><html><head><meta name='viewport' content='width=device-width'><title>Fridge door</title></head><body><h1>Fridge door monitor</h1>";
 p+="<h2 id='state'>"+String(stateName())+"</h2><p>Distance: <span id='cm'>"+(distanceCm<0?String("no echo"):String(distanceCm))+"</span> cm</p>";
 p+="<form method='post' action='/settings'>Closed-door distance (cm): <input type='number' name='target' min='2' max='400' required value='"+String(target)+"'><br>Tolerance +/- (cm): <input type='number' name='tol' min='1' max='100' required value='"+String(tolerance)+"'><button>Save settings</button></form>";
 p+="<p>Valid readings within the band (including its edges) mean CLOSED; outside means OPEN. Three matching readings confirm a change (about 0.3 seconds). Missing echoes mean UNKNOWN, not CLOSED.</p>";
 p+="<p>K1: set closed distance to the current valid reading (close the door first). K2: hold for 3 seconds to restore setup Wi-Fi without erasing saved settings. K3: decrease tolerance. K4: increase tolerance. Saved settings survive power-off.</p>";
 p+="<h2>Wi-Fi</h2><p>Recovery: hold K2 for 3 seconds, join Door-Collector (password DoorSetup2026), then open http://192.168.4.1. Keep connected even if your phone says no internet. Blank network password means an open network; captive-portal networks requiring a browser login are not supported.</p><p>Hotspot IP: "+(WiFi.status()==WL_CONNECTED?WiFi.localIP().toString():String("not connected"))+"</p><form method='post' action='/wifi'>Network: <input name='ssid' maxlength='32' required><br>Password: <input type='password' name='pass' maxlength='63'><button>Save and connect</button></form>";
 p+="<h2>TagoIO</h2><p>Device token: "+String(prefs.getString("tago","").length()?"saved":"not configured")+".</p><p>Upload status: <span id='upload'>"+uploadStatus+"</span></p>";
 p+="<form method='post' action='/tago-region'>TagoIO account region: <select name='region'><option value='us-e1' "+String(prefs.getString("region","us-e1")=="us-e1"?"selected":"")+">United States</option><option value='eu-w1' "+String(prefs.getString("region","us-e1")=="eu-w1"?"selected":"")+">Europe</option></select><button>Save region</button></form>";
 p+="<form id='tokenForm' method='post' action='/tago'>Device token: <input type='password' name='token' maxlength='64' autocomplete='new-password' required placeholder='Paste your TagoIO device token'><button id='saveToken'>Save token</button></form><p id='tokenResult' role='status'></p><form method='post' action='/tago-clear'><button>Remove saved token</button></form>";
 p+="<p>The token is never displayed or returned by this page. Enter it only on your trusted local network; this local settings page uses HTTP, not encrypted HTTPS.</p>";
 p+="<p>Encrypted TagoIO uploads on state/settings changes and every 60 seconds. Configure push notifications separately in TagoIO using door_event = OPEN. door_state updates immediately; door_event is PENDING until OPEN lasts more than 15 continuous seconds, then OPEN once per opening. CLOSED or UNKNOWN cancels the timer. Internet outages can delay or prevent notifications. No offline history is stored. Use only on a trusted network. Keep electronics dry and protected from fridge condensation.</p><script>let savingToken=false;document.getElementById('tokenForm').addEventListener('submit',async e=>{e.preventDefault();savingToken=true;let b=document.getElementById('saveToken'),r=document.getElementById('tokenResult');b.disabled=true;r.textContent='Saving...';const controller=new AbortController();const timer=setTimeout(()=>controller.abort(),10000);try{const response=await fetch('/tago',{method:'POST',body:new URLSearchParams(new FormData(e.target)),headers:{'Accept':'application/json','Content-Type':'application/x-www-form-urlencoded'},signal:controller.signal});const text=await response.text();let data;try{data=JSON.parse(text);}catch(parseError){throw new Error('Unexpected response (HTTP '+response.status+'). Reload the settings page.');}r.textContent=data.message||('HTTP '+response.status);if(response.ok)e.target.reset();}catch(err){r.textContent=err.name==='AbortError'?'The save request timed out. Reload the main page to check whether the token is saved.':'Save confirmation failed: '+err.message;}finally{clearTimeout(timer);b.disabled=false;savingToken=false;}});setInterval(async()=>{if(savingToken)return;try{let d=await(await fetch('/status')).json();document.getElementById('state').textContent=d.state;document.getElementById('cm').textContent=d.cm<0?'no echo':d.cm;document.getElementById('upload').textContent=d.upload;}catch(e){}},500);</script></body></html>";
 server.send(200,"text/html",p);
 });
 server.on("/status",HTTP_GET,[]{server.sendHeader("Cache-Control","no-store");server.send(200,"application/json","{\"state\":\""+String(stateName())+"\",\"cm\":"+String(distanceCm)+",\"target\":"+String(target)+",\"tolerance\":"+String(tolerance)+",\"upload\":\""+uploadStatus+"\"}");});
 server.on("/settings",HTTP_POST,[]{
 int a,b;
 if(!number(server.arg("target"),a)||!number(server.arg("tol"),b)||a<2||a>400||b<1||b>100){server.send(400,"text/plain","Use a distance of 2-400 cm and tolerance of 1-100 cm.");return;}
 target=a;tolerance=b;saveSettings();redirect();
 });
 server.on("/tago-region",HTTP_POST,[]{
 String r=server.arg("region");if(r!="us-e1"&&r!="eu-w1"){server.send(400,"text/plain","Invalid region");return;}
 prefs.putString("region",r);sentState=-1;lastAttempt=0;uploadStatus="Ready to upload";redirect();
 });
 server.on("/tago",HTTP_POST,[]{
 String token=server.arg("token");token.trim();
 bool valid=token.length()==36;
 for(unsigned i=0;i<token.length();i++){
 char c=token[i];
 if(i==8||i==13||i==18||i==23){if(c!='-')valid=false;}
 else if(!((c>='0'&&c<='9')||(c>='a'&&c<='f')||(c>='A'&&c<='F')))valid=false;
 }
 if(!valid){server.send(400,"application/json","{\"message\":\"Enter the 36-character device token, including hyphens.\"}");return;}
 if(prefs.putString("tago",token)==0){server.send(500,"application/json","{\"message\":\"Could not save token. Try again.\"}");return;}
 sentState=-1;lastAttempt=0;uploadStatus="Ready to upload";tokenConfirmation("Token saved");
 });
 server.on("/tago",HTTP_GET,[]{redirect();});
 server.on("/tago-clear",HTTP_GET,[]{redirect();});
 server.on("/tago-clear",HTTP_POST,[]{prefs.remove("tago");tokenConfirmation("Token removed");});
 server.on("/wifi",HTTP_POST,[]{
 String s=server.arg("ssid"),p=server.arg("pass");
 if(s.length()<1||s.length()>32||p.length()>63){server.send(400,"text/plain","Invalid network settings");return;}
 prefs.putString("ssid",s);prefs.putString("pass",p);
 server.send(200,"text/html","Saved. Wait 15 seconds. Joining a router may briefly disconnect setup Wi-Fi. Rejoin Door-Collector and open http://192.168.4.1, or hold K2 for 3 seconds to recover. <a href='/'>Return</a>");
 recoveryMode=false;
 scheduleWiFi();
 });const char* headers[]={"Accept"};server.collectHeaders(headers,1);server.begin();
}
void setup(){
 Serial.begin(115200);
 pinMode(3,OUTPUT);digitalWrite(3,LOW);pinMode(4,INPUT);
 for(int p:keys)pinMode(p,INPUT_PULLUP);
 Wire.begin(6,7);
 for(uint8_t a:{uint8_t(0x3c),uint8_t(0x3d)}){Wire.beginTransmission(a);if(Wire.endTransmission()==0){ready=oled.begin(SSD1306_SWITCHCAPVCC,a,false,false);break;}}
 if(ready){oled.clearDisplay();oled.setTextColor(SSD1306_WHITE);oled.setTextWrap(false);}
 webSetup();
 configTime(0,0,"pool.ntp.org","time.google.com");
 uploads=xQueueCreate(1,sizeof(Upload));results=xQueueCreate(1,sizeof(UploadResult));
 if(!uploads||!results||xTaskCreate(uploadWorker,"tago",12288,nullptr,1,nullptr)!=pdPASS){uploadStatus="Upload task unavailable";}
}
void loop(){
 server.handleClient();uint32_t now=millis();
 static bool connected=false;bool net=WiFi.status()==WL_CONNECTED;
 if(net!=connected){connected=net;dirty=true;}
 serviceWiFi(now);
 for(int i=0;i<4;i++){
 bool r=digitalRead(keys[i])==LOW;
 if(r!=raw[i]){raw[i]=r;changed[i]=now;}
 if(r!=stable[i]&&now-changed[i]>=30){stable[i]=r;if(r){
 if(i==0&&distanceCm>=2){target=distanceCm;saveSettings();}
 if(i==2&&tolerance>1){tolerance--;saveSettings();}
 if(i==3&&tolerance<100){tolerance++;saveSettings();}
 }}
 }
 if(stable[1]){
 if(!recoveryHeldAt)recoveryHeldAt=now;
 if(!recoveryMode&&now-recoveryHeldAt>=3000)recoverWiFi();
 }else recoveryHeldAt=0;
 if(now-lastPing>=100){
 lastPing=now;digitalWrite(3,LOW);delayMicroseconds(3);digitalWrite(3,HIGH);delayMicroseconds(10);digitalWrite(3,LOW);
 unsigned long us=pulseIn(4,HIGH,25000);int cm=us?int((us+29)/58):-1;
 if(cm<2||cm>400)cm=-1;
 if(cm!=distanceCm){distanceCm=cm;dirty=true;}
 int next=cm<0?0:(abs(cm-target)<=tolerance?1:2);
 if(next!=candidate){candidate=next;streak=1;}else if(streak<3)streak++;
 if(streak>=3&&state!=candidate){state=candidate;dirty=true;}
 }
 if(ready&&dirty){
 dirty=false;oled.clearDisplay();oled.setTextSize(1);oled.setCursor(0,0);oled.print("Door: ");oled.print(stateName());
 oled.setCursor(0,12);oled.print("Distance: ");if(distanceCm<0)oled.print("--");else oled.print(distanceCm);oled.print(" cm");
 oled.setCursor(0,24);oled.print("Closed:");oled.print(target);oled.print(" +/-");oled.print(tolerance);oled.print("cm");
 oled.setCursor(0,36);oled.print(net?WiFi.localIP().toString():"AP: 192.168.4.1");
 oled.setCursor(0,46);oled.print("K1 set closed dist");oled.setCursor(0,56);oled.print("K3 tol- K4 tol+");oled.display();
 }updateDoorEvent(now);if(uploads&&results)serviceUploads(now);delay(1);
}

Remix this project

Make it yours in one click

Open a full copy of this project in your own Schematik workspace, diagram, code, parts, and assembly steps included. Swap the sensor, add features, or redesign the whole thing with AI. The author's original stays untouched.

Open in Schematik