#include "U8glib.h" // Library for controlling of the OLED
U8GLIB_SSD1306_128X64 u8g;
int trig = 7; // Pin declaring for trig pin
int echo = 6; // Pin declaring for echo pin
void setup() {
Serial.begin(9600); // Serial monitor startup
u8g.setFont(u8g_font_7x13); // Setting the font
u8g.setColorIndex(1); // Setting the colour to white
pinMode(trig, OUTPUT); // Trig pin to output
pinMode(echo, INPUT); // Echo pin to input
}
void loop() {
digitalWrite(trig, HIGH); // Trig high for 10 microseconds
delayMicroseconds(10);
digitalWrite(trig, LOW); // Trig low
int duration = pulseIn(echo, HIGH);
int distanceCM = duration/58;
int distanceInches = duration/148;
Serial.print("Distance in CM: ");
Serial.print(distanceCM);
Serial.print("\t");
Serial.print("Distance in inches: ");
Serial.print(distanceInches);
Serial.print("\n");
Serial.print("\n");
delay(50);
u8g.firstPage();
if (distanceCM < 80) { // If distance in cm is under 80, display "too close"
do {
u8g.drawStr(35,20,"Too Close");
u8g.drawBox(0,40,distanceCM/3,30); // Draw box representing the distance
}
while (u8g.nextPage());
}
else if (distanceCM >=80 && distanceCM < 200) { // If distance in cm is over 80 and under 200, display "careful"
do {
u8g.drawStr(40,20,"Careful");
u8g.drawBox(0,40,distanceCM/3,30); // Draw box representing the distance
}
while (u8g.nextPage());
}
else if (distanceCM >= 200) { // If distance in cm is over 200, display "safe"
do {
u8g.drawStr(50,20,"Safe");
u8g.drawBox(0,40,distanceCM/3,30); // Draw box representing the distance
}
while (u8g.nextPage());
}
}