#include "U8glib.h"
#define ECHO_PIN 6
#define TRIG_PIN 7
U8GLIB_SSD1306_128X64 u8g; // create an instant of OLED display
void setup() {
Serial.begin(115200);
u8g.setFont(u8g_font_7x13); // set the font for text
//u8g.setColorIndex(1); set the display colour can be done outside picture loop
}
float readDistanceCM() {
unsigned long timestart = millis();
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
int duration = pulseIn(ECHO_PIN, HIGH);
return duration * 0.034 / 2;
unsigned long timeend = millis();
Serial.println("----");
Serial.println(timeend - timestart);
}
void loop() {
float distance = readDistanceCM();
Serial.println(distance);
//delay(50);
u8g.firstPage(); //marks the beginning of the picture loop.
do {
u8g.setColorIndex(1); // set the colour to white
//note (X,Y) position is the lower left corner of the first character of the string
u8g.drawFrame(4, 10, 128, 20); //draw frame at (0,10) with width = 128, height = 20
if (distance < 108) {
u8g.drawBox(10, 15, distance, 10);
}//draw box at (10,15) with width = x, height = 10
else if (distance >= 108) {
u8g.drawBox(10, 15, 108, 10);
}
if (distance >= 200) {
u8g.drawStr(0, 50, "safe");
}
else if (80 <= distance <= 200) {
u8g.drawStr(0, 50, "Careful");
}
else if (distance <= 80) {
u8g.drawStr(0, 50, "Too close");
}
u8g.setColorIndex(0); //change the colour back to black
} while ( u8g.nextPage() ); //marks the end of the body of the picture loop
u8g.setColorIndex(1);
u8g.drawStr(0, 20, "outside");
//drawing function must use inside the picture loop.
delay(500);
}