Hello Folks,
I am attempting to blink a LED in the following pattern:
On for 1 second
Off for 1 second
On for 2 seconds
Off for 1 second
On for 1 second etc.
I am using the following code to blink an LED off and on, this is working fine but I am lost on how to vary the on time every other time it turns on. I would love a clue on what type of code to try.
Many thanks for any ideas.
Code:
void Update()
{
// check to see if it's time to change the state of the LED
unsigned long currentMillis = millis();
if((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
{
ledState = LOW; // Turn it off
previousMillis = currentMillis; // Remember the time
digitalWrite(ledPin, ledState); // Update the actual LED
}
else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
{
ledState = HIGH; // turn it on
previousMillis = currentMillis; // Remember the time
digitalWrite(ledPin, ledState); // Update the actual LED
}
One way to do this is to put your on times and your off times into arrays.
const int patternLength = 3;
const unsigned long onTimeMs[patternLength] = {1000, 2000, 1000, 3000};
const unsigned long offTimeMs[patternLength] = {1000, 1000, 2000, 1000};
int patternIndex = 0;
Each time you do the loop, use onTimeMs[patternIndex] and offTimeMs[patternIndex] as the on and off time, and add one to the pattern index. If the pattern index is >= patternLength after adding one, then reset it back to zero.
The example code above will blink like -**---***- continuously.
Alternatively, you can use a single array with all the times in it and keep track of whether you need to be on or off as you step through it. This will do something interesting if the array has an odd length.