Hi, I have built a robot using 2 servos, an ultrasonic distance sensor(HC-SR04) and an arduino nano.
when it senses an object, it is supposed to stop for 1 second, turn around, and then continue going. However, when I turn it on, it stops and turns around and goes repeatedly even if there isn't an obstacle, but if there is an obstacle, is crashes into it. I have tested both the servos and the sensor, and there is no hardware issue as far as i can see. Here is the code:
#include <Servo.h>
Servo motor1;
Servo motor2;
int ledPin =(13);
const int sensor = A0;
const int Trig = 9;
const int Echo = 8;
int distance;
int mydistance;
int getDistance() {
digitalWrite(Trig, LOW);
delayMicroseconds(2);
digitalWrite(Trig, HIGH);
delayMicroseconds(20);
digitalWrite(Trig, LOW);
float distance = pulseIn(Echo, HIGH);
distance= distance / 58;
return (int)distance;
}
void Go() {
motor1.write(0);
motor2.write(180);
delay(1000);
}
void Stop() {
motor1.write(90);
motor2.write(90);
delay(1000);
}
void Turn() {
motor1.write(0);
motor2.write(0);
delay(1000);
}
void setup() {
motor1.attach(11);
motor2.attach(10);
pinMode(ledPin, OUTPUT);
pinMode(sensor, INPUT);
Go();
}
void loop() {
mydistance = getDistance();
if(mydistance <= 20){
Stop();
Turn();
Go();
}
else{
Go();
}
}
please help, I would appreciate it.