Skip to content

Instantly share code, notes, and snippets.

@soap
Created April 29, 2025 13:58
Show Gist options
  • Save soap/a8f14048089fbc8552725106b8b8afe2 to your computer and use it in GitHub Desktop.
Save soap/a8f14048089fbc8552725106b8b8afe2 to your computer and use it in GitHub Desktop.
Measure distance with HC-SR04 and display on OLED using ESP32
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define ledPin 2
#define trigPin 5
#define echoPin 18
#define buzzerPin 19
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
Adafruit_SSD1306 oled(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
const float soundSpeed = 0.034; //
void setup() {
Serial.begin(115200); // ใช้ความเร็วสูงขึ้น
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
if( !oled.begin(SSD1306_SWITCHCAPVCC, 0x3C) ) {
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
oled.clearDisplay();
oled.setTextSize(2);
oled.setTextColor(SSD1306_WHITE);
oled.setCursor(0, 10);
oled.println("Ready");
oled.display();
delay(1000);
}
void loop() {
float duration_us, distance_cm;
// ส่งสัญญาณ Trigger
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration_us = pulseIn(echoPin, HIGH);
// คำนวณระยะทาง
distance_cm = duration_us * soundSpeed /2;
if (distance_cm < 10) {
//turn buzzer on
digitalWrite(buzzerPin, HIGH);
digitalWrite(ledPin, HIGH);
}else{
//turn buzzer off
digitalWrite(buzzerPin, LOW);
digitalWrite(ledPin, LOW);
}
Serial.print("Distance:");
Serial.print(distance_cm);
//Serial.println(" cm");
Serial.println(",");
Serial.println(200);
// แสดงบนจอ OLED
oled.clearDisplay();
oled.setTextSize(2);
oled.setTextColor(SSD1306_WHITE);
oled.setCursor(5,10);
oled.print(distance_cm);
oled.println(" cm");
oled.display();
delay(100);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment