#include <Wire.h>
#include <ESP32Servo.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// declare an SSD1306 display object connected to I2C
Adafruit_SSD1306 oled(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
static const int servoPin = 13;
Servo servo1;
int trigPin = 19;
int echoPin = 18;
float duration_us, distance_cm;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
servo1.attach(servoPin);
pinMode(2, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// initialize OLED display with address 0x3C for 128x64
if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
while (true);
}
}
void loop() {
// put your main code here, to run repeatedly:
delay(2000); // wait for initializing
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration_us = pulseIn(echoPin, HIGH);
distance_cm = 0.017 * duration_us;
if (distance_cm < 100) {
oled.clearDisplay();
oled.setTextSize(1);
oled.setTextColor(WHITE);
oled.setCursor(0, 10);
oled.println("The Servo has spun to the right!");
oled.display();
for (int posDegrees = 0; posDegrees <= 180; posDegrees++) {
servo1.write(posDegrees);
Serial.println(posDegrees);
delay(20);
}
}
else {
oled.clearDisplay();
oled.setTextSize(1);
oled.setTextColor(WHITE);
oled.setCursor(0, 10);
oled.println("The Servo has spun to the left!");
oled.display();
for (int posDegrees = 180; posDegrees >= 0; posDegrees--) {
servo1.write(posDegrees);
Serial.println(posDegrees);
delay(20);
}
}
// oled.clearDisplay();
// oled.setTextSize(1);
// oled.setTextColor(WHITE);
// oled.setCursor(0, 10);
// oled.println("Distance: ");
// oled.print(distance_cm);
// oled.print(" cm");
// oled.display();
// oled.setTextSize(1);
// oled.setTextColor(WHITE);
// oled.setCursor(0, 30);
// oled.println("Duration: ");
// oled.print(duration_us);
// oled.print(" us");
// oled.display();
// delay(5000);
// digitalWrite(2, HIGH);
// Serial.println("The LED is on!");
// oled.clearDisplay();
// oled.setTextSize(1);
// oled.setTextColor(WHITE);
// oled.setCursor(0, 10);
// oled.println("The LED is on!");
// oled.display();
// delay(2000);
// digitalWrite(2, LOW);
// Serial.println("The LED is off!");
// oled.setTextSize(1);
// oled.setTextColor(WHITE);
// oled.setCursor(0, 30);
// oled.println("The LED is off!");
// oled.display();
}