Arduino Mega Smart LED Street System with Ultrasonic Sensor

Hi everyone ! I am working on a project that includes using ultrasonic sensors to power LEDS. This will work the following way: A miniature car will be used to trigger the Ultrasonic Sensors within a certain distance set , that will then trigger the LEDs to be turned on every time the sensors detect the miniature car passing by. Each Sensor corresponds to an individual LED, I will be using 5 LEDS and 5 Ultra Sonic sensors. The LEDS will be activated by the Sensors and then stay on for 2-3 seconds before turning off. The Issue I am having is that if the car stay in front of the UltraSonic sensor then the LED should stay on. Right now when this happens the light stays on but flickers after 1 second. I am trying to figure out how to best optimize this and work as smoothly as possible. I am attaching the code which is only working for 3 LEDs right now since I am still testing before connecting all of them. There is no specific order for the LEDs to turn on but more so according to the UltraSonic sensors.

#define trigPin1 3
#define echoPin1 2
#define trigPin2 4
#define echoPin2 5
#define trigPin3 7
#define echoPin3 8
//#define trigpin4 9
//#define echopin4 10
#define Led1 22
#define Led2 24
#define Led3 26
//#define Led4

long duration, distance, RightSensor,BackSensor,FrontSensor,LeftSensor;

void SonarSensor(int trigPin,int echoPin)
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;

}

void setup()
{
Serial.begin (9600);
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
pinMode(trigPin3, OUTPUT);
pinMode(echoPin3, INPUT);
pinMode(Led1,OUTPUT);
pinMode(Led2,OUTPUT);
pinMode(Led3,OUTPUT);

}

void loop() {
SonarSensor(trigPin1, echoPin1);
RightSensor = distance;

if (distance <= 20)
{
digitalWrite(Led1,HIGH);
delay(1500);
digitalWrite(Led1,LOW);
}
else
{
  digitalWrite(Led1,LOW);
}

SonarSensor(trigPin2, echoPin2);
LeftSensor = distance;

if (distance <= 20)
{
digitalWrite(Led2,HIGH);
delay(1500);
digitalWrite(Led2,LOW);
}
else
{
  digitalWrite(Led2,LOW);
}

SonarSensor(trigPin3, echoPin3);
FrontSensor = distance;


if (distance <= 20)
{
digitalWrite(Led3,HIGH);
delay(1500);
digitalWrite(Led3,LOW);  
}

else
{
digitalWrite(Led3,LOW);

}



Serial.print(LeftSensor);
Serial.print(" - ");
Serial.print(FrontSensor);
Serial.print(" - ");
Serial.println(RightSensor);


}

You found the code tags. You only click once and then paste code in the middle of symbols.

I don't like the delays You use. After the delay(1500) You turn off the LED.....

I recommend:

  • Start using millis() instead of delay()
  • Start using arrays, otherwise your code will finish up 5 times longer than it should be

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.