You can also simulate some parallel tasks that runs at some preconfigured intervals.
Note: I used direct bitwise operation to control led blink, but you can do it using digitalWrite
of course
#include <Arduino.h>
//------------------------------------------------------------------------------
// Declarations // should be in the .h file
#define THA 0
void threadA(unsigned long time);
#define THB 1
void threadB(unsigned long time);
#define THC 1
void threadC(unsigned long time);
//------------------------------------------------------------------------------
// Initializations
const unsigned int pump1 = _BV(0); //0b00000001, bit position, bit 0 in PORTB, == digital pin 9
const unsigned int ledB = _BV(1); //0b00000010, bit position, bit 1 in PORTB, == digital pin 10
// Threads definitions
// You can add or remove threads here
void (*THREADS[])(unsigned long) = {threadA, threadB, threadC};
int THINT[] = {0, 500, 5000}; // Interval for each threads
//------------------------------------------------------------------------------
// Threads
// Main loop, no interval
void threadA(unsigned long time){
}
// Every 500ms
void threadB(unsigned long time){
PORTB ^= ledB; // Just toggle a led ON/OFF on bit ledB on PORTB
}
// Every 5000ms
void threadC(unsigned long time){
PORTB ^= pump1; // Toggle the motor
}
//------------------------------------------------------------------------------
// Arduino core
void setup(){
DDRB |= ledB | pump1; // Enable ledB and pump1 as output
}
// The loop method handle threads by launching each threads one after the other when their time come
void loop(){
const int nbThread = sizeof(THREADS)/sizeof(&threadA); // Number of threads
unsigned long threadTime[nbThread];
char nextThread = 0;
while(1){
if((threadTime[nextThread] + THINT[nextThread]) < millis()){
threadTime[nextThread] = millis();
(*THREADS[nextThread])(threadTime[nextThread]);
}
if(++nextThread >= nbThread)
nextThread = 0;
}
}