Hi I am new to Arduino so this may be a stupid question, I have a ultrasonic sensor and a Led that is supposed to blink in different intervals depending on the distance of the object from the sensor. The Led is blinking in strange intervals
Please help
This is my code
// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;
int Ledpin = 11;
// defines variables
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode(Ledpin, OUTPUT); // set the ledpin as output
Serial.begin(9600); // Starts the serial communication
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
// 50 cm away from object
if (distance <=50){
digitalWrite(Ledpin, HIGH);
delay(250);
digitalWrite(Ledpin,LOW);
delay(250);
}
//40 cm away from object
if (distance <=40){
digitalWrite(Ledpin, HIGH);
delay(200);
digitalWrite(Ledpin,LOW);
delay(200);
}
// 30 cm away from object
if (distance <=30){
digitalWrite(Ledpin, HIGH);
delay(150);
digitalWrite(Ledpin,LOW);
delay(150);
}
// 20 cm away from object
if (distance <=20){
digitalWrite(Ledpin, HIGH);
delay(100);
digitalWrite(Ledpin,LOW);
delay(100);
}
// 10 cm away from object
if (distance <=10){
digitalWrite(Ledpin, HIGH);
delay(50);
digitalWrite(Ledpin,LOW);
delay(50);
}
}