Simple Traffic Light works but suddendly goes crazy

Believe me, I have read a lot of forums and checked several YouTube videos but for something as simple as a Traffic Light, I cannot understand the problem I’m facing. In my town there are no real electronic engineers, they only sell supplies but have no answers so I have built my own Arduino and got it to work. The problem is that my code seems to have a problem with the timing of the delays, plus another issue I don’t quite understand with the power supply. I almost have it perfected but this is truly driving me crazy, because once I get it to work, after some minutes, it goes nuts.

When I upload my code it works like a charm, just as intended. But when I change it to a wall outlet using the converter power supply (with a 5volts converter) it never works, only with my USB. I’ve read that the 5V pin is for the USB and the VIN pin is for the converter power supply, am I right?

But then the code gets stuck even when it’s connected to the computer with a usb connector. So I am guessing that my timing with the milliseconds is off, or something, but I simply can’t understand how to flush/reset the times for it to not get all messed up after 10 minutes of work. This is a simple code, and I’ve read many threads but I truly cant’ understand. Bear in mind that I am no engineer, and I had to figure it all out by myself, so I’m beggin for some guidance for these last steps.

Can you please tell me what can I add for it to not get buggy after some minutes? thanks a lot!!!

A link for a video with the problem been shown by minute 23:35

This is my code:

// variables where in total there are 58,200 milliseconds being assigned
int GREEN = 4;
int YELLOW = 3;
int RED = 2;
int DELAY_GREEN = 21000;
int DELAY_YELLOW = 5000;
int DELAY_RED = 21000;
int DELAY_GREENALERTOFF = 700;
int DELAY_GREENALERTON = 700;
int DELAY_REDALERTOFF = 700;
int DELAY_REDALERTON = 700;
// basic functions
void setup() 
{
pinMode(GREEN, OUTPUT);
pinMode(YELLOW, OUTPUT);
pinMode(RED, OUTPUT);
}

void loop()
// put your main code here, to run repeatedly:
// AND FOR SOME REASON THE OUTPUT IS OPPOSITE in the lights

{
green_light();
delay(DELAY_GREEN);
green_alertOFF();
delay(DELAY_GREENALERTOFF);
green_alertON();
delay(DELAY_GREENALERTON);
green_alertOFF();
delay(DELAY_GREENALERTOFF);
green_alertON();
delay(DELAY_GREENALERTON);
green_alertOFF();
delay(DELAY_GREENALERTOFF);
green_alertON();
delay(DELAY_GREENALERTON);
green_alertOFF();
delay(DELAY_GREENALERTOFF);
green_alertON();
delay(DELAY_GREENALERTON);
green_alertOFF();
delay(DELAY_GREENALERTOFF);
yellow_light();
delay(DELAY_YELLOW);
red_light();
delay(DELAY_RED);
red_alertOFF();
delay(DELAY_REDALERTOFF);
red_alertON();
delay(DELAY_REDALERTON);
red_alertOFF();
delay(DELAY_REDALERTOFF);
red_alertON();
delay(DELAY_REDALERTON);
red_alertOFF();
delay(DELAY_REDALERTOFF);
red_alertON();
delay(DELAY_REDALERTON);
red_alertOFF();
delay(DELAY_REDALERTOFF);
}

void green_light()
{
digitalWrite(GREEN, LOW);
digitalWrite(YELLOW, HIGH);
digitalWrite(RED, HIGH);
}

void green_alertOFF()
{
digitalWrite(GREEN, HIGH);
digitalWrite(YELLOW, HIGH);
digitalWrite(RED, HIGH);
}

void green_alertON()
{
digitalWrite(GREEN, LOW);
digitalWrite(YELLOW, HIGH);
digitalWrite(RED, HIGH);
}

void yellow_light()
{
digitalWrite(GREEN, HIGH);
digitalWrite(YELLOW, LOW);
digitalWrite(RED, HIGH);
}

void red_light()
{
digitalWrite(GREEN, HIGH);
digitalWrite(YELLOW, HIGH);
digitalWrite(RED, LOW);
}

