Arduino時(shí)間片輪轉(zhuǎn)

  • 同等地位的N個(gè)任務(wù)
  • 每個(gè)任務(wù)有固定的執(zhí)行間隔
  • 典型的Arduino模式


    setup-loop
  • 將loop進(jìn)行中的任務(wù)進(jìn)行拆分,設(shè)定調(diào)用時(shí)間周期


    時(shí)間片
    • 適用于運(yùn)行周期不同的任務(wù),周期相對(duì)比較準(zhǔn)確
    • 任務(wù)不能阻塞
    • 每次調(diào)用都是同一個(gè)入口,也就是說一次調(diào)用是全部完成返回的
    • 執(zhí)行任務(wù)從時(shí)間上分散后可以增加“實(shí)時(shí)任務(wù)”的及時(shí)性
分散任務(wù)
#ifndef TASK_H
#define TASK_H

typedef void (*P_VOID_void)();

class Task{
  
private:
  int mPeri;
  volatile int mTick;
  P_VOID_void mProc;
  
public:
  Task( P_VOID_void proc, int peri=10 )
  { 
    mPeri = peri;
    mTick = peri; 
    mProc = proc;
  }

  void run()
  {
    if ( mTick <= 0 )
    {
      mTick = mPeri;
      mProc();
    }
  }

  void tick()
  {
    if ( mTick > 0 )
    { mTick--; }
  }
};

#define MAX_TASK_CNT 8

class Schedule
{
private:
  Task * mTasks[MAX_TASK_CNT];
  int mTaskCnt;
  
public:
  Schedule()
  {
    mTaskCnt = 0;
  }  
  
  void start()
  {
      TCCR1A = 0;          // normal operation
      TCCR1B = bit(WGM12) | bit(CS10) | bit(CS12);   // CTC, 1024
      OCR1A =  999;       // compare A register value (1000 * clock speed)
      TIMSK1 = bit (OCIE1A);             // interrupt on Compare A Match
  }

  void run()
  {
      int i;

      for ( i = 0; i < mTaskCnt; i++ )
      {
        mTasks[i]->run();
      }
  }

  void tick()
  {
      int i;

      for ( i = 0; i < mTaskCnt; i++ )
      {
        mTasks[i]->tick();
      }
  }

public:
  void attachTask( Task *pTask )
  {
    mTasks[ mTaskCnt ] = pTask;
    mTaskCnt++;
  } 
};

Schedule _schedule;

ISR(TIMER1_COMPA_vect)
{
  _schedule.tick();
}

#endif 
  • 使用方法
#include <Task.h>
void task1()
{
  Serial.println("task1 "+String( millis() ));
}

void task2()
{
  Serial.println("task2 "+String( millis() ));
}

Task _task1( task1, 60 );
Task _task2( task2, 120 );

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

  _schedule.attachTask( &_task1 );
  _schedule.attachTask( &_task2 );

  _schedule.start();
}

void loop() {
  // put your main code here, to run repeatedly:
  _schedule.run();
}

模塊的添加方法

  • /libraries/模塊名稱
  • /libraries/模塊名稱/src中放置源碼
  • /libraries/模塊名稱/library.properties進(jìn)行模塊描述
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容