Electronic – arduino – Attiny44A Arduino Multitasking

arduinoattinymicrocontrollerthread

I am trying to blink a led as well as switch a motor on/off parallely using attiny44A below is my code:

Pump Controller:

   digitalWrite(pump1, HIGH);
   delay(5000);
   digitalWrite(pump1, LOW);
   digitalWrite(pump2, HIGH);
   delay(5000);

Led Blink:

    digitalWrite(ledB, HIGH);
    delay(500);
    digitalWrite(ledB, LOW);
    delay(500);

How do I make this run paralley together

Best Answer

There are a few ways to go about it, such as using timer interrupts etc, but another way is to use a simple state machine to keep track of when events last occurred. Treat this as more as an example of how to do it because it's untested and I'm not an Arduino user so may have a few data types wrong. But one approach would be something like:

boolean led_on = false;
unsigned long led_toggle_ms = 0;
boolean pump1_on = false;
unsigned long pump_toggle_ms = 0;

void loop()
{
    if (millis() - led_toggle_ms >= 500)
    {
        led_toggle_ms = millis();
        led_on = !led_on;
        digitalWrite(ledB, led_on);
    }
    if (millis() - pump_toggle_ms >= 5000)
    {
        pump_toggle_ms = millis();
        pump1_on = !pump1_on;
        digitalWrite(pump1, pump1_on);
        digitalWrite(pump2, !pump1_on);
    }
}

By keeping track of the time something last occurred rather than using delay it allows the rest of the code to continue running. Note that as per the millis() documentation the value will overflow after approximately 50 days, so if you want the application to run for longer that will need to be taken in consideration. If you don't mind a momentary glitch after 50 days that could be something simple like:

if ((millis() - led_toggle_ms >= 500) || (millis() < led_toggle_ms))