#include "U8glib.h"
U8GLIB_SSD1306_128X64 u8g; // hardware
int echo = 8;
int trig = 9;
void setup() {
pinMode(trig, OUTPUT); // set trig output pin
pinMode(echo, INPUT); // set echo input pin
u8g.setFont(u8g_font_7x13); // set the font for letters
}
void loop() {
digitalWrite(trig, HIGH); // start the measuring
digitalWrite(trig, LOW); // low the trig
int duration = pulseIn(echo, HIGH); // read the length of echo high
int box_length = duration / 182; // scale factor for printing box length
int distance = duration / 58;// pulse/58 = distance in centimeters
u8g.firstPage(); // begin the display
do {
if (distance >= 200) {
u8g.drawStr(50, 20, "Safe");
}
else if (distance < 80) {
u8g.drawStr(28, 20, "Too Close");
}
else {
u8g.drawStr(40, 20, "Careful");
}
// display the box starts with upper left cordinate (0,32) and 20 height. take with as box_length which defined above
u8g.drawBox(0, 32, box_length, 20);
} while (u8g.nextPage());
}