Hello,
I am making a robot car that stops when it comes to any obstacle or pit, that is, it stops if there is an obstacle in front of it or it stops if a pit comes, for this I have an ultrasonic sensor and an IR sensor. I have written this code but the car stops at the obstacle but instead of coming to a stop it rolls over.
// Include the library
#include <L298N.h>
#include <Servo.h>
#include <NewPing.h>
// Pin definition
const unsigned int IN1 = 5;
const unsigned int IN2 = 6;
const unsigned int IN3 = 10;
const unsigned int IN4 = 9;
Servo myservo;
// Create one motor instance
L298N motor_left(IN1, IN2);
L298N motor_right(IN3, IN4);
int us_front = 105;
int us_right = 0;
int us_left = 180;
int irFront = 2;
//int irLeft = 3;
int echoPin = 7;
int trigPin = 8;
int distance;
NewPing us_sensor(trigPin, echoPin, 200);
void setup() {
// Used to display information
Serial.begin(9600);
myservo.attach(4);
myservo.write(us_front);
pinMode(irFront, INPUT);
// Wait for Serial Monitor to be opened
while (!Serial) {
//do nothing
}
}
void loop() {
motor_left.setSpeed(150);
motor_right.setSpeed(150);
int distance = us_sensor.ping_cm();
int valFront = digitalRead(irFront);
//If distance is within 30 cm then adjust motor direction as below
if ((distance > 0 && distance < 30) || valFront == HIGH) {
//Stop motors
motor_left.stop();
motor_right.stop();
delay(200);
//Reverse motors
motor_left.backward();
motor_right.backward();
delay(300);
//Stop motors
motor_left.stop();
motor_right.stop();
delay(500);
//Rotate servo to left
myservo.write(us_left);
delay(500);
//Read left side distance using ultrasonic sensor
int distanceLeft = us_sensor.ping_cm();
//Rotate servo to right
myservo.write(us_right);
delay(500);
//Read right side distance using ultrasonic sensor
int distanceRight = us_sensor.ping_cm();
//Bring servo to center
myservo.write(us_front);
delay(500);
if (distanceLeft == 0 && irFront == LOW) {
motor_right.forward();
motor_left.stop();
delay(500);
} else if (distanceRight == 0 && irFront == LOW) {
motor_right.stop();
motor_left.forward();
delay(500);
} else if (distanceLeft >= distanceRight && irFront == LOW) {
motor_right.forward();
motor_left.stop();
delay(500);
} else {
motor_right.stop();
motor_left.forward();
delay(500);
}
motor_left.stop();
motor_right.stop();
delay(500);
} else {
motor_right.forward();
motor_left.forward();
}
}
Please help me,
Thanks in advance.