Arduino Multithreading

Hi, I want to do two things at the same time, for example: turn on two servo motors.

Or I dunno, but can the Arduino handle multithread tasks?
Like calculating [ch960] and flashing a led at the same time.

No such thing as a thread, to the microcontroller. But you could write your own simple task scheduler, and bounce between those tasks according to their timing requirements.

Here's a function I came up with to do what halley is talking about.

boolean cycleCheck(unsigned long *lastMillis, unsigned int cycle) 
{
  unsigned long currentMillis = millis();
  if(currentMillis - *lastMillis >= cycle)
  {
    *lastMillis = currentMillis;
    return true;
  }
  else
    return false;
}

Basic usage:

For each event you want to deal with, set up an unsigned int for how often it should trigger in ms (cycle), and an unsigned long to keep track of the last millis() reading since the last event (lastMillis). You call the function passing the address of the lastMillis for that event and the cycle for that event. The function returns a true if the event is due for action, and a false if the syscle time hasn't elapsed yet.

Typical usage example (Simple blinking 2 LEDs at different rates)

#define ledPin1 11
#define ledPin2 12

#define led1Cycle 100U
#define led2Cycle 275U

unsigned long led1LastMillis = 0;
unsigned long led2LastMillis = 0;

boolean led1State = false;
boolean led2State = false;

boolean cycleCheck(unsigned long *lastMillis, unsigned int cycle) 
{
  unsigned long currentMillis = millis();
  if(currentMillis - *lastMillis >= cycle)
  {
    *lastMillis = currentMillis;
    return true;
  }
  else
    return false;
}

void setup()
{
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
}

void loop()
{
  if(cycleCheck(&led1LastMillis, led1Cycle))
  {
    digitalWrite(ledPin1, led1State);
    led1State = !led1State;
  }
  if(cycleCheck(&led2LastMillis, led2Cycle))
  {
    digitalWrite(ledPin2, led2State);
    led2State = !led2State;
  }
}

I've found this to work very well, and it keeps the main loop code very clean. You can even make the cycle times variable by making them variables instead of #defines. Then you can change the cycle times during execution. For example, you want to change the blink rate with a potentiometer.

That's a very good generalized solution to a common problem.

Thanks. Hope it's useful to some... Someday I'll make the function deal with millis() rollover, too....

For each event you want to deal with, set up an unsigned int for how often it should trigger in ms (cycle), and an unsigned long to keep track of the last millis() reading since the last event (lastMillis). You call the function passing the address of the lastMillis for that event and the cycle for that event. The function returns a true if the event is due for action, and a false if the syscle time hasn't elapsed yet.

I use a very similar function myself, the difference is that I'm using a struct to hold the last_millis- and interval-values. I'm also using similar functions to poll switches, changes in analog input etc. As you said, it keeps the main loop clean and the code is much easier to follow.

I like the idea of using a struct for the last millis and cycle parameters. Good idea.

Maybe have a look at http://www.bdmicro.com/code/threads/ too.

Hello i have to play a sound on a buzzer (so repeat HIGH and LOW on its pins, at a given frequency (the note)) and while i'm doing this, i have to check if to continue or not.

i check from an incoming message from the usb (a midi message), if the message is NoteOff then it has to stop the BUzzer.

maybe i could use this code to deal with that? :-?

giacomo, have a look at the Arduino tone function introduced in release 0018: http://arduino.cc/en/Reference/Tone

thaaaaaanks!

Could have a look at this next time you need to time some reoccurring actions:
http://www.arduino.cc/playground/Code/TimedAction
:slight_smile:

Hi.

I wrote some lines using structs and 2 task running, one for send display data and other for read keyboard buttons.

Task for display run every 3000 milliseconds
Keyboard task run every 100 milliseconds

Enjoy ...

Bruno

typedef struct Timer
{
unsigned long start;
unsigned long timeout;
};

char TimerExpired ( struct Timer * timer )
{
if ( millis () > timer->start + timer->timeout )
return true;

return false;
}

void TimerStart ( struct Timer * timer )
{
timer->start = millis ( );
}

//Display task running every 3000 milliseconds
Timer timerDisplay = { 0, 3000 };
//Keyboard task running every 100 milliseconds
Timer timerKeyboard = { 0, 100 };

void setup (void)
{
}

void loop (void)
{
if ( TimerExpired ( & timerDisplay ) )
{
taskDisplay ( );
TimerStart ( & timerDisplay );
}

if ( TimerExpired ( & timerKeyboard ) )
{
taskKeyboard ( );
TimerStart ( & timerKeyboard );
}
}

void taskKeyboard ( void )
{
}

void taskDisplay ( void )
{
}

Try this:

You can you use the Arduino's in-built PWM timers to change the brightness (as you see it) of an LED.

Check out analogWrite().

Hi, the link to download DuinOS had changed to this:

There you will find in the downloads section the v0.1 and the v0.2 versions.

Regards,
Julián

Hi, the link to download DuinOS (the port of FreeRTOS to Arduino) had changed to this:

There you will find (in the downloads section) the v0.1 and the v0.2 versions.

Regards,
Julián

I forgot the forum DuinOS discussion thread:

http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1256745982/0

Regards,
Julián

Hi.
I want to keep pushing the button to the sound which is played at regular intervals.And,I want to output the time the button is pushed.
At this moment,I respectively made the module which outputs time by the button push and the module which plays a sound at regular intervals.

1.the module which plays a sound at regular intervals

#include <Tone.h>
Tone notePlayer;

void setup(void)
{notePlayer.begin(13);}

void loop(void)
{notePlayer.play(1000,50);  
  delay(1000); // ISI 
}

2.The module which outputs time by the button push

#define BUTTON 7

int val=0;
int  old_val=0;
unsigned long time=0;

void setup(void)
{pinMode(BUTTON,INPUT);
 Serial.begin(9600);}

void loop(void)
{ val=digitalRead(BUTTON);
  delay(5);
  time=millis();
  
if (((val==HIGH) &&(old_val==LOW)))
{Serial.println(time);}
  
old_val=val;  }

Next, I want to integrate these by using multithread.
What should I do?

Lose the delay statements, take a look at the blink without delay example in the IDE, then the two sketches have to be interleaved so they work as one.

The arduino is a primitive computer by anything approaching modern standards, it has no multithreading or multitasking ability, it can do only one thing at once, although with care, it needn't be much hardship.