1 arduino for 4 individual tasks

Hello,

I have been making a miniature city, and now i want to add traffic lights on 4 intersections.
These traffic lights need to work all independent from each other (so every intersection has its own light control so not every intersection shows red at the same moment for example)

is there a way to do this? like creating 4 loops maybe ?
I'm pretty new so i ask first before i buy the components.

Best regards

Hi @only4games .

Yes there is.
Write independent routines for each traffic light and don't use delay to control the times.
Use the millis() method.

RV mineirin

Yes you can do this.

You need to decide on how many controls and inputs are needed (then add a few more for expansion).

An Arduino Mega might be a good place to start.

The basic principle is to have one big loop and to execute the functions in a sequential way
by using a technique that is called state-machine. Traffic-lights are a very typical application for state-machines

So as a rough picture the functionality of your code looks like this

void loop() {
  TrafficLights_One();
  TrafficLights_Two();
  TrafficLights_Three();
  TrafficLights_Four();

where each function gets called again and again and all the steps of switching light from red to yellow, to green etc. is done by the program-logic of the state-machine

This means your code jumps in and out of the functions all the time
and something similar to if-conditions control which part of the code

  • switch to red
  • switch to yellow
  • switch to green

etc. gets executed
best regards Stefan

1 Like

It's a situation where you might consider writing a class or two. An intersection class perhaps and a TrafficLight class.

If you're new to C++, though the earlier suggestions would be a better place to start.

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