Ultrasonic Sensor Only Gives 0cm


image

Hello! I am currently working on an obstacle-avoiding car, however, it seems like the ultrasonic sensor is not working. To test, I tried out codes from the internet and from my teacher's materials that isolate the ultrasonic sensor only. But even when I tried the simplest code, it still gave out zero. I also tried using a different set of components---different sensor, different wires, different breadboard, different Arduino, everything. Here is a sample code of a test I tried out (i remember trying this out before and it worked). Thanks!

const int echoPin = 2;
const int triggerPin = 3;
int pulseValue;
float centimetersDistance;
const int ledGreen = 4;
const int ledRed = 5;

void setup() {
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(triggerPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  digitalWrite(triggerPin, LOW);
  delayMicroseconds(5);
  digitalWrite(triggerPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(triggerPin, LOW); 

  pulseValue = pulseIn(echoPin, HIGH);
  centimetersDistance = pulseValue * 0.034/2;

  Serial.print("Distance: ");
  Serial.print(centimetersDistance);
  Serial.println(" cm ");
  delay(500);

  if(centimetersDistance >=10) {

    digitalWrite(4, HIGH);
    digitalWrite(5, LOW);
}   else  {
    digitalWrite(4, LOW);
    digitalWrite(5, HIGH);
}
}

IF you wrote this code, you did not study the documentation on pulseln(). If you copied the code, someone else did not read the documentation on on pulseln(). If you want to fix the program, find and read the documentation on pulseln() and fix your program so it looks for zero being returned and the reason why zero may be returned. Then add code to take care of zero being returned.

Check if you connected the sensor correctly, as your code worked correctly here.

I quote what I have already written on another thread about my suspect:

Some time ago I had exactly the same problem when using HC-SR04 sensors, they are mostly bugged and get stuck with "0 cm" (or sometimes "3 cm") readings until powered off and on again, or using a trick I discovered to "recover" that lock situation (by temporarily putting Echo pin as OUTPUT, bringing it LOW then after a vew milliseconds change it back as INPUT) .

So if you're currently using SR04 take this probable issue in consideration. And give HY-SRF05 sensors a try: their cost is a bit higher (a few cents) but I've never had problems with those!

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