Newer
Older
m5scp2_exp / Sample / Sample.ino
#include <M5Unified.h>

// RGB565形式の色から輝度を計算する関数
uint8_t calculateBrightness(uint16_t color) {
  // RGB565からRGB888に変換
  uint8_t r = ((color >> 11) & 0x1F) * 255 / 31;  // 5bit -> 8bit
  uint8_t g = ((color >> 5) & 0x3F) * 255 / 63;   // 6bit -> 8bit  
  uint8_t b = (color & 0x1F) * 255 / 31;          // 5bit -> 8bit
  
  // 輝度計算(人間の視覚に基づく重み付け)
  return (uint8_t)(0.299 * r + 0.587 * g + 0.114 * b);
}

void changeBackgroundColor() {
  // ランダムな背景色を生成
  uint16_t randomColor = random(0x0000, 0xFFFF);  // RGB565形式でランダム色生成
  M5.Display.fillScreen(randomColor);
  
  // 輝度に基づいて適切な文字色を選択
  uint8_t brightness = calculateBrightness(randomColor);
  uint16_t textColor = (brightness < 128) ? WHITE : BLACK;  // 輝度128を境界とする
  M5.Display.setTextColor(textColor);
  
  // テキストを再描画
  M5.Display.setCursor(0, 0);
  M5.Display.println("5秒ごとに\n色が変わります");
}

void setup() {
  auto cfg = M5.config();
  cfg.serial_baudrate = 115200;
  M5.begin(cfg);
  M5.Display.setRotation(3);
  M5.Display.setFont(&fonts::lgfxJapanGothic_16);
  M5.Display.setTextSize(2);
  
  // ランダムシードを初期化
  randomSeed(millis());
  
  // 初期背景色を設定
  changeBackgroundColor();
  
  M5.Display.setTextScroll(true);
  M5.Display.setBrightness(255);
  
}

void loop() {
  M5.update(); // ここではキーを使用しないが、将来的にキー入力を処理する場合はこの関数が必要
  
  changeBackgroundColor();
  
  Serial.println("5秒ごとに色が変わります。");
  M5.delay(5000); 
}
// 書き込み方法: https://scrapbox.io/iot-programming/Build_on_Server を参照してください。