Code
#include <ESP32Servo.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <NewPing.h>
#define TRIGGER_PIN 5 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 5 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
#define MOTOR1_P 16
#define MOTOR1_N 17
#define MOTOR2_P 27
#define MOTOR2_N 18
#define RIGHT_BUTTON 34
int distance, distanceFlag, setdistance;
Adafruit_SSD1306 display(128, 64);
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
void setup() {
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
delay(500);
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.println("Obstacle Avoider");
display.display();
pinMode(MOTOR1_P, OUTPUT);
pinMode(MOTOR1_N, OUTPUT);
pinMode(MOTOR2_P, OUTPUT);
pinMode(MOTOR2_N, OUTPUT);
pinMode(34, INPUT_PULLUP);
Serial.begin(9600);
while (digitalRead(RIGHT_BUTTON))
{
display.setCursor(0, 0);
display.clearDisplay();
setdistance = map(analogRead(POT), 0, 4000, 5, 50); // map potentiometer value to distance threshold
display.println("Press right button to start");
display.println();
display.print("Set Distance is ");
display.print(setdistance);
display.println("cm");
display.println();
display.println("Rotate knob to change");
display.display();
delay(50);
}
}
void loop() {
distance = sonar.ping_cm();
setdistance = map(analogRead(POT), 0, 4000, 5, 50);
if (distance > (setdistance + 3))
{
distanceFlag = 0;
display.clearDisplay();
display.setCursor(0, 0);
display.setTextSize(2);
display.println(" MOVING");
display.setTextSize(1);
display.println();
display.print("Set Distance: ");
display.print(setdistance);
display.print("cm");
display.println();
display.println();
display.print("Current Distance: ");
display.print(distance);
display.print("cm");
display.display();
}
if (distance < setdistance && distanceFlag == 0 && distance > 0)
{
distanceFlag = 1;
display.setCursor(0, 0);
display.setTextSize(1);
display.clearDisplay();
display.println("OBJECT DETECTED!");
display.println();
display.print("Distance is ");
display.print(distance);
display.print("cm");
display.display();
}
if (distanceFlag == 0)
{
analogWrite(MOTOR1_N, 200);
digitalWrite(MOTOR1_P, LOW);
analogWrite(MOTOR2_N, 200);
digitalWrite(MOTOR2_P, LOW);
}
else if (distanceFlag == 1)
{
digitalWrite(MOTOR1_N, HIGH);
digitalWrite(MOTOR1_P, LOW);
digitalWrite(MOTOR2_N, LOW);
digitalWrite(MOTOR2_P, HIGH);
}
}