// https://forum.arduino.cc/t/struggling-with-millis-for-two-tasks/904391
// code copied and pasted from #4
// w/o MyHW defined (use OP's pins)
// Flash the blue LED for 500 ms every 10 seconds
// If the button has been pressed for at least 1 s, light the red LED for 5s
// (Not fussed what happens to the blue LED during that time, but ideally
// would prefer to use millis for that 5s, rather than delay)
// Report events in the serial monitor during testing
// (It's a simplified learning sketch. When I have it working I'll adapt for
// a more complex servo and motion sensor program.)
// Button via 10k to 5V;
// input to D6 goes low when pressed
// Triggers red LED when input to D6 from button has remained low for >= 1s
// Report timestamps for testing
// Constants
// #define MyHW
#ifdef MyHW
const byte triggerPin = A1;
const byte blueLEDPin = 13;
const byte redLEDPin = 12;
#else
const byte triggerPin = 6; // Low input from button to D6
const byte blueLEDPin = 7; // Blue LED flashes at 10s intervals
const byte redLEDPin = 8; // Large red LED, high for 5s when triggered
#endif
enum { Off = HIGH, On = LOW };
unsigned long triggerStart; // Time when D6 goes low
unsigned long blueMsec;
byte butState;
void setup ()
{
pinMode (triggerPin, INPUT_PULLUP); // D6
butState = digitalRead (triggerPin);
pinMode (blueLEDPin, OUTPUT); // D7
pinMode (redLEDPin, OUTPUT); // D8
digitalWrite (blueLEDPin, Off); // D7
digitalWrite (redLEDPin, Off); // D8
Serial.begin (9600);
Serial.println ("RegularBlinksPlusButtonTrigger");
Serial.println ("");
}
void loop ()
{
unsigned long currentMillis = millis (); // Get current time
byte but = digitalRead (triggerPin);
if (LOW == but) { // button being pressed
if (butState != but) {
butState = but;
triggerStart = currentMillis;
}
if ( (currentMillis - triggerStart) >= 700)
{
digitalWrite (redLEDPin, ! digitalRead (redLEDPin));
triggerStart = currentMillis;
}
}
if (currentMillis > blueMsec) {
if (Off == digitalRead (blueLEDPin))
blueMsec += 200;
else
blueMsec += 800;
digitalWrite (blueLEDPin, ! digitalRead (blueLEDPin));
}
}