My robot isnt working

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.

Where do the ranger pins get set-up?
Where are the debug prints?

i would expect the above to Stop

i expect the above to Turn

i expect the above to go straight

is there a debug print the reports the sensor reading?

Post an annotated schematic showing exactly how you have wired it, including ground, power and power sources. Also provide links to technical information on each of the hardware items. Hint: I do not do well with word problems or frizzies.

I think your sensor is pointed down and seeing the surface (floor, table) less than 20cm away. Point the sensor slightly up.

Thank you for your help. This simple flaw that I had overlooked was what had been causing the robot's malfunction. My robot is working now. thanks a lot!

See reply #2

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.