Arduino时间片轮转

2020-12-30  本文已影响0人  ww4u
分散任务
#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();
}

模块的添加方法

上一篇 下一篇

猜你喜欢

热点阅读