void red_alertOFF()
{
digitalWrite(GREEN, HIGH);
digitalWrite(YELLOW, HIGH);
digitalWrite(RED, HIGH);
}

void red_alertON()
{
digitalWrite(GREEN, HIGH);
digitalWrite(YELLOW, HIGH);
digitalWrite(RED, LOW);
}

A few new words.

  • State Machine
  • Functions
    Also read up on -
    HOW to use this forum.

what he said, with links:

Read "How To Use This Forum"

This is what happens when you do not

Using millis() for timing. A beginners guide

traffic lights at the Project Hub

I've read that the 5V pin is for the USB and the VIN pin is for the converter power supply, am I right?

raw power socket > V IN pin > onboard regulator > 5 V pin

put a 6 - 9 V power source in on V IN if you don't want to use the DC socket. put regulated power in on the 5 V pin. if you use the 5 V pin to power more than a few modules, you are using the Arduino as a fuse.

lastchancename:
A few new words.

  • State Machine
  • Functions
    Also read up on -
    HOW to use this forum.

I know that for an engineer I might sound stupid, but I believe this problem should be extremely easy to solve. I've looked for the term "State Machine" which you refer me to and it seems you want me to study the whole basic concepts of electronics. And I get it, people should be asking much more complicated stuff in here, therefore your second suggestion for revising how to use this forum. Believe me, I wanted to solve it by myself and I've gone far, but I have encountered terms like "fushing", "rollover" and others that have confused me greatly. I just want the traffic light as a decoration for my bar. I am no engineer.

My (real size) traffic light turns on already, it does the proper blinking switching from red to green, then yellow and back to red, with the assigned delays in my poor code, if you want me to be honest. BUT, I thought that in these forums I could get some easy, fast advice for a simple code like mine. It's just a Traffic Light code, something any electronics engineer should have studied at their early stage of their universities, right? So after many try outs, I finally opted to try to ask in here for a professional guidance or even better, THE ONE OR TWO LINES OF CODE THAT I AM MISSING. Your guidance is as general as an index of a book, so it doesn't help at all. Thanks for reading me though, I just hope I didn't make you angry. I'm just desperate for something as simple as a TRAFFIC LIGHT CODE.

Ok, to be fair I was hoping to lead you on a path to elegance, reliability and scalability.
You can go the way you are, but likely you’ll have to rewrite a fair chunk for the simplest change.

State machines have nothing to do with electronics concepts, so you may have landed on some other reference.
They are used to create logical, easily managed sequencing of processes and timing control.
A traffic light sequencer is almost textbook in state machine territory- once you have red/green/yellow working, you may want to add a cross street, pedestrian buttons or lane arrows.
A state machine could achieve this with almost zero code changes than adding the extra inputs & outputs - and states of course.

Ok, thanks, it seems I will have to study the whole concept of milliseconds.
I also checked the suggestions for posting, and I did not paste my code properly I'm sorry, but anyhow it seems I have to solve it by myself. Thanks for checking out my post I guess.

Ok, now we’ve got that far...
We tried to point how you can start out better, now try implementing those ideas - it does mean work,
Then post your effort, and we’ll help you forward.

Example-
If you want to build a car, and show us a scooter as your best effort, we’ll suggest extra wheels and an engine. Then we can all move ahead together !

lastchancename:
Ok, to be fair I was hoping to lead you on a path to elegance, reliability and scalability.
You can go the way you are, but likely you’ll have to rewrite a fair chunk for the simplest change.

State machines have nothing to do with electronics concepts, so you may have landed on some other reference.
They are used to create logical, easily managed sequencing of processes and timing control.
A traffic light sequencer is almost textbook in state machine territory- once you have red/green/yellow working, you may want to add a cross street, per buttons or lane arrows.
A state machine could achieve this with almost zero code changed than adding the extra inputs & outputs - and states of course.

I forgot to mention that it is only one Traffic Light, not two. So it should be as simple as blinking leds, but it still gets stuck after a few minutes. I will do my homework, like I said, I already did the hard part (building the Arduino into the traffic light) and it works, just not perfectly. Therefore I know I’m very close. I can do it, I just got desperate and thought it was going to be a rewarding experience to ask in here, which was not.
Thanks for your longer reply though, it does explain more to me.

