• This is a fairly simple tutorial to demonstrate how you can use the button BTN1 to turn on one or more LEDs.

    First, let's turn on LED1:


    Next, let us create a function that will alternate between turning LED1 on and off:

    var next_state = 1;
    function swap() {
      next_state = !next_state;

    we can now simply type swap(); to turn the LED on when it was off or vice versa. The next step is to keep a watch for that button and whether the user pressed it. For this, we have the function setWatch. However, this will be triggered twice: once when the button is pressed down, and once when the user releases the button. We only want our LED to change when the user presses down the button, so we need another function:

    function swap_on_down() {
      if (digitalRead(BTN1) == 1) swap();

    This function is very easy, and will just verify whether BTN1 is pressed down. As such, it won't call the function swap when the user removes his/her finger from the button. This is exactly what we want! Now we can use the setWatch and let it call swap_on_down:

    setWatch(swap_on_down, BTN1, true);

    The last true option is provided so that this watch will keep on calling our function on successive presses on the button instead of only once. Try it, and you should see the red LED go on and off, each time you press the button.

    Maybe even more fun is alternating the colours. The idea here is that, when we press the button, the red light comes on. When we press the button again, the green lights goes on. Next time, the blue goes on, after which another press of the button will turn the red light back on etc. As one added tough, we can add that all LEDS turn off after the user stopped pressing the button for 5 seconds.

    // keep track of the next LED
    var next_LED = 1;
    // keep track of the ID, see later
    var timeout_ID = 0;
    function swap() {
      // remove the timeout to turn of all LEDs when the user pressed the button
      // determine which LED to turn on/off
      switch(next_LED) {
        case 1:
        case 2:
        case 3:
      // determine the next LED to turn on
      next_LED = Math.wrap(next_LED, 3) + 1;
      // prepare a timeout to turn off all LEDs after a while
      // we capture the ID here, so that we can use it in a next call to this function
      timeout_ID = setTimeout(function () { LED1.write(0); LED2.write(0); LED3.write(0); }, 5000);

    As you will see, this works as expected but returns an ERROR: Unknown Timeout at some times (when all LEDs are off). Sadly, there is nothing to be done about that using this code, but you are always welcome to improve upon it :).


Avatar for Kim @Kim started