When you use arduino to do 2 or more jobs at the same time.You ussualy use function delay, but when you use delay function you will waste time on the cpu. The technique in this article will help you to run multiple programs in parallel.

Hardware

  • Arduino Uno
  • Breadboard
  • Wire put breadboard
  • 2 resistor 560 Ohm ( you can use 220 Ohm or 1kOhm)
  • 2 LED

Put wire

Programs

Target this program, you can blink 2 led in the same time, each led have flow on off different

byte led1 = 5;

byte led2 = 6;

unsigned long time1 = 0;

unsigned long time2 = 0;

void setup()

{

    pinMode(led1, OUTPUT);

    pinMode(led2, OUTPUT);

}

void loop()

{

    if ( (unsigned long) (millis() – time1) > 1000 )

    {

        if ( digitalRead(led1) == LOW )

        {

            digitalWrite(led1, HIGH);

        } else {

            digitalWrite(led1, LOW );

        }

        time1 = millis();

    }

    if ( (unsigned long) (millis() – time2) > 300  )

    {

        if ( digitalRead(led2) == LOW )

        {

            digitalWrite(led2, HIGH);

        } else {

            digitalWrite(led2, LOW );

        }

        time2 = millis();

    }

}

Analysis

On this programs, two variable time1, time2 compare the value with function millis(). If time1 time exceeded 1000ms and 300ms with variable time2 Led will be change. If usual way we will develope

void loop()

{

   if ( digitalRead(led1) == LOW )

   {

        digitalWrite(led1, HIGH);

   } else {

        digitalWrite(led1, LOW );

   }

   delay (700); // 700 + 300 = 1000ms

   if ( digitalRead(led2) == LOW )

   {

        digitalWrite(led2, HIGH);

   } else {

        digitalWrite(led2, LOW );

   }

   delay (300);

}

Thanks for your reading!