programming HC-SR04

Hello, I am trying to learn more about the arduino language, and the code below is the example from the NewPing library called “NewPingExample”

// ---------------------------------------------------------------------------
// Example NewPing library sketch that does a ping about 20 times per second.
// ---------------------------------------------------------------------------

#include <NewPing.h>

#define TRIGGER_PIN  12  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     11  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

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

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}

void loop() {
  delay(50);                     // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm()); // Send ping, get distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");
}

My question is, how do i get it to turn on an led when the distance gets lower than 10cm?

I know that i must assign a digital pin and set it to a output to turn on the LED, so lets say digital pin 8 on the arduino Uno.
Here the part im not sure about because i am very new to programming, But i believe that i must make an (IF) statement to say when
sonar.ping_cm < 10cm
digitalWrite (8,HIGH)

I’m definitely sure that code won’t compile, can anyone nudge me in the right direction, please?

The if structure reference.

Thank you for the reply and the link. Here is my best go at it.

// ---------------------------------------------------------------------------
// Example NewPing library sketch that does a ping about 20 times per second.
// ---------------------------------------------------------------------------

#include <NewPing.h>

#define TRIGGER_PIN  12  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     11  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
redLed = 8
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
  digitalWrite(redLed,OUTPUT);
}

void loop() {
  delay(50);                     // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm()); // Send ping, get distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");
if (sonar.ping_cm > 10cm)
digitalWrite(redLed,HIGH);
}

I cant get past the first error code, which says redLed was not declared in this scope and it also says redLed is not a name type.
Could you explain why this is?

redLed = 8

The problem is in the variable declaration for the led pin. All variables must have a data type assigned when they are declared. Like so:

byte redLed = 8;

And the semicolon is missing from that statement.

Thank you once again, my next error code is where the IF statement starts.
It says (unable to find numeric literal operator 'operator""cm'

Since sonar.ping_cm is a function you cannot compare it to 10 cm, you need to compare the value it returns to 10.

The example prints the value but does not store it, so step 1 is to define storage for the distance value, sonar.ping_cm returns an unsigned int.

#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
unsigned int distance;

Step 2 is to store the value read in your new variable.

void loop() {
  delay(50);  
  distance = sonar.ping_cm();

Now change the print statement to use the variable.

  Serial.print("Ping: ");
  Serial.print(distance); // Send ping, get distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");

At this point the program should work identically to the example. If it does, add the LED code.

Look at the button example in IDE under File=>Examples=>Digital=>Button. Copy the bits that deal with the LED into your program. You will need to change the if statement to look at your distance variable, comparing it to 10, in place of the buttonState variable in the example.

In the if you want to compare 2 numeric values. 10 is a numeric value, 10cm is not (to the compiler).

Ok, thank you everyone so much for the replys, i feel like i am getting close. This code compiles but i want to get your approval before i physically try it.

// ---------------------------------------------------------------------------
// Example NewPing library sketch that does a ping about 20 times per second.
// ---------------------------------------------------------------------------

#include <NewPing.h>

#define TRIGGER_PIN  12  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     11  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
unsigned int distance;
byte redLed = 8;
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
  digitalWrite(redLed,OUTPUT);
}

void loop() {
  delay(50);                     // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  distance = sonar.ping_cm(); 
  Serial.print("Ping: ");
  Serial.print(distance); // Send ping, get distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");
if (sonar.ping_cm()> 4){
digitalWrite(redLed,HIGH);
} else {
  digitalWrite(redLed,LOW);
}
}
digitalWrite(redLed,OUTPUT);

That, probably, should be:

pinMode, redLed, OUTPUT);

To set the pin to output mode, then digitalWrite to the pin.

If I may, a couple of points on programming style to make your code more readable and easier to debug.

Put every { and } on their own lines. Doing so makes the code blocks easier to see and mismatched brackets stand out. Like so:

if (sonar.ping_cm()> 4)
{
   digitalWrite(redLed,HIGH);
} 
else 
{
  digitalWrite(redLed,LOW);
}

Use the auto format feature of the IDE (ctrl-t or Tools, Auto Format) to indent the code in a standard fashion. That improves readability and makes some common errors like mismatched brackets and missing semicolons stand out.