Thanks.

Thanks a lot for that last link. And also for the guidance with the voltage.
I'll try those out and hopefully fix my 1 traffic light problem.

Thanks!

Can you post a drawing or (preferably) a schematic of how you have the arduino and the traffic light connected? There really isn’t anything in your code that should cause any problems, so it is much more likely that there is a problem elsewhere.

Ok, let’s start again...
Sorry you didn’t get the reception you hoped for... a bit like programming!

// variables where in total there are 58,200 milliseconds being assigned
int GREEN = 4;
int YELLOW = 3;
int RED = 2;
int DELAY_GREEN = 21000;
int DELAY_YELLOW = 5000;
int DELAY_RED = 21000;
int DELAY_GREENALERTOFF = 700;
int DELAY_GREENALERTON = 700;
int DELAY_REDALERTOFF = 700;
int DELAY_REDALERTON = 700;
// basic functions
void setup() 
{
  pinMode(GREEN, OUTPUT);
  pinMode(YELLOW, OUTPUT);
  pinMode(RED, OUTPUT);
}

void loop()
  // put your main code here, to run repeatedly:
  // AND FOR SOME REASON THE OUTPUT IS OPPOSITE in the lights

{
  green_light();
  delay(DELAY_GREEN);
  green_alertOFF();
  delay(DELAY_GREENALERTOFF);
  green_alertON();
  delay(DELAY_GREENALERTON);
  green_alertOFF();
  delay(DELAY_GREENALERTOFF);
  green_alertON();
  delay(DELAY_GREENALERTON);
  green_alertOFF();
  delay(DELAY_GREENALERTOFF);
  green_alertON();
  delay(DELAY_GREENALERTON);
  green_alertOFF();
  delay(DELAY_GREENALERTOFF);
  green_alertON();
  delay(DELAY_GREENALERTON);
  green_alertOFF();
  delay(DELAY_GREENALERTOFF);
  yellow_light();
  delay(DELAY_YELLOW);
  red_light();
  delay(DELAY_RED);
  red_alertOFF();
  delay(DELAY_REDALERTOFF);
  red_alertON();
  delay(DELAY_REDALERTON);
  red_alertOFF();
  delay(DELAY_REDALERTOFF);
  red_alertON();
  delay(DELAY_REDALERTON);
  red_alertOFF();
  delay(DELAY_REDALERTOFF);
  red_alertON();
  delay(DELAY_REDALERTON);
  red_alertOFF();
  delay(DELAY_REDALERTOFF);
}

void green_light()
{
  digitalWrite(GREEN, LOW);
  digitalWrite(YELLOW, HIGH);
  digitalWrite(RED, HIGH);
}

void green_alertOFF()
{
  digitalWrite(GREEN, HIGH);
  digitalWrite(YELLOW, HIGH);
  digitalWrite(RED, HIGH);
}

void green_alertON()
{
  digitalWrite(GREEN, LOW);
  digitalWrite(YELLOW, HIGH);
  digitalWrite(RED, HIGH);
}

void yellow_light()
{
  digitalWrite(GREEN, HIGH);
  digitalWrite(YELLOW, LOW);
  digitalWrite(RED, HIGH);
}

void red_light()
{
  digitalWrite(GREEN, HIGH);
  digitalWrite(YELLOW, HIGH);
  digitalWrite(RED, LOW);
}

void red_alertOFF()
{
  digitalWrite(GREEN, HIGH);
  digitalWrite(YELLOW, HIGH);
  digitalWrite(RED, HIGH);
}

void red_alertON()
{
  digitalWrite(GREEN, HIGH);
  digitalWrite(YELLOW, HIGH);
  digitalWrite(RED, LOW);
}

Someone else may like to chip in while I pull this up on my PC later.

david_2018:
Can you post a drawing or (preferably) a schematic of how you have the arduino and the traffic light connected? There really isn't anything in your code that should cause any problems, so it is much more likely that there is a problem elsewhere.

