Funduino Traffic Light Intersection – Setup and Practical Exercises

FunduinoPublished on

Ampelphasen und Fußgängeranforderung mit dem Arduino MEGA programmieren

Mit der Arduino-kompatiblen Ampelkreuzung simulierst du Verkehrsflüsse an Kreuzungen durch individuelle Programmierung von Ampelsequenzen. Ideal für Bildungszwecke, Hobbyprojekte oder technische Demonstrationsmodelle.

In dieser Anleitung erläutern wir zunächst die Grundlagen der Ampelfunktion sowie die Rolle und Funktionsweise eines lichtabhängigen Widerstands (LDR). Im weiteren Verlauf zeigen wir anhand eines praktischen Beispiels, wie du eine solche Kreuzung realitätsnah programmierst.

Funduino traffic light intersection with attached traffic lights

Layout and Equipment of the Intersection

Flexible traffic light configuration: The base plate has space for up to six individual traffic lights, each with three colors (red, yellow, green) for controlling road traffic. In addition, each traffic light has a red and green pedestrian signal that can face left or right.

Control with the Arduino MEGA: The integrated Arduino MEGA microcontroller, with its 54 digital I/O ports and 16 analog inputs, provides ample capacity to control a variety of LEDs and program complex traffic light sequences.

Interactive sensors: A photoresistor is built into each lane and can detect whether vehicles are waiting at the traffic light. This enables adaptive traffic control based on real traffic conditions, including traffic jam monitoring.

Roads: The Funduino intersection connects a two-lane road with a three-lane road. On the two-lane road, vehicles can either go straight or turn right, while on the three-lane road, they can turn left or right. This intersection can be seamlessly expanded with Funduino road stickers to connect multiple traffic light systems.

Preparation

First, plug the Arduino MEGA microcontroller into the designated slot on the traffic light intersection and install the individual traffic lights. You can connect adjacent traffic lights with a plastic clip for greater stability.

When attaching the microcontroller, make sure the base plate is resting flat on a surface so that the board does not bend too much and get damaged.

Arduino MEGA in the traffic light intersection slot
Lay the base plate flat so the circuit board doesn't bend.
1 / 2

The LDR sensors in the roadway

LDR sensors (photoresistors) change their resistance depending on the intensity of light falling on them. The more light that falls on the sensor, the lower its resistance, allowing more current to flow. A second resistor forms a voltage divider. The microcontroller then evaluates the sensor’s voltage to determine whether a vehicle is covering the sensor and casting a shadow on it.

LDR sensor (photoresistor) in the roadway

Labeling of the traffic light bases

Each traffic light base is labeled in detail. On one side, you can see which digital pin on the microcontroller the corresponding contact is connected to. On the other side, you can see which LED or button corresponds to that traffic light.

Labeling a traffic light base with pin numbers

Program a single LED

Task: The traffic light's red LED should blink.

We plug a traffic light into the slot right next to the MEGA microcontroller. This uses digital pins 34, 35, 36, 37, 38, and 39.

  • Pin 34 – Green traffic light LED
  • Pin 35 – Yellow traffic light LED
  • Pin 36 – Red traffic light LED
  • Pin 37 – Push button contact
  • Pin 38 – Red pedestrian traffic light LED
  • Pin 39 – Green pedestrian traffic light LED

For this task, we only need one pin on the microcontroller board: pin 36. The LED for the red traffic light is connected to pin 36. A voltage must be output on pin 36, since the LED needs to light up. Therefore, the setup must specify that pin 36 is an output.

The explanations after the double slash "//" can be entered in the Arduino software, but they have no effect on how the sketch runs. This so-called commenting is very useful when programming, as it lets you leave information about the program for yourself.

The sketch in the Arduino software, Upload button at the top left
Make a red LED blink
void setup()     //Setup begins here.
{        //A program section begins here.
pinMode(36, OUTPUT); //Pin 36 should be an output.
}        //A program section ends here.
void loop()      //The main program begins here.
{         //A program section begins here.
digitalWrite(36, HIGH);//Turn on the voltage at pin 36 (LED on).
delay(1000);      //Wait 1000 milliseconds (one second).
digitalWrite(36, LOW);//Turn off the voltage at pin 36 (LED off).
delay(1000);      //Wait 1000 milliseconds (one second).
}              //Program section ends here.

