Basic LED Animations for Beginners (Arduino)

Contributors: Brandon J. Williams
Favorited Favorite 2

One for the Road

Last exercise is for a taste of using LEDs as indicators for a sensor as opposed to toggling or fading an LED. Sensor indicating lights are a very simple and effective form of user interface. So we'll trigger a 'stoplight' sequence when the proximity sensor detects something getting too close.

Check out the circuit diagram below to see how everything is connected.

Stoplight example using using RYB LEDs and a distance sensor

Copy and paste the following code into the Arduino IDE. Hit upload, and see what happens!

//This example will trigger a 'stoplight' sequence when the proximity sensor detects something getting too close.

//Declare pins and variables
int trigger = 13;
int echo = 12;
int red = 2;
int yellow = 3;
int green = 4;

void setup() {
  Serial.begin(9600);               //Initialize serial monitor at 9600 baud
  pinMode(trigger, OUTPUT);         //Output to initiate sensor cycle
  pinMode(echo, INPUT);             //Input to do math from for distance
  pinMode(red, OUTPUT);
  pinMode(yellow, OUTPUT);
  pinMode(green, OUTPUT);

  digitalWrite(green, HIGH);

void loop() {
  long duration, distance;
  digitalWrite(trigger, LOW);
  digitalWrite(trigger, HIGH);
  digitalWrite(trigger, LOW);
  duration = pulseIn(echo, HIGH);   //Reads PWM
  distance = (duration / 2) / 29.1; //Take half of duration and divide by 29.1
  Serial.println(" cm");

  if (distance <= 15) {
    //Stoplight Animation
    digitalWrite(green, LOW);
    digitalWrite(yellow, HIGH);
    digitalWrite(yellow, LOW);
    digitalWrite(red, HIGH);
    digitalWrite(red, LOW);
    digitalWrite(green, HIGH);

When the code initializes, the LED will have the green LED turned on. Once an object gets too close to the ultrasonic sensor, the stoplight sequence will start animating. This is a simplified example of how a stoplight works using an ultrasonic sensor to trigger the LEDs. Depending on the designer, a traffic control system may use image processing with cameras, radar, infrared sensors, magnetometers, or inductive loops to detect when a car is trying to cross an intersection. If a car is detected, the stoplight will trigger to notify other cars across from the intersection to slow down and stop. After a few sections, the LED will reset to green and run through the sequence again if there still is an object in front of the ultrasonic sensor.

Try adjusting the code to keep the red LED on as long as the object is in front of the ultrasonic sensor as opposed to reseting to green. The circuit is just a miniature prototype of a traffic control system. Try mounting the LEDs in a cardboard enclosure to make your own miniature intersection for two, one-way streets. Then try adding more LEDs and adjusting the code to control LEDs for a four-way intersection.

Demo LEDs Sequencing in a Stoplight a Hand Gets too Close to the Proximity Sensor