I will get that for you, thanks a lot for giving me a chance.
I know it might also be a problem with the power supply, since it works fine for a while when connected through the usb hub to my laptop (after like ten minutes it starts getting irregular to fully stuck on an only red light on), but when I switch it to a regulated 5V power supply to an outlet, it never works properly having only the red light on. I already read that it is better to use a higher voltage like 7V (since it can be from 7 to 12v) for it to properly regulate it, and that might be my problem. But I have to get another converter. Anyhow, the code always gets stuck after some blinks, with the green light blinking irregularly (making rushed blinks or missing the last two blinks).

I will get a drawing of my connections and a video of the misbehaving traffic light. Again, is only one Traffic light, not two, and that's why it was driving me nuts. I will get back with those as soon as I can.

Thanks again.

// AND FOR SOME REASON THE OUTPUT IS OPPOSITE in the lights

Sounds like you have the LEDs connected from 5V to output pin, that is backward from the normal way (LED cathode to GND, anode to current limit resistor, other end of resistor to output pin) but will work if you reverse the output logic. Change HIGHs to LOWs and vice versa.
Do you have the proper current limiting resistors in series with the LEDs? Are you powering the LEDs directly from the Arduino output pins? Do you know how much current the LEDs require? What is the output voltage and current rating of your converter and where are you connecting it to on the Arduino?

OK, this wasn’t compiled, but should do for now—
This is only ONE WAY of approaching the problem, I can think of better ways - but give it a shot.
Any errrors should be easy to locate of the compiler throws any.

/* This could be more elegant with use of functions()
 but the intent was to demonstrate use of arrays[] 
 Similarly, we should eliminate delay() completely with millis() timing.
*/
//---------------------------------------------------------------------
// output pins
byte GRN_led = 4;
byte YEL_led = 3;
byte RED_led = 2;

byte index; // used in for() loops
byte repeat; // used to repeat color loop sequences

//---------------------------------------------------------------------
// arrays to hold each color sequence and the associated delay period(mS)
// one color state[] member for each LED state in the sequence
// these correspond to tghe original colour_alert() functions
// each binary number represents bit positions of R/Y/G LED states

byte GRNstates[] = { b110, b111, b110 };
byte GRNdelay[] = { 21000, 700, 700 };

byte YELstates[] = { b101 };
byte YELdelay[] = { 5000 };

byte REDstates[] = { b011, b111, b011 };
byte REDdelay[] = { 21000, 700, 700 };

//---------------------------------------------------------------------
void setup() {
  pinMode(GREEN, OUTPUT);
  pinMode(YELLOW, OUTPUT);
  pinMode(RED, OUTPUT);
}
//---------------------------------------------------------------------