Variant: make the LED blink faster

After the last curly brace in the loop section, the sketch is complete. When the sketch has run through the loop section to the final brace, it starts again at the beginning of the loop section. This makes the LED turn on and off repeatedly.

You can now modify the program. For example, the LED should blink faster. To do this, we shorten the delays (delay) from 1000 milliseconds to 200 milliseconds.

Variant: flash faster (200 milliseconds)
void setup()        //Here begins the setup
{           //Here begins a program section.
pinMode(36, OUTPUT);    //Pin 13 should be an output.
}           //This program section ends.
void loop()         //Here begins the main program
{           //Program section begins.
digitalWrite(36, HIGH); //Turn on the voltage at pin 36 (LED on).
delay(200);         //Wait 200 milliseconds
digitalWrite(36, LOW); //Turn off the voltage at pin 36 (LED off).
delay(200);       //Wait 200 milliseconds
}         //Program section ends.

Task 2 – The alternating flasher

Task: Two LEDs should blink alternately. You can vary the blinking speed and rhythm. For this task, we’ll use the red and green LEDs in the traffic light. So, in addition to pin 36, we’ll now also need pin 34, which is connected to the green LED.

The shorter the “delay,” the faster the blinking rhythm. You can set the rhythm so fast that the human eye can no longer distinguish between the lit and unlit phases. With this sketch, you can, for example, recreate the flashing sequence of a fire truck or police car, or a traffic light at a railroad crossing. At a traffic light intersection, flashing is only needed if the system fails and all the yellow traffic lights are supposed to flash. Is this a task you can solve?

Alternating flasher
void setup()
{     //We start with the setup
pinMode(36, OUTPUT);  //Pin 36 is an output.
pinMode(34, OUTPUT);  //Pin 34 is an output.
}
void loop()
{       //The main program begins.
digitalWrite(36, HIGH); //Turn on the LED on Pin 36.
delay(1000);           //Wait 1000 milliseconds.
digitalWrite(36, LOW);  //Turn off the LED on Pin 36.
digitalWrite(34, HIGH); //Turn on the LED on Pin 34.
delay(1000);           //Wait 1000 milliseconds.
digitalWrite(34, LOW);  //Turn off the LED on Pin 34.
}       //Here at the end, the program jumps back to the start of the loop section. So: turn on the LED on Pin 36… and so on…

Read the voltage at the photoresistor

The microcontroller is meant to read how bright it is using a photoresistor. To do this, it uses a simple physical principle: When two loads are connected one after the other in a circuit (in series), the voltage applied across them is also “divided.” For example: Two identical lamps are connected in series and a voltage of 6 volts is applied. Each lamp then has only 3 volts across it. If two different lamps are connected, two different voltages are measured, e.g. 1.5 volts and 4.5 volts.

A photoresistor changes its resistance depending on the light intensity. This effect is used to read a brightness or darkness value based on the voltage present. To create a voltage divider, connect the photoresistor and a resistor (1–10 kOhm, depending on the photoresistor used; the resistor should have a similar resistance value to the photoresistor) in series, then connect them to 5 volts and ground (Ground / GND).

The microcontroller board at the intersection can measure and process analog signals. It converts the measured voltage into a number: 0 volts corresponds to a value of 0, and the highest reading at 5 volts corresponds to a value of 1023 (0 to 1023 corresponds to 1024 numbers = 10 bits). For example: If a voltage of 2.5 volts is measured, the microcontroller returns a value of 512.

The Serial Monitor

The "Serial Monitor" is an important part of the Arduino software. It lets you view data and values on your PC that the microcontroller board sends to it. This is useful because there isn't always an LCD connected to the microcontroller that you can use to read values.

In this sketch, the Serial Monitor is used to display the values the board reads from the photoresistor. Suppose the LED should only light up as it starts to get dark. The sketch then needs a section with the function: "If the photoresistor reading falls below x, the LED should light up." To do this, you need to know what the value of x is at the start of dusk.

