I'm trying to create a car that can detect an object in front of it and move around it. I've been taking this project in steps, and as of now, I'm just trying to make the car back up when it detects an object. In this project, I am using an Arduino Uno, an HC-SR04 Ping Sensor, an L298 Dual H-Bridge, and 2 DC Motors. When I upload the code onto the Arduino, the car moves forward for a few seconds, then moves backward without stopping, without any object ever going in front of it. When i pick it up and move my hand in front of the sensor, it continues moving backward, so I believe it's not the polarity of the motors. I also put the sensor in a test circuit and it is still detecting objects. I'm also convinced it's not the wiring because when I isolate either part (the motors or the sensor), it works fine. This is the code I created by fusing my ping sensor code with my motor code:
#define trigPin 13
#define echoPin 12
void setup() {
Serial.begin (9600);//ping
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(2, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
}
void loop() {
long duration, distance;
digitalWrite(echoPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance < 4) {
digitalWrite(2, HIGH);
digitalWrite(4, LOW);
analogWrite(3, 160);
digitalWrite(7, HIGH);
digitalWrite(6, LOW);
analogWrite(5, 160);
}
else {
digitalWrite(2, LOW);
digitalWrite(4, HIGH);
analogWrite(3, 160);
digitalWrite(7, LOW);
digitalWrite(6, HIGH);
analogWrite(5, 160);
}
if (distance >= 200 || distance <= 0){
Serial.println("Out of range");
}
else {
Serial.print(distance);
Serial.println(" cm");
}
delay(500);
}
I believe the problem is in the code, but I am not confident in my Arduino coding abilities to see what it is (I've been staring at this code and making small alterations for about a week). If someone could help me with this, that would be great! Thanks!