You need to log in to create posts and topics.

Multithreading with Arduino

What happens if you need to do more than one thing at different time intervals?

 

The simplest thing that you might want to do at intervals is to blink a LED and normally you would use the delay(milliseconds) function:

void loop()

{

digitalWrite(nLEDPin, HIGH);

delay(500);

digitalWrite(nLEDPin, LOW);

delay(500);

}

But what if you wanted to blink 2 LEDs and at different speeds? E.G. One every half a second and the other every second.

This means you can't use the delay(microseconds) function.

So how would you do it?

You use the millis() function which returns the number of milliseconds that have elapsed since the sketch started.

void loop()

{

// The key word 'static' makes all the variables that follow like global variables in that they won't lose their value each time the loop() function finishes.

// But unlike regular global variables their scope is confined to inside the loop() function

static uint32_t nMillisLastChangeStateLED1 = 0, nMillisLastChangeStateLED2 = 0;

static bool bLED1State = false, bLED2State = true;

 

// millis() - nMillisLastChangeStateLED1  gives you the number of milliseconds that have elapsed since LED1 was last turned on or off

// And we want to change the state of  LED1 every half a second or 500 milliseconds.

if ((millis() - nMillisLastChangeStateLED1 ) >= 500)

{

// Toggle the state of LED1 - true = on and false = off

bLED1State  = !bLED1State ;

// Now actually set the LED to that state

digitalWrite(nLED1Pin, bLED1State);

// Save the time.

nMillisLastChangeStateLED1  = millis();

}

// millis() - nMillisLastChangeStateLED2  gives you the number of milliseconds that have elapsed since LED2 was last turned on or off

// And we want to change the state of LED2 every 1 second or 1000 milliseconds

if ((millis() - nMillisLastChangeStateLED2) >= 1000)

{

// Toggle the state of LED2 - true = on and false = off

bLED2State  = !bLED2State ;

// Now actually set the LED to that state

digitalWrite(nLED2Pin, bLED2State);

// Save the time.

nMillisLastChangeStateLED2  = millis();

}

}

 

 

 

 

 

Hi Greg - Was this an answer to a question someone had raised in class?

Cheers/Trevor