Arduino HC-SR04 NewPing Code Not Working

2.9k Views Asked by At

I was getting to know this ultrasonic detector with a simple code. All I was looking for was an output (my LED) to light up whenever the detector sensed an object within so many centimetres. However the LED remains lit and the serial monitor just keeps spitting out the value '0.00cm'

I would appreciate any help, thanks.

(I do apologise if there is a very simple error I have overlooked)

#include <NewPing.h>

int TriggerPIN = 2;
int EchoPIN = 3;
int LEDPIN = 7;

void setup() 
{
Serial.begin(9600);
//That started the distance monitor
pinMode(LEDPIN, OUTPUT);
pinMode(TriggerPIN, OUTPUT);
pinMode(EchoPIN, INPUT);
}

void loop() 
{
float Distance, Duration;
digitalWrite(TriggerPIN, LOW);//These three blink the distance LED
delayMicroseconds(2);
digitalWrite(TriggerPIN, HIGH);
delayMicroseconds(10);
digitalWrite(TriggerPIN, LOW);

Duration = pulseIn(EchoPIN, HIGH); //Listening and waiting for wave
Distance = (Duration*0.034/2);//Converting the reported number to CM

if (Distance > 50)
  {
  digitalWrite(LEDPIN,LOW);
  }
else
  {
  digitalWrite(LEDPIN,HIGH);
  }
Serial.print(Distance);Serial.print("cm");
Serial.println(" ");
delay(200);
}
1

There are 1 best solutions below

3
On

A couple of things to try:

Change the serial print to display 'Duration', to see if the problem lies in the centimetre conversion.

If this is not the problem:

(Assuming you are using the NewPing 1.7 library, as found here. )

The NewPing library has a built in 'Ping' function, along with distance conversion. Try replacing the start of your code with this:

#include <NewPing.h>
#define TRIGGER_PIN  2
#define ECHO_PIN     3
#define MAX_DISTANCE 200 // Maximum distance to ping for (cm). Up to ~450cm

 NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

You do not need to then set the Trigger and Echo pins as outputs in your setup.

In your main loop, use these methods to get time and distance in microsecs and centimetres:

 unsigned int pingTime = sonar.ping(); //Gets the ping time in microseconds.
 Serial.print(sonar.convert_cm(pingTime)); // Convert ping time in cm, serial out.

I hope this helps.