Search code examples
c++arduinoledarduino-ide

C++ Arduino, running two loops at once?


Okay so I have just recently dived into programming an Arduino, Currently I have the basic blink function along with a RGB LED program that changes an LED to blue, green and red in fading colors. I have 2 LEDS a simple and basic yellow LED that's supposed to function as an indicator for a "working status". And a LED that is RGB. Now I want the RGB one to transition through it's colors normally although I want to keep the Yellow LED constantly flashing. How hould I make my code so that two processes can run at the same time?


Solution

  • Something like:

    int timekeeper=0;
    while (1) 
    {
        do_fade(timekeeper);
        if (timekeeper%100==0) {
          do_blink_off();
        }
        if (timekeeper%100==50) {
          do_blink_on();
        }
        delay(10);
        timekeeper++;
    }
    

    This is done from memory, so your mileage may vary. I've passed timekeeper to do_fade(), so you can figure out how far along the fade you are. do_fade() would update the fade, then immediately return. do_blink_on() and do_blink_off() would be similar - change what you need to change, then return. In this example, do_fade() would be called every 10 milliseconds, do_blink_off() once per second, with do_blink_on() 1/2 a second after (so on, 1/2 second, off, 1/2 second, on, 1/2 second...)