Here is your code with the above applied.

// ---------------------------------------------------------------------------
// Example NewPing library sketch that does a ping about 20 times per second.
// ---------------------------------------------------------------------------

#include <NewPing.h>

#define TRIGGER_PIN  12  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     11  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
unsigned int distance;
byte redLed = 8;
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

void setup()
{
   Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
   pinMode(redLed, OUTPUT);
}

void loop()
{
   delay(50);                     // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
   distance = sonar.ping_cm();
   Serial.print("Ping: ");
   Serial.print(distance); // Send ping, get distance in cm and print result (0 = outside set distance range)
   Serial.println("cm");
   if (sonar.ping_cm() > 4)
   {
      digitalWrite(redLed, HIGH);
   }
   else
   {
      digitalWrite(redLed, LOW);
   }
}

Okay i corrected my formatting and you are right, it is much easier to read.
Also i changed my pinMode because i accidentally put digitalWrite when setting up my led pin.

// ---------------------------------------------------------------------------
// Example NewPing library sketch that does a ping about 20 times per second.
// ---------------------------------------------------------------------------

#include <NewPing.h>

#define TRIGGER_PIN  12  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     11  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
unsigned int distance;
byte redLed = 8;
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

void setup() 
{
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
  pinMode(redLed, OUTPUT);
}

void loop() 
{
  delay(50);                     // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  distance = sonar.ping_cm();
  Serial.print("Ping: ");
  Serial.print(distance); // Send ping, get distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");
  if (sonar.ping_cm() > 4) 
  {
    digitalWrite(redLed, HIGH);
  }
  else 
  {
    digitalWrite(redLed, LOW);
  }
}

Am i ready for testing?

It works! thank you so much, but what is the scaling for this?
10 = 200? 5=100? ect.

 distance = sonar.ping_cm();
  Serial.print("Ping: ");
  Serial.print(distance); // Send ping, get distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");
  if (distance > 4)

Thank you for that correction, i applied it. But the problem i am having with both sketches is even when i change the distance from 1 to 9, the LED turns on from about 4ft away or less. The distance doesnt vary. Is there something wrong i am doing and is the scale from 1-10?

You appear to be turning on the LED for any range greater than 4cm.
(I assume HIGH is on - I don't know how your LED is wired)

The way the code is written, there are 2 conditions that turn off the LED. The sonar will return 0 if there is nothing in range (no echo within the timeout) or the range is less than 4 centimeters. And that is how it works on my test setup.

What do you want to happen?

I have the anode of my LED going to pin 8 and cathode to ground on arduino. What i am noticing now. is any disance beyond 400cm. I get a readining of 0cm on my serial monitor and that counts as lower than 40cm so the LED pin stays lit. Is there a way around this?

I have actually been able to mess around with distances and the serial monitor and i have a better grasp on it now, except if the ultrasonic sensor is pointed somewhere farther than 400cm it will register as 0cm and since 0cm is less than 40 cm. the led stays lit.
Is there a way around this?

and also when i unplug the Arduino from the computer and power it with a phone charger, the circuit behaves very differently.

groundFungus:
The way the code is written, there are 2 conditions that turn off the LED. The sonar will return 0 if there is nothing in range (no echo within the timeout) or the range is less than 4 centimeters. And that is how it works on my test setup.

What do you want to happen?

I only want it to turn on when i am 40cm or less. if it detects nothing , i want the led off.

I realize now that the one i showed you b4 does not do what i said above,
but i believe this does

// ---------------------------------------------------------------------------
// Example NewPing library sketch that does a ping about 20 times per second.
// ---------------------------------------------------------------------------

#include <NewPing.h>

#define TRIGGER_PIN  12  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     11  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 400 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
unsigned int distance;
byte redLed = 8;
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

void setup() 
{
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
  pinMode(redLed, OUTPUT);
}

void loop() 
{
  delay(50);                     // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  distance = sonar.ping_cm();
  Serial.print("Ping: ");
  Serial.print(distance); // Send ping, get distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");
  if (distance > 40) 
  {
    digitalWrite(redLed, LOW);
  }
  else 
  {
    digitalWrite(redLed, HIGH);
  }
}