Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- unsigned long currentMillis = 0;
- const int ledSize = 3;
- const int led[] = {13, 12, 8};
- int ledState[] = {LOW, LOW, LOW};
- const int button = 7;
- int previousButtonState = HIGH;
- int buttonState = HIGH;
- unsigned long previousMillis = 0;
- unsigned long loopCounter = 0;
- const long interval = 1; // 1 millisecond
- // state 0 : blink every second, state 1 blink 3 times
- int ledStateMachine[] = {0, 0, 0};
- int currentLed = -1;
- int togglesLeft[] = {6, 6, 6};
- void setup()
- {
- for (int i = 0; i < ledSize; i++)
- pinMode(led[i], OUTPUT);
- }
- bool buttonWasPressed()
- {
- previousButtonState = buttonState;
- buttonState = digitalRead(button);
- return previousButtonState == HIGH && buttonState == LOW;
- }
- void handleLedStuff(int i, unsigned long loopCounter)
- {
- if (i == currentLed && ledStateMachine[i] == 1 && togglesLeft[i] == 0)
- {
- // no toggles left, reset state to default
- ledStateMachine[i] = 0;
- // set toggles back to default value
- togglesLeft[i] = 6;
- }
- else if (i == currentLed && ledStateMachine[i] == 1 && loopCounter % 300 == 0)
- {
- // toggles left, toggle and decrease toggles every 300 milliseconds
- ledState[i] = !ledState[i];
- togglesLeft[i]--;
- }
- else if (loopCounter % 2000 == 0)
- {
- // manually set led to low on every even second
- // in order not to get out of sync, with the previously fast
- // blinking led
- ledState[i] = LOW;
- }
- else if(loopCounter % 1000 == 0)
- {
- // manually set led to on every odd second
- // needed in order not to get out of sync
- // with the previously fast blinking led
- ledState[i] = HIGH;
- }
- }
- bool blinkingLedExists()
- {
- for (int i = 0; i < ledSize; i++)
- {
- if (ledStateMachine[i] == 1)
- return true;
- }
- return false;
- }
- void loop()
- {
- // get state
- bool buttonPressed = buttonWasPressed();
- currentMillis = millis();
- if (buttonPressed)
- {
- if(!blinkingLedExists())
- {
- // configure current led to be the blinking led
- // only continue if no blinking led exists
- // we don't want weird stuff to happen if the button is pressed too fast
- currentLed = (currentLed + 1) % 3;
- ledStateMachine[currentLed] = 1;
- }
- }
- // evaluate every millisecond
- if (currentMillis - previousMillis >= interval)
- {
- previousMillis = currentMillis;
- for (int i = 0; i < ledSize; i++)
- {
- handleLedStuff(i, loopCounter);
- }
- loopCounter++;
- }
- // set state
- for (int i = 0; i < ledSize; i++)
- digitalWrite(led[i], ledState[i]);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement