1

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?

2
  • you don't set pinMode Commented Sep 12, 2022 at 7:17
  • Thanks. I just set the pinMode and now it is working fine. Commented Sep 13, 2022 at 13:32

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.