In our specific example of the traffic light intersection, you can use this value in the software to determine whether a vehicle is over the sensor or not.

Program the photoresistor

For the following program, we read the measured value from “Sensor 1.” This sensor is located right next to the MEGA microcontroller.

Later in the intersection programming, you will use the same code to make decisions based on the sensor value.

Read a photoresistor and switch an LED on/off
int eingang=A0; //Das Wort „eingang“ steht jetzt für den Wert „A0“ (Bezeichnung vom Analogport 0)
int LED=36;   //Das Wort „LED“ steht jetzt für den Wert 36. Hier wird also die Rote LED an der Ampel angesteuert, die sich genau neben dem Mikrocontroller befindet.
int sensorwert=0; //Variable für den Sensorwert mit 0 als Startwert
void setup()    //Hier beginnt das Setup.
{
Serial.begin(9600); //Die Kommunikation mit dem Seriellen Port wird gestartet, um den Wert des Sensors im Seriellen Monitor darzustellen.
pinMode (LED,OUTPUT);//Der Pin mit der LED (Pin 36) ist jetzt ein Ausgang
}
void loop()
{ //Mit dieser Klammer wird der Loop-Teil geöffnet.
sensorwert=analogRead(eingang); //Die Spannung an dem Fotowiderstand auslesen und unter der Variable „sensorWert“ abspeichern.
Serial.println("Sensorwert=");  //Der Befehl „Seriel.print“ erzeugt eine Ausgabe am Seriellen Monitor.: Das Wort „Sensorwert:”
Serial.println(sensorwert); // Ausgabe am Seriellen Monitor. Mit dem Befehl „Serial.println“ wird der Sensorwert des Fotowiderstandes in Form einer Zahl zwischen 0 und 1023 an den Seriellen Monitor gesendet. Durch die Erweiterung um die beiden Buchstaben „LN“ wird aus dem Befehl „Seriel.println“. Dadurch wird bei der Ausgabe am Seriellen Monitor ein Seitenumbruch erzeugt und die Messwerte sind leichter ablesbar
if(sensorwert < 512)     //Wenn der Sensorwert unter dem Wert 512 liegt….
{
digitalWrite(LED,HIGH); //…soll die LED leuchten…
}
else        //…andernfalls
{
digitalWrite(LED,LOW);  //…soll sie nicht leuchten
}
delay(50);//Eine kurze Pause, in der die LED an oder aus ist
} //Mit dieser letzten Klammer wird der Loop-Teil geschlossen.
//Wenn nun der Sensorwert bei normaler Helligkeit bspw. nur den Wert 100 hat (der Wert ist abhängig von den verwendeten Widerständen, von der Helligkeit und von der Stromrichtung), dann nimmt man anstelle des Wertes 512 einen wesentlich kleineren Wert, bei dem die LED zu leuchten beginnen soll. Bspw. nimmt man dann den Wert 90. Den aktuellen Sensorwert kann man sich nun mithilfe des Seriellen Monitor anzeigen lassen. Dazu klickt man oben auf „Werkzeuge“ und anschließend auf „Serieller Monitor“
Diagram: Decision based on the sensor value
if(sensorwert < 512)     //If the sensor value is below 512….
{
Option 1 happens (For example, the traffic light for vehicles stays green)
}
else        //…otherwise
{
Option 2 happens (For example, the traffic light for vehicles changes to red)
}

Program a traffic light

In this project, we’ll start programming the first traffic light. We’ll use a different slot for this: the slot with digital pins 4, 5, 6, 7, 8, and 9.

  • Pin 4 – LED for the green traffic light
  • Pin 5 – LED for the yellow traffic light
  • Pin 6 – LED for the red traffic light
  • Pin 7 – Button contact
  • Pin 8 – Red LED for the pedestrian traffic light
  • Pin 9 – Green LED for the pedestrian traffic light

In the setup, we specify that the pins connected to the LEDs are configured as OUTPUTS. This means they send signals. The pin connected to the button is set as an INPUT and has a so-called PULLUP resistor. A PULLUP resistor ensures that the voltage on this pin is high by default. When the button is pressed, the voltage drops to LOW. So, to check whether the button has been pressed, we look for a LOW signal rather than a HIGH signal.

