From 37eaa5d112dc7dc20505bb70171d8ac30893936d Mon Sep 17 00:00:00 2001 From: Koichi Ito Date: Tue, 22 Sep 2026 15:54:08 +0900 Subject: [PATCH] =?UTF-8?q?I2C=E3=81=8C=E7=84=A1=E3=81=8F=E3=81=A8?= =?UTF-8?q?=E3=82=82=E5=8B=95=E4=BD=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- firmware/firmware.ino | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/firmware/firmware.ino b/firmware/firmware.ino index 5b0ba36..9305684 100644 --- a/firmware/firmware.ino +++ b/firmware/firmware.ino @@ -23,6 +23,12 @@ int currentVolumePercent = 0; // 音量(0〜100%) bool bluetoothConnected = false; bool musicPlaying = false; unsigned long lastDisplayUpdate = 0; +bool oledReady = false; + +bool isI2cDevicePresent(uint8_t address) { + Wire.beginTransmission(address); + return Wire.endTransmission() == 0; +} // UTF-8の文字列を1文字ずつ描画します。 // フォントにない文字は、フォントに頼らず四角形を直接描きます。 @@ -93,6 +99,10 @@ void drawUtf8WithTofu(uint8_t x, uint8_t y, const String& text) { // OLEDの内容を現在の状態に合わせて描き直します。 void updateDisplay() { + if (!oledReady) { + return; + } + u8g2.clearBuffer(); // 音楽を再生していないときは、センサーの情報を表示します。 @@ -212,10 +222,21 @@ void setup() { // I2Cの配線を設定します。Wire.begin(SDA, SCL)の順です。 Wire.begin(21, 22); + Wire.setTimeOut(50); - // OLEDを使える状態にします。 - u8g2.begin(); - u8g2.enableUTF8Print(); // UTF-8(日本語)描画を有効化 + // OLEDが接続されているときだけ初期化と描画を行います。 + uint8_t oledAddress = 0; + if (isI2cDevicePresent(0x3C)) { + oledAddress = 0x3C; + } else if (isI2cDevicePresent(0x3D)) { + oledAddress = 0x3D; + } + if (oledAddress != 0) { + u8g2.setI2CAddress(oledAddress << 1); + u8g2.begin(); + u8g2.enableUTF8Print(); // UTF-8(日本語)描画を有効化 + oledReady = true; + } sensorLogger.begin(32); updateDisplay();