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.
This should work. So, try this way and if it won't work still, it is probably a faulty sensor.