Step 3.1: Define the pins
#define AMPEL_1_GRUEN 4
#define AMPEL_1_GELB 5
#define AMPEL_1_ROT 6
#define AMPEL_1_KNOPF 7
#define AMPEL_1_FUSSGAENGER_ROT 8
#define AMPEL_1_FUSSGAENGER_GRUEN 9
//This defines the pins for the first traffic light.
Step 3.2: The setup
void setup()
{
// LEDs
pinMode(AMPEL_1_GRUEN, OUTPUT);
pinMode(AMPEL_1_GELB, OUTPUT);
pinMode(AMPEL_1_ROT, OUTPUT);
pinMode(AMPEL_1_FUSSGAENGER_ROT, OUTPUT);
pinMode(AMPEL_1_FUSSGAENGER_GRUEN, OUTPUT);
// BUTTON
pinMode(AMPEL_1_KNOPF, INPUT_PULLUP);
}

The traffic light loop: switching the phases

Here we begin by initializing the traffic lights and turning off all the LEDs except the red pedestrian light and the green traffic light. These need to be switched on.

Then we wait 5 seconds and switch the traffic light from green to yellow to signal that it will soon turn red. Five seconds later, the light changes from yellow to red. At the same time, the pedestrian light switches from red to green. We wait another 5 seconds. You can adjust this time, for example, to give pedestrians more time. Then we switch on the yellow light to signal to drivers that they will soon be able to go. We also switch the pedestrian light from green to red. After another 5 seconds, drivers can go again.

Of course, the times used are made up and have nothing to do with reality. Find out how long each traffic light phase lasts and program your traffic lights with realistic values!

If you have already placed all the traffic lights at the intersection, you may have noticed that additional traffic lights are lit. Pins 20 and 21 carry a voltage of about 3.3 V by default and are normally intended for signal transmission. Setting these pins to LOW prevents random signals that could, for example, cause the pedestrian light on traffic light 3 to light up unintentionally.

The loop of a single traffic light
void loop()
{
// Set every LED to off except AMPEL_1_FUSSGAENGER_ROT
// and AMPEL_1_GRUEN. These should be on.
digitalWrite(AMPEL_1_GRUEN , HIGH);
digitalWrite(AMPEL_1_FUSSGAENGER_ROT, HIGH);
digitalWrite(AMPEL_1_GELB, LOW);
digitalWrite(AMPEL_1_ROT, LOW);
digitalWrite(AMPEL_1_FUSSGAENGER_GRUEN, LOW);
// wait
delay(5000);
// Switch from green to yellow.
digitalWrite(AMPEL_1_GRUEN , LOW);
digitalWrite(AMPEL_1_GELB, HIGH);
// wait
delay(5000);
// Switch from yellow to red and change the red pedestrian
// LED to the green pedestrian LED.
digitalWrite(AMPEL_1_GELB, LOW);
digitalWrite(AMPEL_1_ROT, HIGH);
digitalWrite(AMPEL_1_FUSSGAENGER_ROT, LOW);
digitalWrite(AMPEL_1_FUSSGAENGER_GRUEN, HIGH);
// wait
delay(5000);
// Activate red and switch from pedestrian green back to red.
digitalWrite(AMPEL_1_GELB, HIGH);
digitalWrite(AMPEL_1_FUSSGAENGER_ROT, HIGH);
digitalWrite(AMPEL_1_FUSSGAENGER_GRUEN, LOW);
delay(5000);
}

Control multiple traffic lights simultaneously

Here is a more specific example that uses 4 traffic lights. When a button is pressed, the pedestrian lights should switch to green after a short delay.

To keep the sketch shorter, the following example uses structures, known as “structs.” An object is created from this structure for each traffic light. The basics of arrays and structures are not covered here. This is just one of many ways to compress a sketch.

We start again with a red light for all pedestrians. One direction of traffic has a green light, while the crossing direction has a red light. Then we check whether one of the buttons has been pressed. If a pedestrian presses a button, the lights for all traffic lanes slowly switch to red. All pedestrians then get a green signal. After a certain amount of time, the pedestrians get a red light again, and vehicles traveling in one direction get a green light.

