/** * 辞書クラスの使用例 (&正規表現の利用) */ #include <M5StickCPlus.h> #include <Dictionary.h> #include <Regexp.h> Dictionary *dict = new Dictionary(); // 辞書/ハッシュ。キー文字列→値 を保持するデータ構造 // param2dict関数のなかで使われるコールバック関数 void match_callback(const char *match, // matching string (not null-terminated) const unsigned int length, // length of matching string const MatchState &ms) // MatchState in use (to get captures) { char k[10]; // 配列サイズに注意。size must be large enough to hold captures char v[10]; // 配列サイズに注意。size must be large enough to hold captures ms.GetCapture(k, 0); ms.GetCapture(v, 1); dict->insert(k, v); // 辞書に追加 (たとえば、 red→120 を追加) } // end of match_callback // 下のsetupからは使用していないが、文字列で受け取った複数のパラメータを辞書に設定するサンプル // たとえば、*cbuf = "red=120&green=255&blue=100" のような文字列をうけとると、辞書に設定する。その後、色を表す整数値として返す int32_t param2dict(char *cbuf) { MatchState ms(cbuf); // 正規表現マッチャーの作成 ms.GlobalMatch("([a-z]+)=([0-9]+)", match_callback); // (key)=(value) で複数回マッチングする。match_callback は別関数。 int r = dict->search("red").toInt(); // 辞書 dict int g = dict->search("green").toInt(); int b = dict->search("blue").toInt(); int32_t color = (int(r * 31 / 255) << 11) | (int(g * 63 / 255) << 5) | (int(b * 31 / 255)); return color; } void setup() { M5.begin(115200); // M5StickCPlusの初期化処理 M5.Lcd.setRotation(3); // Aボタンが左側になる向きで画面を使用するよう設定 M5.Lcd.fillScreen(CYAN); // 画面を塗りつぶす M5.Lcd.setTextColor( BLUE, GREENYELLOW ); M5.Lcd.setCursor(0, 0, 4); // 左から0,上から0ピクセルの位置にフォントサイズ3の文字を出力するよう設定 dict->insert("apple", 200); // 辞書に追加 dict->insert("banana", 100); dict->insert("cherry", 300); char keys[3][10] = {"banana", "cherry", "apple"}; for (int k = 0; k < 3; k++) { Serial.printf("key %s => val %d\n", keys[k], dict->search(keys[k]).toInt()); M5.Lcd.printf("key %s => val %d\n", keys[k], dict->search(keys[k]).toInt()); } } void loop() { // do nothing delay(100); }