programming HC-SR04

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

The code in your last post (#19) seems to fit the requirement.

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

What does that mean? I can't see what it does, that is strange, so you will have to explain it to me.

Did someone modify a post. A few minutes ago they replied with a different if statement that checks to see if it is less and not equal to zero.
If someone could repost that answer, i am having the same problem. anything past 400cm and it registers as a zero and turns the led on

Sorry, I posted that before i read your previous post and it was all wrong.

groundFungus:
Sorry, I posted that before i read your previous post and it was all wrong.

so my code #19 does address my problem with it reading 0cm and keeping the LED on?

No not really. Try this:

// ---------------------------------------------------------------------------
// 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 && distance != 0) // less than 40 and exclude 0 readings
   {
      digitalWrite(redLed, HIGH);
   }
   else
   {
      digitalWrite(redLed, LOW);
   }
}