system
September 13, 2014, 5:41pm
1
I am trying to measure distance with HC-SR04 ultrasonic sensor.
According to my program, it will show out of range when the distance to be measured is out of range. But whenever it is of range in the serial monitor it displays Out of range followed by a garbage distance value. But it works correctly whenever the distance is in range. Please help.
Program given below.
#include<NewPing.h>
#define echo 13
#define trig 12
NewPing sonar(trig, echo);
void setup()
{
Serial.begin(9600);
pinMode(echo, INPUT);
pinMode(trig, OUTPUT);
}
void loop()
{
float duration=0, dis=0;
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
duration=pulseIn(echo, HIGH);
dis=(duration/58);
if (dis >= 450 || dis <= 0)
{
Serial.println("Out of range");
}
else
{
Serial.print("Distance: ");
Serial.print(dis);
Serial.print("Cm");
Serial.println();
}
delay(5000);
}
Attached the serial monitor screenshot
no, it looks like it is reporting out of range, then a distance, then out of range then a distance.
not actually printing "some garbage"
system
September 13, 2014, 6:00pm
3
But why that ? It should display Out of range whenever it is. Please see the next part i.e. Distance: 13.67cm at that time the distance is in range so it displays correctly.
good question. Check your connections.
Also, why are you using float here:
float duration=0, dis=0;
pulseIn returns an unsigned long, I'd think you would want to stick with integer math:
#include<NewPing.h>
#define echo 13
#define trig 12
NewPing sonar(trig, echo);
//
void setup()
{
Serial.begin(9600);
pinMode(echo, INPUT);
pinMode(trig, OUTPUT);
}
//
void loop()
{
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
unsigned long duration = pulseIn(echo, HIGH);
unsigned long dis = (duration / 58);
if (dis >= 450 || dis <= 0)
{
Serial.println("Out of range");
}
else
{
Serial.print("Distance: ");
Serial.print(dis);
Serial.print("Cm");
Serial.println();
}
delay(5000);
}
system
September 13, 2014, 6:10pm
5
Thanks for your reply. After running your code, output attached.
hmmm
did you try to use the library's function?
#include<NewPing.h>
#define MAX_DISTANCE 400
#define echo 13
#define trig 12
NewPing sonar(trig, echo, MAX_DISTANCE);
//
void setup()
{
Serial.begin(9600);
pinMode(echo, INPUT);
pinMode(trig, OUTPUT);
}
//
void loop()
{
int dis = sonar.ping_cm();
if (dis >= MAX_DISTANCE || dis <= 0)
{
Serial.println("Out of range");
}
else
{
Serial.print("Distance: ");
Serial.print(dis);
Serial.print("Cm");
Serial.println();
}
delay(5000);
}
system
September 13, 2014, 6:43pm
7
I tried that previously. Now i tried with the code you provided. Result attached.