Search code examples
arduinosequentialled

arduino sequential lighting


i'm still learning arduino. I'm trying to initialize a sequence of 3 leds lighting sequentially on button click. What I want is that the button acts as a switch switching on and off the sequence. So far I've done it but you have to keep the button pressed to keep it running.. I've tried another method by reading the button state after the sequence(all 3 leds) has finished, but I'm still not satisfied with that solution, since I want to be able to press the button switch ANY time during the sequence to turn the sequence off. Any help please?


Solution

  • You could try using a state variable. Declare a boolean variable such as:

    boolean runSequence = false;
    

    Now, when you detect a button press, just toggle the state:

    // Replace this condition to whatever matches your button setup
    if ( digitalRead(pin) == HIGH )
    {    
        runSequence = !runSequence;
    }
    

    Then, you can control your light sequence based on the state:

    if ( runSequence )
    {
        // code to run your light sequence
    }
    

    Now, be warned: this is a simplified example, and does not take into account debouncing the switch. You should add a bit of additional code handle debouncing the switch when you read the switch state; if you're not familiar with this, there are some code examples in the Arduino IDE.

    Try out these suggestions, and if you run into trouble, please post the code that you have so far, and describe where you're having difficulty.