void loop() {
  // THE REASON THE OUTPUT IS OPPOSITE...
 // is because the LEDs are being driven active LOW (quite typical)
 // this may change when you add drivers and bigger LEDs
 // to invert - just drive the output bit in the opposite direction(!hint)

 // run through the GRN sequence - ** TWICE **
 for (repeat = 0; repeat < 2; repeat++) { 
 for (index = 0; index < sizeof(GRNstates)) {
 digitalWrite(GRN_led, (GRNstates[index] & b001) );  // <<--- invert this logic if ACTIVE HIGH
 delay(GRNdelay[index];
 }
 }
 // run through the YEL sequence - ** ONCE **
 for (index = 0; index < sizeof(YELstates)) {
 digitalWrite(YEL_led, (YELstates[index] & b010) );  // <<--- invert this logic if ACTIVE HIGH
 delay(YELdelay[index];
 }
 // run through the RED sequence - ** TWICE **
 for (repeat = 0; repeat < 2; repeat++) { 
 for (index = 0; index < sizeof(REDstates)) {
 digitalWrite(RED_led, (REDstates[index] & b100) );  // <<--- invert this logic if ACTIVE HIGH
 delay(REDdelay[index];
 }
 }
//---------------------------------------------------------------------

Sorry about the indenting - my editor doesnt play nice with the forum fixed spacing

david_2018:
Can you post a drawing or (preferably) a schematic of how you have the arduino and the traffic light connected? There really isn't anything in your code that should cause any problems, so it is much more likely that there is a problem elsewhere.

I already uploaded an image with the exact connections I made with the exact same components.
Also here is the link for the video showing the problem I'm having.

By the minute 23:35 the green light seems to skip a blink for some reason and makes it lose its rythm until the red light is the only one lit. I felt it did it sometimes sooner than that but never much later, therefore I thought it was created by the sum of periods I did assign in my code. Also, like I said before, when I connect it with a converter of 5V with the jack (which is my goal, instead of the USB) it never works, the yellow and green lights never turn on this way.

I will try the new suggestions I got while I was reproducing the error and recording it.
Hopefully you can see the image I made of the connection scheme. I'm using 3 relays.
The image is uploaded in my beginning post.

Thanks for your assistance, with so much help I believe it will be solved.
I will post back if I manage to make it work properly to let you all know.

Thanks.

JCA79B:
Sounds like you have the LEDs connected from 5V to output pin, that is backward from the normal way (LED cathode to GND, anode to current limit resistor, other end of resistor to output pin) but will work if you reverse the output logic. Change HIGHs to LOWs and vice versa.
Do you have the proper current limiting resistors in series with the LEDs? Are you powering the LEDs directly from the Arduino output pins? Do you know how much current the LEDs require? What is the output voltage and current rating of your converter and where are you connecting it to on the Arduino?

I have uploaded an image with the connections I have made to explain myself better in my beginning post.

1.- I am not using any extra resistors in series with the leds, since I'm using the relays to connect it to a real life size traffic light, powered up separately.

2.- I'm powering up the traffic light separately, the relays are only being connected as switches, as far as I understand.

3.- These are the specs for each led light:
Red : 10.1 VA / 120 Volts / 60 Hz / 10 W / 0.084 Inom.
Yellow : 22.2 VA / 120 Volts / 60 Hz / 22 W / 0.183 Inom.
Green : 12.1 VA / 120 Volts / 60 Hz / 12 W / 0.101 Inom.

4.- My converter has an output of 5volts and 2000mA connected with a jack to the arduino, at least that's my goal since it only works for some time when I connect it with the USB hub to my laptop.

For what it's worth, OP, I ran your code with normal leds at about 10mA and was still getting:

  • long green
  • 4 green blinks
  • orange
  • long red
  • 3 red blinks

... an hour later.

I had made a simple change to the code to count and timestamp each cycle, and serial monitor gave the following:

starting cycle number 60 at 3433 seconds
starting cycle number 61 at 3492 seconds
starting cycle number 62 at 3550 seconds
starting cycle number 63 at 3608 seconds
starting cycle number 64 at 3666 seconds

(I had also changed the highs and lows of the leds to lows and highs, leds wired from pin to ground.)

I have uploaded an image

Didn't see any image posted ?
FOUND IT - did you post that back afterwards? Not good form.
SHould always be posted in chronological order so the following posts make sense.

Here is that image -

The relays should not be powered off the same 5V supply as the arduino, that often leads to problems, and when you are powering the arduino through the barrel jack or Vin the voltage regulator on the arduino will be incapable of supplying the current needed by the relays.

If you can post a link to the specific relays you bought, someone can tell you specifically how to connect them.
Relay modules normally have a 2-pin or 3-pin connector with one pin labeled VCC and another labeled JD-VCC (or something similar). There is a jumper on the connector to connect VCC from the arduino to JD-VCC, remove the jumper and connect a separate power supply to JD-VCC and to GND.
The only connections between the relay module and arduino should be VCC and IN1 on the single relay board, and VCC, IN1, and IN2 on the 2-relay module, do not connect the GND from the relay modules to the arduino, it is not needed, and you want the relay power supply to be totally isolated from the arduino power supply.

Incidentally, it is quite normal for a LOW level to turn the relays ON, and a HIGH level to turn them OFF. That is know as an active-low input, and is the way a lot of the relay modules are made.

DEFINITELY - THE GND ON ALL DEVICES SHOULD BE CONNECTED IN THIS CIRCUIT !

The suggestions on the other pins and control are valid.