ping sensor reading 0

Hey I've got a robot with a ping sensor mounted on front. I want it to go forward till it sees a wall the turn and keep going. But it goes forward sees a wall then goes in circles because the sensor keeps reading 0. How do I solve this can I reset the sensor using arduino?

const int leftMotor = 10;
const int rightMotor = 9;
const int pingPin = 7;
const int ledPin = 12;


void setup() {
  pinMode(rightMotor, OUTPUT);
  pinMode(leftMotor, OUTPUT);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}
void loop()
{

  long duration, inches, cm;
  pinMode(pingPin, OUTPUT);

  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);

  Serial.print(inches); //for testing purposes
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();

  if(inches<4 ) { //I want it to turn when it see something less than 4 inches
    digitalWrite(ledPin, HIGH);
    digitalWrite(leftMotor, LOW);
    digitalWrite (rightMotor, LOW);
    delay(1000);
    digitalWrite(leftMotor, HIGH);
    digitalWrite (rightMotor, LOW);
    delay(300);
    digitalWrite(ledPin, LOW);
    digitalWrite(leftMotor, LOW);

    pinMode(pingPin, OUTPUT);

    digitalWrite(pingPin, LOW);
    delayMicroseconds(2);
    digitalWrite(pingPin, HIGH);
    delayMicroseconds(5);
    digitalWrite(pingPin, LOW);

    pinMode(pingPin, INPUT);
    duration = pulseIn(pingPin, HIGH);
    inches = microsecondsToInches(duration);
    cm = microsecondsToCentimeters(duration);

    if(inches<4) { //once it turns i want it to read agian then do a 180 
      digitalWrite(ledPin, HIGH); // if inches is less than 4
      digitalWrite(leftMotor, LOW);
      digitalWrite (rightMotor, LOW);
      delay(1000);
      digitalWrite(leftMotor, HIGH);
      digitalWrite(rightMotor, LOW);
      delay(600);
      digitalWrite(leftMotor, LOW);
      digitalWrite (rightMotor, LOW);
    }
  }

  else {
    digitalWrite(ledPin, LOW);
    digitalWrite(leftMotor, HIGH);
    digitalWrite(rightMotor, HIGH);
  }
}
long microsecondsToInches(long microseconds)
{
  return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds)
{
  return microseconds / 29 / 2;
}
  long  cm;
  cm = microsecondsToCentimeters(duration);

  Serial.print(cm);
  Serial.print("cm");

long microsecondsToCentimeters(long microseconds)
{
  return microseconds / 29 / 2;
}

Why is any of this code here? You don't care about the distance in centimeters.

But it goes forward sees a wall then goes in circles because the sensor keeps reading 0.

Then there is something wrong with your sensor, or how it is connected to the Arduino.

Is this a cross-post?

http://arduino.cc/forum/index.php/topic,109896

Thread locked.