Search code examples
arduinoarduino-ultra-sonic

Why ultrasonic sensor just output 0 in Arduino?


I have developed a code to get distance using an Ultrasonic Sensor. But it doesn't seem to work. It just output 0. Here's the code.

`#include <math.h>

void setup() {

Serial.begin(9600);

}

void loop() {

int dist = getcm();

delay(100);

Serial.println(dist);

}

int getcm() {

digitalWrite(A0, LOW);

delayMicroseconds(2);

digitalWrite(A0, HIGH);

delayMicroseconds(10);

digitalWrite(A0, LOW);

int duration = pulseIn(A1, HIGH);

int distance = (duration*.0343)/2;

distance = round(distance);

return distance;

}`

Is anything wrong with the code? Or the problem is with the sensor?


Solution

  • I do not know how the interface on these sensors work but, there are easier ways to do this like using the NewPing.h library.

    #include <NewPing.h>
    NewPing sonar (10, 11, 20);
    
    void setup() {
    Serial.beign(9600);
    delay(50);
    }
    
    void loop() {
    Serial.print("The Distance is:");
    Serial.println(sonar.ping_cm());
    delay(1000);
    }
    

    This should work. So, try this way and if it won't work still, it is probably a faulty sensor.