// Forum: https://forum.arduino.cc/t/flash-led-using-millis-while-relay-is-activated/1289454
// This Wokwi project: https://wokwi.com/projects/405568161981442049
const int ledPin = 1; // 'int' or 'byte'
const int relayPin = 0; // 'int' or 'byte'
const unsigned long FANONDURATION = 5000UL;
const unsigned long FANOFFDURATION = 15000UL;
const unsigned long LEDONDURATION = 150;
const unsigned long LEDOFFDURATION = 250;
unsigned long previousMillisFan;
unsigned long fanInterval = FANOFFDURATION;
unsigned long previousMillisLed;
unsigned long ledInterval = LEDONDURATION;
bool ledOn = false;
bool fanOn = false;
void setup(void)
{
pinMode(ledPin, OUTPUT); // set output and low
pinMode(relayPin, OUTPUT); // set output and low
digitalWrite(ledPin, LOW); // not necessary
digitalWrite(relayPin, LOW); // not necessary
}
void loop()
{
unsigned long currentMillis = millis();
// A millis timer for the fan.
// With different on and off times.
if(currentMillis - previousMillisFan >= fanInterval)
{
previousMillisFan = currentMillis;
if(!fanOn)
{
digitalWrite(relayPin, HIGH);
fanInterval = FANONDURATION;
fanOn = true;
}
else
{
digitalWrite(relayPin, LOW);
fanInterval = FANOFFDURATION;
fanOn = false;
}
}
// A millis timer for the led.
// Flash led when the fan is on.
if(fanOn)
{
if(currentMillis - previousMillisLed >= ledInterval)
{
previousMillisLed = currentMillis;
if(!ledOn)
{
digitalWrite(ledPin, HIGH);
ledInterval = LEDONDURATION;
ledOn = true;
}
else
{
digitalWrite(ledPin, LOW);
ledInterval = LEDOFFDURATION;
ledOn = false;
}
}
}
}