Monthly Archives: October 2009

Multitasking/multithreading in C on Arduino

Doing multitasking/multithreading on Arduino has an advantage, it’s give the possibility to read multiple captors, blink led and start a motor at virtually the same time. This is done by cycling rapidly (faster as the Arduino can) witting all the functions. I made up this code to execute many functions in the default cycling loop function on the Arduino. In the sample, the starting functions are hard coded, but The program offer the advantage of starting and stopping functions at run time. In a more complex program I’m doing it by adding a serial communication ability to the code, so I can call only the functions I need.

// By kevin@playwithmyled.com - 2009-10-17.
// 2010-05-11: Better and lighter.

// Define a function pointer and initialize to NULL.
typedef void (*FunctionPointer) ();

// Declare looping actions function names, declared lower.
FunctionPointer xActions[] = {loopActionA,loopActionB,loopActionC};
// Define actions status flags. Set to 1 to auto execute a start.
int xActionsFlags[] = {0,0,0}; 

int xActionsCount = sizeof(xActions);

void xActionTrigger(int id=0, int action=0) {
  // The id represent it's position in the flags array.
  // Action 1 = executed, 0 not.
  xActionsFlags[id] = action;
}

// LOOPING FUNCTIONS

void loopActionA() {
        // Do something...
}

void loopActionB() {
	// Do something...
}

void loopActionC() {
	// Do something...
}

// Exectute all loop functions.
void xDoActions() {
	// Execute all looped function.
	for(unsigned int j=0; j < xActionsCount; j++) {
		if( xActionsFlags[j] == 1 ) { // Execute the action if.
			xActions[j](); // Call the related loop action.
		}
	}
}

void setup() {
        xActionTrigger(0,1); // First action.
        xActionTrigger(2,1); // Third action.
}

void loop() {
	xDoActions();
}