ZAIRobotics
Published © MIT

Arduino Mega Ultrasonic Distance Monitor with OLED

This project uses an ultrasonic sensor to detect distance and display it on an OLED Display with an Arduino Mega microcontroller.

BeginnerFull instructions provided1 hour228
Arduino Mega Ultrasonic Distance Monitor with OLED

Things used in this project

Hardware components

Arduino Mega 2560
Arduino Mega 2560
×1
0.96" OLED 64x128 Display Module
ElectroPeak 0.96" OLED 64x128 Display Module
×1
Ultrasonic Sensor - HC-SR04 (Generic)
Ultrasonic Sensor - HC-SR04 (Generic)
×1

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Schematics

Schematics

This is the schematics for the project.

Code

arduino_ultrasonic_distance_monitor.ino

Arduino
This is the code.
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

const int trigPin = 22;
const int echoPin = 23;

void setup() {
  // put your setup code here, to run once:
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)){
    for(;;);
  }
  display.clearDisplay();
}

void loop() {
  // 1. Trigger the sensor
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW); // <--- ADD THIS: Stops the trigger pulse

  // 2. Measure the bounce
  long duration = pulseIn(echoPin, HIGH);
  int distance = (duration * 0.034) / 2; // (Using 0.034 for better accuracy)
  
  // 3. Update the OLED
  display.clearDisplay();
  display.setTextSize(2); // Size 3 might be too big for "Dist: 100cm"
  display.setTextColor(SSD1306_WHITE); // Explicitly set color just in case
  display.setCursor(0, 0);
  
  display.print("Dist: ");
  display.print(distance);
  display.print("cm");

  display.display(); // <--- ADD THIS: Actually pushes the data to the glass!
  
  delay(100); // Give the sensor a tiny rest
}

Credits

ZAIRobotics
2 projects • 1 follower
Learn about basic of electronics and ai robotics

Comments