Skip to content

Instantly share code, notes, and snippets.

@EDISON-SCIENCE-CORNER
Created August 2, 2025 13:13
Show Gist options
  • Select an option

  • Save EDISON-SCIENCE-CORNER/1a78bf6815adce467e6a29e4b3271539 to your computer and use it in GitHub Desktop.

Select an option

Save EDISON-SCIENCE-CORNER/1a78bf6815adce467e6a29e4b3271539 to your computer and use it in GitHub Desktop.
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// OLED settings
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
// Ultrasonic sensor pins
#define TRIG_PIN 9
#define ECHO_PIN 8
void setup() {
// Start serial and OLED
Serial.begin(9600);
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // I2C address 0x3C
Serial.println(F("SSD1306 allocation failed"));
while(1);
}
display.clearDisplay();
display.setTextColor(SSD1306_WHITE);
// Setup ultrasonic pins
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop() {
long duration;
float distance;
// Trigger the sensor
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Read echo time
duration = pulseIn(ECHO_PIN, HIGH);
distance = duration * 0.034 / 2; // Convert to cm
// Display on OLED
display.clearDisplay();
display.setTextSize(2);
display.setCursor(0, 10);
display.print("Distance:");
display.setTextSize(3);
display.setCursor(0, 35);
display.print(distance, 1);
display.print(" cm");
display.display();
delay(300);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment