NewPing Library: HC-SR04, SRF05, SRF06, DYP-ME007, Parallax PING))) - v1.7

jaylfc:
Thanks Tim,

I actually managed it before seeing this post but. I have actually soldered the sensor to the control board as this passes the commands to the motor board. The only problem I seem to be having is that once it detects an object within the desired range the pinging stops as do the measurements to the serial monitor. So when it is supposed to rotate and then carry on doing the same again it just seems to end and then the motors go into a wiggling action?

Thanks again!

Jay.

My guess is that it has something to do with the while loop where you never set a ping variable and never output serial results. Like usual, it's just doing what you're telling it to do.

I don't know why you have two nestled curly brackets after loop(), either or what that would even do. Also, you're doing multiple pings and probably shouldn't be. You're doing one to set the variable cm and print the results, then another ping in the while statement that's actually being used to detect an object. My guess is that your loop() routine should be more like this:

void loop() {
  unsigned int cm = sonar.ping_cm(); // Do a ping and set the distance in centimeters to variable cm
  Serial.println(cm); // Output the ping distance in centimeters
  if (cm < 20) { // If an obstacle is less than 20cm away
    Robot.motorsStop(); // stop the motors
    setFace(false); //shows an unhappy face
    Robot.turn(45); // turn to the right and try again
    delay(500); // wait for a moment while it turns (this isn't required if Robot.turn() is a blocking command)
  } else {
    Robot.motorsWrite(155, 155); // if there are no objects in the way, keep moving
    setFace(true); // happy face
    delay(50); // Delay between pings
  }
}

But, I don't ultimately know what you're trying to accomplish, nor have an Arduino Robot to test this with. But, this code makes more sense than what you had and it compiles. Also, this has nothing really to do with NewPing. This is more just simple programming debugging. You were creating a while loop where it wasn't setting a new distance variable nor sending that value to the serial port, so of course it won't output anything for as long as it's stuck in the while loop.

Tim