#include <NewPing.
h>
#define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on the ultrasonic
sensor.
#define ECHO_PIN 11 // 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_PIN1 2 // Motor 1 control pin 1
#define MOTOR1_PIN2 3 // Motor 1 control pin 2
#define MOTOR2_PIN1 4 // Motor 2 control pin 1
#define MOTOR2_PIN2 5 // Motor 2 control pin 2
#define FORWARD_SPEED 150 // Forward speed of the motors
#define TURN_SPEED 200 // Speed to turn
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and
maximum distance.
void setup() {
pinMode(MOTOR1_PIN1, OUTPUT);
pinMode(MOTOR1_PIN2, OUTPUT);
pinMode(MOTOR2_PIN1, OUTPUT);
pinMode(MOTOR2_PIN2, OUTPUT);
// Initially move forward
moveForward();
}
void loop() {
delay(50); // Delay to stabilize readings
// Read distance from the ultrasonic sensor
unsigned int distance = sonar.ping_cm();
if (distance <= 10 || distance == 0) { // If obstacle detected or out of range
// Turn right
turnRight();
delay(1000); // Turn for 1 second
// Move forward again
moveForward();
}
}
void moveForward() {
digitalWrite(MOTOR1_PIN1, HIGH);
digitalWrite(MOTOR1_PIN2, LOW);
digitalWrite(MOTOR2_PIN1, HIGH);
digitalWrite(MOTOR2_PIN2, LOW);
analogWrite(MOTOR1_PIN1, FORWARD_SPEED);
analogWrite(MOTOR2_PIN1, FORWARD_SPEED);
}
void turnRight() {
digitalWrite(MOTOR1_PIN1, LOW);
digitalWrite(MOTOR1_PIN2, LOW);
digitalWrite(MOTOR2_PIN1, HIGH);
digitalWrite(MOTOR2_PIN2, LOW);
analogWrite(MOTOR2_PIN1, TURN_SPEED);
}