This circuit interfaces an Arduino Nano with an OLED display and an HC-SR04 Ultrasonic Distance Sensor. The distance measured by the sensor is displayed on the OLED screen. The Arduino Nano serves as the central microcontroller, handling the sensor data and updating the display.
Arduino Nano
OLED 1.3" Display
HC-SR04 Ultrasonic Distance Sensor
Comment
GND is connected to:
D9 is connected to:
D10 is connected to:
VIN is connected to:
A5 is connected to:
A4 is connected to:
GND is connected to:
VCC is connected to:
SCL is connected to:
SDA is connected to:
GND is connected to:
VCC is connected to:
TRIG is connected to:
ECHO is connected to:
/*
* This Arduino Sketch interfaces with an OLED display and an HC-SR04
* Ultrasonic Distance Sensor. The distance measured by the sensor is
* displayed on the OLED screen.
*/
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#define TRIG_PIN 10
#define ECHO_PIN 9
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Initialize the OLED display
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
display.display();
delay(2000); // Pause for 2 seconds
display.clearDisplay();
// Initialize the ultrasonic sensor pins
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop() {
// Clear the trigger pin
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
// Set the trigger pin HIGH for 10 microseconds
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Read the echo pin
long duration = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance
float distance = duration * 0.034 / 2;
// Display the distance on the OLED
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 10);
display.print("Distance: ");
display.print(distance);
display.println(" cm");
display.display();
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Wait for a short period before the next measurement
delay(500);
}
This code initializes the OLED display and the ultrasonic sensor, measures the distance using the sensor, and displays the measured distance on the OLED screen as well as prints it to the Serial Monitor. The loop continuously measures and updates the distance every 500 milliseconds.