// Sketch for testing switch between loops for LED patterns v3 (remembers mode state)
unsigned long lastMilli = 0;
int intervalDelay = 500;
byte mode = 1;
unsigned long lastCheck = 0;
int ledPin = 9; // the number of the LED pin
int pinSwitch = 2; // pin to button to GND (use internal pullup)
int ledState = LOW; // ledState used to set the LED
unsigned long M1InitOnTime = 500; // milliseconds of on-time
unsigned long M1OnIncrement = 100; // increment on time in milliseconds
unsigned long M1OnTimeMax = 1000 - M1OnIncrement; // Mode 1 max on time before cycling back to start
unsigned long M2InitOnTime = 1000; // milliseconds of on-time
unsigned long M2OnIncrement = 1000; // increment on time in milliseconds
unsigned long M2OnTimeMax = 5000 - M2OnIncrement; // Mode 2 max on time before cycling back to start
unsigned long M1OnTimeCurr = M1InitOnTime; // initialize variable for Mode 1 current On Time incrementing
unsigned long M2OnTimeCurr = M2InitOnTime; // initialize variable for Mode 2 current On Time incrementing
unsigned long currentMillis;
byte butLst; // last button state
// -----------------------------------------------------------------------------
void loop ()
{
currentMillis = millis ();
byte but = digitalRead(pinSwitch);
if (butLst != but) {
butLst = but;
delay (20); // debounce
if (LOW == but)
mode = !mode;
}
if (mode)
mode1 ();
else
mode2 ();
}
// -----------------------------------------------------------------------------
void mode1 ()
{
if (currentMillis - lastMilli >= M1OnTimeCurr) {
lastMilli = currentMillis; // Remember the time
if (ledState == HIGH) {
ledState = LOW; // Turn it off
// increment on time up to Max
if ((M1OnTimeCurr <= M1OnTimeMax))
M1OnTimeCurr = M1OnTimeCurr + M1OnIncrement;
else
M1OnTimeCurr = M1InitOnTime;
}
else
ledState = HIGH; // turn it on
digitalWrite (ledPin, ledState); // Update the actual LED
Serial.print ("mode1: ");
Serial.println (M1OnTimeCurr);
}
}
// -----------------------------------------------------------------------------
void mode2 ()
{
if (currentMillis - lastMilli >= M2OnTimeCurr) {
lastMilli = currentMillis; // Remember the time
if (ledState == HIGH) {
ledState = LOW; // Turn it off
// increment on time up to Max
if ((M2OnTimeCurr <= M2OnTimeMax))
M2OnTimeCurr = M2OnTimeCurr + M2OnIncrement;
else
M2OnTimeCurr = M2InitOnTime;
}
else
ledState = HIGH; // turn it on
digitalWrite (ledPin, ledState); // Update the actual LED
Serial.print ("mode2: ");
Serial.println (M2OnTimeCurr);
}
}
// -----------------------------------------------------------------------------
void setup ()
{
pinMode (ledPin, OUTPUT);
pinMode (pinSwitch, INPUT_PULLUP);
butLst = digitalRead (pinSwitch);
Serial.begin (9600);
}