Keep Getting Pulses To LED

New to this so a little slack please.

See following code, even with the output set to LOW, I get a brief pulse that blinks the LED on Pin 8, Output. LED stays solid when the distance is <= 20, so that works, but get the pulse on the LED each 1000 time it runs the circuit with output LOW. Thanks

#include <NewPing.h>

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

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

void setup() {
// put your setup code here, to run once:

pinMode (8, OUTPUT);

}

void loop() {

//Code to testing if/then on distance.
delay (1000);
digitalWrite(TRIGGER_PIN, LOW);
if (sonar.ping_cm ()<=20);
digitalWrite(8, HIGH);
if (sonar.ping_cm ()>20)
digitalWrite(8, LOW);

if (sonar.ping_cm ()<=20);

The semi colon after the statement terminates the conditional, and the next line is executed.
Remove the ;

See Nick Gammon's Tips and Traps #13

You got it right with the second one.

aarg:
You got it right with the second one.

Indeed, but you omitted the code block { }.

Now I agree the language allows you to do that if there is just a single statement following the if. But many a coding standard, including many professional ones, would say that is bad style.

If you are going to allow it I would insist that the single statement is on the same line as the conditional to make it abundantly clear...

if (sonar.ping_cm ()<=20) digitalWrite(8, HIGH);
if (sonar.ping_cm ()>20) digitalWrite(8, LOW);

...far to easy to make an unintended mistake otherwise (only one of which is slapping an unintended semicolon on the end :wink: ).

Or better still use an else clause...

if (sonar.ping_cm ()<=20) {
  digitalWrite(8, HIGH);
} else {
  digitalWrite(8, LOW);
}

Or just...

digitalWrite(8, sonar.ping_cm ()<=20 ? HIGH : LOW);

And while you’re at it name your pins with constants. You’ll thank me later when you have a 1000 line program and need to remember 20 pin assignments.

Wow, thanks for all the great input and suggestions going forward. Will implement all, and really appreciate the help. My first post and really impressed.

For future issues: If you post your code as described in the how to use this forum sticky, more forum members will read it.