#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
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); //Declaring the display name (display)
/**************************************************************
* PARKING SENSOR WITH HC-SR04 *
* *
* This code receives data from the HC-SR04 proximity *
* sensor, analyses them, sends them to the serial monitor *
* and produces intermittent sounds to warn of an obstacle. *
**************************************************************/
// Definition of trigger, echo, beep pins and other constants
#define trigger 2
#define echo 3
#define beep 11
#define beep_start 100
#define min_distance 5
// Definition of sound speed (centimetres / microsecond)
#define c 0.0343
// Definition of the variables
long tempo;
float space;
void setup() {
// Definition of input and output
pinMode(trigger, OUTPUT);
pinMode(echo, INPUT);
pinMode(beep, OUTPUT);
// Serial communication initialisation (optional)
Serial.begin(9600);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); //Start the OLED display
display.setTextColor(WHITE);
}
void loop() {
// Before measurement, the trigger is set to low level
digitalWrite(trigger, LOW);
delayMicroseconds(5);
// Send one pulse (trigger goes high level for 10 microseconds)
digitalWrite(trigger, HIGH);
delayMicroseconds(10);
digitalWrite(trigger, LOW);
// Reading echo, via pulseIn, which returns the duration of the impuse (in microseconds)
// The acquired data is then divided by 2 (forward and backward)
tempo = pulseIn(echo, HIGH) / 2;
// Computation of distance in centimetres
space = tempo * c;
// space is displayed in the serial monitor ([Ctrl] + [Shift] + M)
// approximated to the first decimal place
Serial.println("Distanse = " + String(space, 1) + " cm");
display.clearDisplay(); // Clear the screen
display.setTextSize(2);
display.setCursor(20,0); // Set X Y cordinates
display.println("Distance"); // Print text on 0 20 cordinates
display.setTextSize(2);
display.setCursor(20,30); // Set X Y cordinates
display.print(String(space, 1)); // Print text on 20 20
display.println(" cm"); // Add cm at the end of distance
display.display(); // show on screen
// If the distance is less than one metre
if (space < beep_start) {
// Emits sounds at intervals proportional to distance (1 m = 400 ms)
tone(beep, 1000);
delay(40);
// Below min_distance cm it emits a continuous sound
if (space > min_distance) {
noTone(beep);
delay(space * 4);
}
}
else
{
noTone(beep);
}
// Waits 50 milliseconds before another measurement
delay(50);
}Loading
ssd1306
ssd1306