Hi! I'm pretty new to arduino and this is my first project, I'm trying to upload my code to the robot and it just stops working few mins after i upload it. i'm trying to build a obstacle avoidance robot who on sensing obstacle stops moving forwards, i have four wheels connected to 2 motors, 2 wheels for either side and l298n motor driver connected to motors, arduino uno, an ultrasonic sensor,i have 6 motor pins connected to 2 to 9 digital ports use 3 and 9 for pwm, and ultrasonic sensor pins are connected in 2 and 3, car starts running at 125 speed 2 sec after switch is on, stops if there is a obstacle near 5 cm,
here's my code
// Pin configuration
const int trigPin = 2; // Connect Trig pin of the ultrasonic sensor to digital pin 2-black
const int echoPin = 3; // Connect Echo pin of the ultrasonic sensor to digital pin 3
const int motor1A = 4; // Motor 1 input A - connect to digital pin 4-white
const int motor1B = 5; // Motor 1 input B - connect to digital pin 5-gray
const int motor2A = 6; // Motor 2 input A - connect to digital pin 6-purple
const int motor2B = 7; // Motor 2 input B - connect to digital pin 7-blue
const int thresholdDistance = 20; // Set the threshold distance for obstacle detection
void setup() {
// Motor control pins as output
pinMode(motor1A, OUTPUT);
pinMode(motor1B, OUTPUT);
pinMode(motor2A, OUTPUT);
pinMode(motor2B, OUTPUT);
// Ultrasonic sensor pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
// Measure distance using the ultrasonic sensor
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.println(distance);
// Check if there is an obstacle within the threshold distance
if (distance < thresholdDistance) {
// Stop the motors if obstacle detected
stopMotors();
} else {
// Move the robot forward if no obstacle
moveForward();
}
}
void moveForward() {
digitalWrite(motor1A, HIGH);
digitalWrite(motor1B, LOW);
digitalWrite(motor2A, HIGH);
digitalWrite(motor2B, LOW);
}
void stopMotors() {
digitalWrite(motor1A, LOW);
digitalWrite(motor1B, LOW);
digitalWrite(motor2A, LOW);
digitalWrite(motor2B, LOW);
}
//2 motor motor 1 ka pin ab hoga motor aage 125 speed