Help with ultrasonic sensor

#include <NewPing.h> 
#include <Wire.h> 

#define TRIGGER_PIN 7 
#define ECHO_PIN 8 
#define MAX_DISTANCE 200 
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); 

int testled = 5;
byte ledState = LOW; 


unsigned long currentMillis = 0; 


void setup()
{
 pinMode(testled, OUTPUT); 
}

void loop()
{

        if(ledState == LOW){
	unsigned int uS = sonar.ping(); 
	delay(30);
	int distance = uS / US_ROUNDTRIP_CM;
         if(distance <10){
		ledState = HIGH; 
		currentMillis= millis();
	}
	digitalWrite(testled, ledState);  
  
	if (ledState == HIGH) {  
		if (millis()>(currentMillis+10000)) {
			ledState = LOW;
		}
	}
}
}

I want the led to turn on when there is something in front of the ultrasonic sensor and then turn off when the ultrasonic sensor does not detect anything

Although I want this to happen in the background as I will also be running a another code which is going to be added to this 1

Currently the led just stays on it does not turn off

How is the LED wired? Pin to anode, cathode to resistor to Gnd?
Or Pin to cathode, anode to resistor to +5?

Pin to anode, cathode to resistor to Gnd

Ok dude. Were in your whole code do u digitalWrite your led? Your just changing your ledState Variable...

Edit: Oh i see... in the middle... Gimme a Second...

Where is this given a value?
US_ROUNDTRIP_CM

Put a serial print after this line
int distance = uS / US_ROUNDTRIP_CM;

and see what you are getting for distance

Add UL after this #
10000UL

The led pin is written here:

digitalWrite(testled, ledState);

It the state is low
if(ledState == LOW){
it is changed to HIGH
ledState = HIGH;

and then written.
If the state is HIGH, it is written HIGH again.

Ok. Your Calculation of the distance into cm looks wierd…

I made a code like this some time ago… Take a look at this:

(Dont wonder about the Language… Just some German :D)

#define trigPin 7  // Connect Trig on the module to pin 7 on the Arduino
#define echoPin 6  // Connect Echo on the module to pin 6 on the Arduino

int led = 3;
int led2 = 5;
int led3 = 4;
int repeat = 0;
void setup()
{
  pinMode(led, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  
  pinMode(trigPin, OUTPUT);    // Set the trigPin to output
  digitalWrite(trigPin, LOW);  // Set trigPin low to start
  pinMode(echoPin, INPUT);     // Set echoPin as an input
  Serial.begin(9600);          // Start a serial connection to view the Arduino output
  delay(3000);                 // 3 second pause before we start
}
void loop()
{
 
 repeat = repeat + 1;
 
 
   
 long duration;                     // Define the variable used for the pulse duration
 digitalWrite(trigPin, HIGH);       // Set the trigPin high, to start the measurement
 delayMicroseconds(10);             // Wait 10 uS
 digitalWrite(trigPin, LOW);        // Set the trigPin low, module will send a pulse
 duration = pulseIn(echoPin, HIGH); // Read the pulse length from the module
 duration = duration / 50;  // Convert number to cm (range is 3cm - 4.5M)
 if(repeat==10){
 repeat = 0;
 Serial.println("");
 Serial.println("");
 Serial.println("");
 Serial.println("Entfernung in CM:");
 Serial.println(duration);          // Send the distance to the serial port
 Serial.println("");
 Serial.println("");
 Serial.println("");
 
 if(duration < 20){
   
   
     Serial.println("Abstand: NAH");
 } else
    if(duration < 50){
  Serial.println("Abstand: NORMAL");
   
  
 } else 
    if(duration < 100){
       Serial.println("Abstand: FERN");
     
          
    }
 
 }
 delay(100);    // Wait a second before the next reading
 
 if(duration < 20){
   
    digitalWrite(led, HIGH);
   //  Serial.println("Abstand: NAH");
 } else
    if(duration < 50){
 //  Serial.println("Abstand: NORMAL");
   digitalWrite(led2, HIGH);
  
 } else 
    if(duration < 100){
    //   Serial.println("Abstand: FERN");
      digitalWrite(led3, HIGH);
      
    } else {
     digitalWrite(led,LOW);
    digitalWrite(led2,LOW);
   digitalWrite(led3,LOW); 
    }
}

CrossRoads:
Where is this given a value?
US_ROUNDTRIP_CM

Put a serial print after this line
int distance = uS / US_ROUNDTRIP_CM;

and see what you are getting for distance

Add UL after this #
10000UL

#include <NewPing.h> 
#include <Wire.h> 

#define TRIGGER_PIN 7 
#define ECHO_PIN 8 
#define MAX_DISTANCE 200 
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); 

int testled = 5;
byte ledState = LOW; 


unsigned long currentMillis = 0; 


void setup()
{
 pinMode(testled, OUTPUT); 
 Serial.begin(115200);
}

void loop()
{

        if(ledState == LOW){
	unsigned int uS = sonar.ping(); 
	delay(30);
	int distance = uS / US_ROUNDTRIP_CM;
        Serial.print("Ping: ");
        Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result (0 = outside set distance range)
        Serial.println("cm");
         if(distance <10){
		ledState = HIGH; 
		currentMillis= millis();
	}
	digitalWrite(testled, ledState);  
  
	if (ledState == HIGH) {  
		if (millis()>(currentMillis+10000)) {
			ledState = LOW;
		}
	}
}
}

When doing this I can see that the distance is shown as 0 in the serial monitor, this can be the reason why the led is always on

This is the code I used to produce my code, now looking at this im very sure that there is something wrong with it but I cant really figure out what can anyone help me (im new to arduino):

#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 450 // 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.

pinMode(13,OUTPUT); // pin pe 13, fara rezistenta

}

