This circuit integrates an Arduino Nano microcontroller with an OLED 1.3" display and an HC-SR04 Ultrasonic Distance Sensor. The purpose of the circuit is to measure distances using the ultrasonic sensor and display the measured values on the OLED screen. The Arduino Nano serves as the central processing unit, controlling the sensor and managing the display output.
/*
* 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 is designed to run on the Arduino Nano and performs the following functions: