I'm trying to write code to get 3 LEDs flashing independently, each with a different ON and OFF period.
For example:
LED1: ON for 25 ms, OFF for 500 ms
LED2: ON for 50 ms, OFF for 800 ms
LED3: ON fo 100 ms, OFF for 300 ms
So far I have set up the hardware: 3 LEDs on digital pins 6, 7 and 8 using my Arduino UNO board and a breadboard.
Code-wise I understand that I can't use the "delay" function because it causes the whole system to delay i.e. causes 'blocking'. At the moment I'm using the millis() function. My problem is that at the moment my code causes LED1 to turn ON for 25 ms and off for 25 ms, LED2 turns ON for 50 ms and off for 50 ms etc. So I need to somehow alter the OFF period independently.
In summary: I need a new approach or an alteration to my code to be able to independently change the ON and OFF periods for each of my LEDs independently.
Here is my code so far:
Code: Select all
// Which pins are connected to which LED
const byte LED1 = 6;
const byte LED2 = 7;
const byte LED3 = 8;
// Assigning delays.
const unsigned long LED1_interval = 25;
const unsigned long LED2_interval = 50;
const unsigned long LED3_interval = 100;
// Declaring the variables holding the timer values for each LED.
unsigned long LED1_timer;
unsigned long LED2_timer;
unsigned long LED3_timer;
// Setting 3 digital pins as output pins and resetting timer
void setup ()
{
pinMode (LED1, OUTPUT);
pinMode (LED2, OUTPUT);
pinMode (LED3, OUTPUT);
LED1_timer = millis ();
LED2_timer = millis ();
LED3_timer = millis ();
} // end of setup
//LED1 loop that turns it ON if it is OFF and vice versa
void toggle_LED1 ()
{
if (digitalRead (LED1) == LOW)
digitalWrite (LED1, HIGH);
else
digitalWrite (LED1, LOW);
// remember when we toggled it
LED1_timer = millis ();
} // end of toggleLED_1
//LED2 loop
void toggle_LED2 ()
{
if (digitalRead (LED2) == LOW)
digitalWrite (LED2, HIGH);
else
digitalWrite (LED2, LOW);
// remember when we toggled it
LED2_timer = millis ();
} // end of toggle_LED2
//LED 3 loop
void toggle_LED3 ()
{
if (digitalRead (LED3) == LOW)
digitalWrite (LED3, HIGH);
else
digitalWrite (LED3, LOW);
// remember when we toggled it
LED3_timer = millis ();
} // end of toggle_LED3
void loop ()
{
// Handling the blink of LED1.
if ( (millis () - LED1_timer) >= LED1_interval)
toggle_LED1 ();
// Handling the blink of LED2.
if ( (millis () - LED2_timer) >= LED2_interval)
toggle_LED2 ();
// Handling the blink of LED3.
if ( (millis () - LED3_timer) >= LED3_interval)
toggle_LED3 ();
/* Other code that needs to execute goes here.
It will be called many thousand times per second because the above code
does not wait for the LED blink interval to finish. */
} // end of loop
Any help would be greatly appreciated because I'm very new to this!
Thanks!