#define TRIG 9 //TRIGER connects to port 9
#define ECHO 8 //ECHO connects to port 8
#include <U8glib.h>
U8GLIB_SSD1306_128X64 u8g; // create an instant of OLED display
int pub_duration =0;
void setup() {
Serial.begin(9600);
pinMode(TRIG, OUTPUT); //set TRIG pin as output
pinMode(ECHO, INPUT); // set ECHO pin as input
}
void draw(String outcome) {
u8g.firstPage(); //marks the beginning of the picture loop.
do {
u8g.setColorIndex(1); // set the colour to white
u8g.setFont(u8g_font_unifont);
u8g.setPrintPos(40, 12);
u8g.print(outcome);
u8g.drawFrame(31, 15, 64, 10);
u8g.drawBox(31,15, ((pub_duration/58)*64)/200, 10);
u8g.setColorIndex(0); //change the colour back to black
u8g.drawBox(95,15,124,10);
u8g.drawPixel(15,18); //update the colour of pixel at (15,18) to black colour
} while ( u8g.nextPage() ); //marks the end of the body of the picture loop
}
void loop() {
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
//set the TRIG pin back to low after 10us
digitalWrite(TRIG, LOW);
// Read the result:
//get length of the ECHO high pulse
int duration = pulseIn(ECHO, HIGH);
pub_duration = duration;
//convert ECHO pulse length in microseconds into cm
Serial.print("Distance in CM: ");
Serial.println(duration / 58);
int distance = duration/58;
//convert ECHO pulse length in microseconds into inch
Serial.print("Distance in inches: ");
Serial.println(duration / 148);
if (distance >= 200)
{
draw("Safe");
}
else if (80 <= distance && distance < 200 )
{
draw("Careful");
}
else if (distance < 80) {
draw("Too Close");
}
}