#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// Define the pins for the ultrasonic sensor
const int trigPin = 14;
const int echoPin = 27;
// Create an instance of the OLED display
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
void setup() {
Serial.begin(115200);
// Initialize the ultrasonic sensor pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Initialize the OLED display
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.print("Ultrasonic Distance");
display.display();
delay(2000); // Display the message for 2 seconds
}
void loop() {
// Clear the previous readings
display.clearDisplay();
// Trigger the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pin
long duration = pulseIn(echoPin, HIGH);
// Calculate distance in cm
int distance = duration * 0.034 / 2; // Speed of sound is 0.034 cm/microsecond
// Display the distance on the OLED
display.setCursor(0, 0);
display.print("Distance: ");
display.print(distance);
display.print(" cm");
display.display();
// Wait before the next measurement
delay(500);
}