code for (hc-sr04) ultrasonic sensor to get possible accurate distance

The code I'm using has a limitation of printing only 5 cm for distance, I can't still find the solution for it. Please guide me :slight_smile: Thank you

C O D E

#include "NewPing.h"

#define TRIGGER_PIN 4
#define ECHO_PIN 3
#define MAX_DISTANCE 400

NewPing sonar(TRIGGER_PIN,ECHO_PIN,MAX_DISTANCE);

void setup() {
Serial.begin (9600);
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}

void loop()
{
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
long duration,distance;
duration= pulseIn(ECHO_PIN,HIGH);
distance = duration/58.2;
Serial.print(distance);
Serial.println(" cm");
delay(50);
}

ULTRASONIC.txt (608 Bytes)

Please use code tags (</> button on the toolbar) when you post code or warning/error messages. The reason is that the forum software can interpret parts of your code as markup, leading to confusion, wasted time, and a reduced chance for you to get help with your problem. This will also make it easier to read your code and to copy it to the IDE or editor. If your browser doesn't show the posting toolbar then you can just manually add the code tags:
[code]``[color=blue]// your code is here[/color]``[/code]
Using code tags and other important information is explained in the How to use this forum post. Please read it.

Please always do a Tools > Auto Format on your code before posting it. This will make it easier for you to spot bugs and make it easier for us to read. If you're using the Arduino Web Editor you will not have access to this useful tool but it's still unacceptable to post poorly formatted code. I recommend you to use the standard IDE instead.

Please remove unnecessary blank lines from your code before posting to the forum. One or two to separate code into logical sections is fine but large spaces for no reason or random blank lines just make for more scrolling when we're trying to read your code.

biancadelos:
The code I'm using has a limitation of printing only 5 cm for distance

It's not clear what you mean by that. Are you saying that it always shows the distance as 5, no matter what the distance actually is?

when I used a tape measure cm, it only print an output that is limited to 5cm even it is 1cm NEAR to sensor.

Why have you included the NewPing library and then not used it but read the sensor manually? Seems rather odd.

Steve

I don't know how to use it pls change my code :slight_smile: thanks sir

NewPing wiki for information on the use of the library.

NewPing comes with several useful example sketches. In this case all you need is in the NewPingExample sketch.

Steve