// CONSTANTS
const int redLEDpin = 8; // Red LED
const int blueLEDpin = 7; // Blue LED
const int redLED_Interval = 500; // Experimented with wide range
const int blueLED_Interval = 800;
const int blinkDuration = 500; // How long both LEDs are on
// VARIABLES
byte redLED_State = LOW;
byte blueLED_State = LOW;
unsigned long currentMillis = 0; // Time at start of each iteration of loop()
unsigned long previousredLED_Millis = 0;
unsigned long previousblueLED_Millis = 0;
//========================================
void setup()
{
Serial.begin(115200);
Serial.println("SeveralThings-BlinkRedBlue-2");
pinMode(redLEDpin, OUTPUT);
pinMode(blueLEDpin, OUTPUT);
}
//========================================
void loop()
// As recommended, using FUNCTIONS, even for relatively trival tasks
{
currentMillis = millis(); // Latest value of millis() at start of this iteration
updateredLED_State();
updateblueLED_State();
switchLeds();
}
//========================================
// FUNCTIONS
void updateredLED_State()
{
// If red LED is off, wait for specified interval to expire before turning it on
if (redLED_State == LOW)
{
if (currentMillis - previousredLED_Millis >= redLED_Interval)
{
// Red LED OFf interval has expired, so change the state to HIGH
redLED_State = HIGH;
// Save the time of that state change
previousredLED_Millis += redLED_Interval;
// NOTE: The previous line could alternatively be
// previousredLED_Millis = currentMillis
// which is the style used in the BlinkWithoutDelay sketch
// Adding on the interval ensures that succesive periods are identical
// Usually? Always? I need to study that more to fully grasp this.
}
}
// Else it must be on, so need to wait before turning it off
else
{
if (currentMillis - previousredLED_Millis >= blinkDuration)
{
redLED_State = LOW;
previousredLED_Millis += blinkDuration; // Using this more accurate option
}
}
}
//========================================
void updateblueLED_State()
{
if (blueLED_State == LOW)
{
if (currentMillis - previousblueLED_Millis >= blueLED_Interval)
{
blueLED_State = HIGH;
previousblueLED_Millis += blueLED_Interval;
}
}
else
{
if (currentMillis - previousblueLED_Millis >= blinkDuration)
{
blueLED_State = LOW;
previousblueLED_Millis += blinkDuration;
}
}
}
//========================================
void switchLeds()
{
// Simply switches the LEDs on and off
digitalWrite(redLEDpin, redLED_State);
digitalWrite(blueLEDpin, blueLED_State);
}