Sonar Car Trouble

Thanks - more/better info almost always means better help. If you were looking for somebody who knows a little about servos and rangefinders, then you've had incredibly good luck because I know about as little as can be known. :slight_smile:

Here's a short function to think about. It still has the awful delay(), but it accepts an angle and returns a range:

float range(int angle)
{  static int old = 0;
   if (angle != old)
   {  myservo3.write(angle);
      delay(15 * ((angle>old)?angle-old:old-angle));
      old = angle;
   }
   return ultrasonic.convert(ultrasonic.timing(),Ultrasonic::CM);
}

Note that at 15 msec/deg, a full scan will take about 2.7 seconds. I'm not sure what the forward speed is, but I suspect that it might be more productive to do 180° scans only selectively - and keep the bot's attention on where it's going.

You might consider dividing the 180° field of view into twelve 15° segments and maintaining an array of twelve elements containing the distance to the nearest obstacle (if any) in each direction.

The code you posted swings the rangefinder around and then looks for an obstacle only at the final position. I'm unsure about the benefit of only looking straight right, straight ahead, or straight left. Seems to me that it'd make more sense for it to watch where it's going and if it finds itself approaching an obstacle, then slow down and look for an avoidance pathway (but as I say, I don't know much about these things).

I would guess that once the range-finding and motion control are worked out, you'll be ready to tackle the problem of scanning continuously while the bot is in motion - but it'll be easier to work out (and verify) the basics first.