1

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);
}
SirBuncey
  • 67
  • 1
  • 2
  • 9

1 Answers1

1

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.

Fin Warman
  • 43
  • 1
  • 8
  • This has given me numbers! But now it just keeps fluctuating around 180 and sometimes down to 178. This is not effected in the slightest by by violent waving around the sensor. – SirBuncey Feb 03 '16 at 20:50
  • Good! Is this the case if you do not use the built-in conversions? I have had problems with the cm conversions before. See if not using the convert_cm helps, or changing the MAX_DISTANCE. – Fin Warman Feb 03 '16 at 21:00
  • Please also bear in mind that the accuracy of the sonar is not perfect.Try holding a larger, steadier object at various distances. I find a piece of white A4 paper works best. – Fin Warman Feb 03 '16 at 21:01