LoginSignup
1
0

More than 3 years have passed since last update.

FreeRTOS理解その8(タイマー)

Posted at

ソフトウェアタイマー

今回はFreeRTOSのタイマー機能を使ってみる。あまりいい例題ではないかもしれないが、M5Stackにて起動からの経過時間を表示してみる。

環境

Arduino IDEでのM5Stack利用。

内容

起動からの経過時間をミリ秒で返すmillis()を用いて、「分:秒:ミリ秒」をM5Stack LCDに表示する。ミリ秒については10ミリ秒ごとに表示を更新する。

タイマーAPI

xTimerCreateによりタイマーを作成。ここにあるサンプルを参考に作る。タイマー開始には、xTimerStartを使う。ここでは、10ミリ秒、秒、分のそれぞれについてタイマーを設けた。

ソースコード

まずはタイマー関連の設定。

#include <M5Stack.h>

TimerHandle_t xMsec, xSec, xMin;
void MsecCallback(TimerHandle_t);
void SecCallback(TimerHandle_t);
void MinCallback(TimerHandle_t);

void MsecCallback(TimerHandle_t xTim) {
  char buf[4];
  uint32_t current = millis();
  sprintf(buf, "%02d", (current%1000)/10);
  M5.Lcd.fillRect(210, 100, 70, 40, BLACK);
  M5.Lcd.drawString(buf, 210, 100);  
}

void SecCallback(TimerHandle_t xTim) {
  char buf[4];
  uint32_t current = millis();
  sprintf(buf, "%02d:", (current/1000)%60);
  M5.Lcd.fillRect(140, 100, 70, 40, BLACK);
  M5.Lcd.drawString(buf, 140, 100); 
}

void MinCallback(TimerHandle_t xTim) {
  char buf[4];
  uint32_t current = millis();
  sprintf(buf, "%02d:", (current/(60*1000))%60);
  M5.Lcd.fillRect(70, 100, 70, 40, BLACK);
  M5.Lcd.drawString(buf, 70, 100);   
}

毎10ミリ秒、毎秒、毎分に呼ばれるコールバック関数の定義。M5Stackの描画APIを使い、一つ前の表示数値の削除(黒埋め)および新数値の表示を行う。座標や黒埋めサイズはトライ&エラーで決めた。1ミリ秒単位表示は無視。

void setup() {
  M5.begin();
  M5.Lcd.clear(BLACK);
  M5.Lcd.setTextColor(WHITE);
  M5.Lcd.setTextSize(4);
  M5.Lcd.drawString("00:", 70, 100);  // min
  M5.Lcd.drawString("00:", 140, 100); // sec
  M5.Lcd.drawString("00", 210, 100);  // msec

  xMsec = xTimerCreate("MsecTimer", pdMS_TO_TICKS(10), pdTRUE, (void*)0, MsecCallback);
  xSec = xTimerCreate("SecTimer", pdMS_TO_TICKS(1000), pdTRUE, (void*)0, SecCallback);
  xMin = xTimerCreate("MinTimer", pdMS_TO_TICKS(60*1000), pdTRUE, (void*)0, MinCallback);
  xTimerStart(xMsec, 0);
  xTimerStart(xSec, 0);
  xTimerStart(xMin, 0);
}

void loop() {
  // Nothing
}

setup()にて、LCDの初期化処理および「00:00:00」表示、タイマーの作成(TimerCreate())および開始(TimerStart())を行う。コールバック関数ですべてをハンドリングするのでloop()は何もせず、、(delay()を入れた方がベターか?)。

実験


成功。

実は

タイムアウトした時に呼ばれるコールバック関数で長時間処理を行うことは好ましくない。続編(ストップウォッチ)でこの改善を行う。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0