在 Arduino 上面直接寫多任務(wù)的應(yīng)用顯然有些不完美,且開發(fā)也復(fù)雜。
我在 watering 這個項目上使用了 SimpleTimer 作為多任務(wù)處理的基礎(chǔ)汁掠,
在設(shè)置的過程中芍锦,SimpleTimer
并沒有有效的工作。
使用操作系統(tǒng)將很好的解決多任務(wù)調(diào)度的剧包。
在一個湊巧的機會下,我找到了 AtomThreads 往果,它是一個小巧的系統(tǒng)疆液,支持 8 位單片機。
于是就封裝 AtomThreads-Arduino 讓 AtomThreads
可以直接在 Arduino 里面直接使用陕贮。
#include <AtomThreads.h>
#define IDLE_STACK_SIZE_BYTES 128
#define MAIN_STACK_SIZE_BYTES 204
#define DEFAULT_THREAD_PRIO 16
static ATOM_TCB main_tcb;
static uint8_t main_thread_stack[MAIN_STACK_SIZE_BYTES];
static uint8_t idle_thread_stack[IDLE_STACK_SIZE_BYTES];
uint8_t status;
void setup(){
SP = (int)&idle_thread_stack[(IDLE_STACK_SIZE_BYTES/2) - 1];
status = atomOSInit(&idle_thread_stack[0], IDLE_STACK_SIZE_BYTES, FALSE);
if (status == ATOM_OK) {
avrInitSystemTickTimer();
status = atomThreadCreate(&main_tcb,
DEFAULT_THREAD_PRIO, main_thread_func, 0,
&main_thread_stack[0],
MAIN_STACK_SIZE_BYTES,
FALSE);
if (status == ATOM_OK) {
atomOSStart();
}
}
}
static void main_thread_func (uint32_t) {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
while (1) {
loop();
}
}
// Loop and print the time every second.
void loop() {
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
atomTimerDelay(SYSTEM_TICKS_PER_SEC); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
atomTimerDelay(SYSTEM_TICKS_PER_SEC);
}
在 watering
中堕油,通過使用 atomThreadCreate
創(chuàng)建不同的進(jìn)程去處理不同的任務(wù),通過 atomTimerRegister
和 atomTimerCancel
來控制自動背光燈肮之。整個項目的可靠性和實時性比之前增強了許多掉缺,詳見 https://github.com/Lupino/watering/blob/master/watering.ino