#include <Arduino.h>
#include <U8g2lib.h>
#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif
U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Display
// Define pins for ultrasonic sensor
int const trigPin = 10;
int const echoPin = 9;
void setup(void) {
u8g2.begin(); // Oled display begins
pinMode(trigPin, OUTPUT); // trig pin will have pulses output
pinMode(echoPin, INPUT); // echo pin should be input to get pulse width
}
void loop(void) {
int duration, distance; // Duration will be the input pulse width and distance will be the distance to the obstacle in centimeters
// Output pulse with 1ms width on trigPin
digitalWrite(trigPin, HIGH);
delay(1);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH); // Measure the pulse input in echo pin
distance = (duration/2) / 29.1; // Distance is half the duration devided by 29.1 (from datasheet)
// if distance less than 0.5 meter and more than 0 (0 or less means over range)
if (distance <= 50 && distance >= 0) {
u8g2.clearBuffer(); // clear the internal memory
u8g2.setFont(u8g2_font_inr30_mf); // choose a suitable font
u8g2.drawStr(0,50,"CAT"); // write something to the internal memory
u8g2.sendBuffer(); // transfer internal memory to the display
} else {
u8g2.clearBuffer(); // clear the internal memory
u8g2.sendBuffer(); // transfer internal memory to the display
}
delay(30);
}
Comments
Please log in or sign up to comment.