Overview: Position of the four traffic lights at the intersection
Step 1: Definition of the "Traffic Light" structure
// Schritt 1: Definition der Struktur "Ampel"
struct Ampel
{
int Rot; // Pin für Auto-Rot
int Gelb; // Pin für Auto-Gelb
int Gruen; // Pin für Auto-Grün
int pedestrain_Rot; // Pin für Fußgänger-Rot
int pedestrain_Gruen; // Pin für Fußgänger-Grün
int pedestrain_Knopf; // Pin für Fußgänger-Button
};
Step 2: Set up traffic lights for the four directions
// Schritt 2: Initialisierung von Ampeln für verschiedene Richtungen
Ampel Seite_1_geradeaus = {6, 5, 4, 8, 9, 7};
Ampel Seite_4_geradeaus = {36, 35, 34, 38, 39, 37};
Ampel Seite_2_geradeaus = {18, 17, 16, 20, 21, 19};
Ampel Seite_3_geradeaus = {24, 23, 22, 26, 27, 25};
The complete sketch for four traffic lights
#include <Arduino.h>
// Step 1: Define the "Ampel" structure
struct Ampel
{
    int Rot;              // Pin for car red
    int Gelb;             // Pin for car yellow
    int Gruen;            // Pin for car green
    int pedestrain_Rot;   // Pin for pedestrian red
    int pedestrain_Gruen; // Pin for pedestrian green
    int pedestrain_Knopf; // Pin for pedestrian button
};
// Step 2: Initialize traffic lights for different directions
Ampel AMPEL_1 = {6, 5, 4, 8, 9, 7};
Ampel AMPEL_2 = {18, 17, 16, 20, 21, 19};
Ampel AMPEL_3 = {24, 23, 22, 26, 27, 25};
Ampel AMPEL_4 = {36, 35, 34, 38, 39, 37};
// Step 3: Initialize the pins in setup
void setup()
{
    Serial.begin(9600);
    // Traffic light 1
    pinMode(AMPEL_1.Rot, OUTPUT);
    pinMode(AMPEL_1.Gelb, OUTPUT);
    pinMode(AMPEL_1.Gruen, OUTPUT);
    pinMode(AMPEL_1.pedestrain_Rot, OUTPUT);
    pinMode(AMPEL_1.pedestrain_Gruen, OUTPUT);
    pinMode(AMPEL_1.pedestrain_Knopf, INPUT_PULLUP);
    // Traffic light 2
    pinMode(AMPEL_2.Rot, OUTPUT);
    pinMode(AMPEL_2.Gelb, OUTPUT);
    pinMode(AMPEL_2.Gruen, OUTPUT);
    pinMode(AMPEL_2.pedestrain_Rot, OUTPUT);
    pinMode(AMPEL_2.pedestrain_Gruen, OUTPUT);
    pinMode(AMPEL_2.pedestrain_Knopf, INPUT_PULLUP);
    // Traffic light 2
    pinMode(AMPEL_3.Rot, OUTPUT);
    pinMode(AMPEL_3.Gelb, OUTPUT);
    pinMode(AMPEL_3.Gruen, OUTPUT);
    pinMode(AMPEL_3.pedestrain_Rot, OUTPUT);
    pinMode(AMPEL_3.pedestrain_Gruen, OUTPUT);
    pinMode(AMPEL_3.pedestrain_Knopf, INPUT_PULLUP);
    // Traffic light 2
    pinMode(AMPEL_4.Rot, OUTPUT);
    pinMode(AMPEL_4.Gelb, OUTPUT);
    pinMode(AMPEL_4.Gruen, OUTPUT);
    pinMode(AMPEL_4.pedestrain_Rot, OUTPUT);
    pinMode(AMPEL_4.pedestrain_Gruen, OUTPUT);
    pinMode(AMPEL_4.pedestrain_Knopf, INPUT_PULLUP);
}
// Step 5: Main traffic light control and pedestrian crossing detection
void loop()
{
    // Set straight-ahead traffic lights to green
    digitalWrite(AMPEL_1.Gruen, HIGH);
    digitalWrite(AMPEL_3.Gruen, HIGH);
    // Set the other straight-ahead traffic lights to red
    digitalWrite(AMPEL_1.Rot, LOW);
    digitalWrite(AMPEL_3.Rot, LOW);
    digitalWrite(AMPEL_1.Gelb, LOW);
    digitalWrite(AMPEL_3.Gelb, LOW);
    // Set pedestrian lights to red
    digitalWrite(AMPEL_4.pedestrain_Rot, HIGH);
    digitalWrite(AMPEL_1.pedestrain_Rot, HIGH);
    digitalWrite(AMPEL_2.pedestrain_Rot, HIGH);
    digitalWrite(AMPEL_3.pedestrain_Rot, HIGH);
    digitalWrite(AMPEL_4.pedestrain_Gruen, LOW);
    digitalWrite(AMPEL_1.pedestrain_Gruen, LOW);
    digitalWrite(AMPEL_2.pedestrain_Gruen, LOW);
    digitalWrite(AMPEL_3.pedestrain_Gruen, LOW);
    // Check whether a pedestrian button has been pressed
    if (digitalRead(AMPEL_4.pedestrain_Knopf) == LOW ||
        digitalRead(AMPEL_1.pedestrain_Knopf) == LOW ||
        digitalRead(AMPEL_2.pedestrain_Knopf) == LOW ||
        digitalRead(AMPEL_3.pedestrain_Knopf) == LOW)
    {
        // Wait 2 seconds
        delay(2000);
        // Switch the straight-ahead traffic lights to yellow, then red
        digitalWrite(AMPEL_1.Gruen, LOW);
        digitalWrite(AMPEL_3.Gruen, LOW);
        digitalWrite(AMPEL_1.Gelb, HIGH);
        digitalWrite(AMPEL_3.Gelb, HIGH);
        // Wait 1 second
        delay(1000);
        digitalWrite(AMPEL_1.Gelb, LOW);
        digitalWrite(AMPEL_3.Gelb, LOW);
        digitalWrite(AMPEL_1.Rot, HIGH);
        digitalWrite(AMPEL_3.Rot, HIGH);
        // Wait 2 seconds
        delay(2000);
        // Set pedestrian lights to green
        digitalWrite(AMPEL_4.pedestrain_Gruen, HIGH);
        digitalWrite(AMPEL_1.pedestrain_Gruen, HIGH);
        digitalWrite(AMPEL_2.pedestrain_Gruen, HIGH);
        digitalWrite(AMPEL_3.pedestrain_Gruen, HIGH);
        digitalWrite(AMPEL_4.pedestrain_Rot, LOW);
        digitalWrite(AMPEL_1.pedestrain_Rot, LOW);
        digitalWrite(AMPEL_2.pedestrain_Rot, LOW);
        digitalWrite(AMPEL_3.pedestrain_Rot, LOW);
        // Wait 5 seconds
        delay(5000);
        // Set pedestrian lights to red
        digitalWrite(AMPEL_4.pedestrain_Gruen, LOW);
        digitalWrite(AMPEL_1.pedestrain_Gruen, LOW);
        digitalWrite(AMPEL_2.pedestrain_Gruen, LOW);
        digitalWrite(AMPEL_3.pedestrain_Gruen, LOW);
        digitalWrite(AMPEL_4.pedestrain_Rot, HIGH);
        digitalWrite(AMPEL_1.pedestrain_Rot, HIGH);
        digitalWrite(AMPEL_2.pedestrain_Rot, HIGH);
        digitalWrite(AMPEL_3.pedestrain_Rot, HIGH);
        // Wait 2 seconds
        delay(2000);
        // Switch the straight-ahead traffic lights to yellow
        digitalWrite(AMPEL_1.Gelb, HIGH);
        digitalWrite(AMPEL_3.Gelb, HIGH);
        // Turn off the red lights
        digitalWrite(AMPEL_1.Rot, HIGH);
        digitalWrite(AMPEL_3.Rot, HIGH);
        delay(1000);
    }
}
Rate the instructions

Comments

Ask a question or share an experience

Contact us if something doesn’t work. Please include your board and the error message.

We review every comment before publication. Your email address remains with us.