void loop() {

delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.

unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).

Serial.print("Ping: ");

Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result (0 = outside set distance range)

Serial.println("cm");

if(uS / US_ROUNDTRIP_CM >100)

analogWrite(13, 255);

else

analogWrite(13, 0);

}

Anyone

im very sure that there is something wrong with it

Like what?
It’s not entirely clear to me why you’re doing a PWM write to a non-PWM pin, but it should work.

Try this code.
Change pins + connections to suit.
Change timing to suit.
On detection within range “on-state” in maintained for 3 sec.
One sec delay between pings.

#define trigPin 7
#define echoPin 8
#define datPin 13 // alternatively use as ledPin

float maxrange; // maximum detection range
long duration;
float distance;

void setup()
{
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(datPin, OUTPUT);
  digitalWrite(trigPin, LOW); 	// ensure low state at start
  delay(3000);
}

void loop()
{
   maxrange = 10;
   digitalWrite(trigPin, HIGH); 	// initiate pulse
   delayMicroseconds(10); 		// maintain pulse for 10�s
   digitalWrite(trigPin, LOW);  	// terminate pulse

   duration = pulseIn(echoPin, HIGH);  // measures delay till echo heard
   distance = duration / 29.1 / 2;  // calculates distance in cm

   if (distance < maxrange) {
	   digitalWrite(datPin, HIGH);
	   Serial.print("Activity Detected at ");
	   Serial.print(distance);
	   Serial.println(" cm");
	   delay(3000);
   digitalWrite(datPin, LOW);}
   else{
	   Serial.print("No Activity : ");
	   Serial.print(distance);
	   Serial.println(" cm");}
	   delay(1000);  			// maintain terminates state for 100ms
}

I think your problem is that NewPing will return 0 if the measurement fails (distance too short or too long). The minimum measurable distance is about 3 cm and you set the maximum to 200 cm. If the measurement is outside that range it will return 0 which is <10 so it will be counted as a HIT and turn the LED on for 10 seconds. Try this version:

#include <NewPing.h>
// #include <Wire.h>

#define TRIGGER_PIN 7
#define ECHO_PIN 8
#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

int testled = 5;
byte ledState = LOW;

unsigned long startMillis = 0;

void setup() {
  pinMode(testled, OUTPUT);
}

void loop() {
  if (ledState == LOW) {
    // LED is off
    int distance = sonar.ping_cm();
    // If distance measured and is less than 10 cm, turn on the LED
    if (distance > 0 && distance < 10) {
      ledState = HIGH;
      startMillis = millis();
    }
  } else { // ledState == HIGH
    // If LED has been on for 10 seconds, turn it off
    if (millis() - startMillis > 10000) {
      ledState = LOW;
    }
  }
  digitalWrite(testled, ledState);
}