简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM