マルチタスクで実装
今回はマルチタスクの実装をしてみましょう。
タスクの生成
タスクを生成する関数はこちらです。
// タスク生成 xTaskCreatePinnedToCore(Clock_Time, "Clock_Time", 4096, NULL, 1, NULL, 0); xTaskCreatePinnedToCore(Disp_Edit, "Disp_Edit", 4096, NULL, 1, NULL, 1);
第1引数:タスクの関数名
第2引数:タスク名
第3引数:スタックメモリサイズ
第4引数:NULL
第5引数:タスク優先順位(1~25)
第6引数:タスクハンドルポインタ
第7引数:Core ID(0 or 1)
マルチコアを実行するコード
こちらがコードです。
#include <M5Stack.h> #include <WiFi.h> #include <time.h> #include <TimeLib.h> const char* ssid = "YOUR_SSID"; ←変更箇所 const char* password = "YOUR_PASS"; ←変更箇所 const char* ntpServer = "ntp.nict.jp"; // NTPサーバ const long gmtOffset_sec = 3600 * 9; const int daylightOffset_sec = 0; struct tm timeinfo; static unsigned int auiCnt = 0; /****************************************************/ /* 時刻表示 */ /****************************************************/ void Clock_Time(void* arg) { //init and get the time configTime(gmtOffset_sec, daylightOffset_sec, ntpServer); // 設定した時刻を取得 if(!getLocalTime(&timeinfo)){ M5.Lcd.println("Failed to obtain time"); return; } // 時刻の設定 setTime(timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec, timeinfo.tm_mday, timeinfo.tm_mon + 1, timeinfo.tm_year + 1900); //disconnect WiFi as it's no longer needed WiFi.disconnect(true); WiFi.mode(WIFI_OFF); while (1) { // テキストサイズ指定 M5.Lcd.setTextSize(2); // カーソル位置を設定 M5.Lcd.setCursor(50,0); M5.Lcd.printf("%04d-%02d-%02d %02d:%02d:%02d" ,year() ,month() ,day() ,hour() ,minute() ,second() ); delay(1000); } } /****************************************************/ /* 画面表示 */ /****************************************************/ void Disp_Edit(void* arg){ unsigned int auiCnt = 0; while (1) { // テキストサイズ指定 M5.Lcd.setTextSize(1); // カウンタ表示 M5.Lcd.setCursor(50,80); M5.Lcd.printf("Disp_Edit Task Cnt : %d",auiCnt); // カウンタ更新 auiCnt++; delay(1100); } } void setup() { // M5Stackの初期化 M5.begin(); //connect to WiFi M5.Lcd.print("Connecting to YOUR_SSID "); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); M5.Lcd.print("."); } M5.Lcd.println(" CONNECTED"); delay(500); // BLACK Screen M5.Lcd.fillScreen(BLACK); // タスク生成 xTaskCreatePinnedToCore(Clock_Time, "Clock_Time", 4096, NULL, 1, NULL, 0); xTaskCreatePinnedToCore(Disp_Edit, "Disp_Edit", 4096, NULL, 1, NULL, 1); } void loop() { // テキストサイズ指定 M5.Lcd.setTextSize(1); // カウンタ表示 M5.Lcd.setCursor(50,100); M5.Lcd.printf("Main loop Task Cnt : %d",auiCnt); // カウンタ更新 auiCnt++; delay(1200); }
不安定で落ちます。。。
見た目じゃわからないかもしれないけどマルチタスクになってます。
— yamanonono (@yamano_no_no) September 27, 2019
ただ、不安定なのでよく落ちます。#m5stack pic.twitter.com/pLCE5OVzas