Arduino入門

2. デバイス&サンプル

5. 拡張モジュール&サンプル

アクセサリー

6. アプリケーション

CoreP4X IR 赤外線送受信

CoreP4X の赤外線信号の送信、受信、生波形の記録と再生に関する API とサンプルプログラムです。

サンプルプログラム

コンパイル要件

  • M5Stack ボードマネージャーバージョン >= 3.3.10-a
  • ボード選択 = M5CoreP4X
  • M5Unified ライブラリバージョン >= 0.3.1
  • M5GFX ライブラリバージョン >= 0.3.1
  • IRremote ライブラリバージョン >= 4.7.1

CoreP4X の赤外線 LED は G49 からトランジスタを介して駆動され、赤外線受信モジュールの出力は G13 に接続されています。赤外線回路は 3V3_L3B 電源ドメインを使用し、この電源は M5IOE1 IO12 (PYB_L3B_EN) で制御されます。M5Unified は初期化時に IO12 を High に設定し、L3B の共有電源をオンにします。

NEC ループバックテスト

このサンプルは CoreP4X のオンボード赤外線送受信経路をテストするものです。画面をタップすると、オンボードの赤外線 LED が NEC フレームを 1 回送信し、オンボードの赤外線受信モジュールがその信号を受信して解析します。外部のリモコンや、送信部と受信部の間の反射物は必要ありません。

cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
#include <IRremote.hpp>
#include <M5Unified.h>

static constexpr uint8_t IR_TX_PIN = 49;
static constexpr uint8_t IR_RX_PIN = 13;

M5Canvas canvas(&M5.Display);

uint16_t nextAddress = 0x0000;
uint8_t nextCommand = 0x10;

bool hasSent = false;
uint16_t sentAddress = 0;
uint8_t sentCommand = 0;

bool hasReceived = false;
char rxProtocol[16] = "--";
uint32_t rxAddress = 0;
uint8_t rxCommand = 0;
uint32_t rxRaw = 0;

static void drawPanel(int y, const char* title, uint16_t accent,
                      const char* line1, const char* line2)
{
  constexpr int x = 24;
  constexpr int w = 432;
  constexpr int h = 148;

  canvas.fillRect(x, y, w, h, TFT_WHITE);
  canvas.drawRect(x, y, w, h, TFT_DARKGREY);
  canvas.fillRect(x, y, w, 8, accent);

  canvas.setTextDatum(middle_center);
  canvas.setTextColor(TFT_BLACK);

  canvas.setFont(&fonts::FreeSansBold18pt7b);
  canvas.drawString(title, x + w / 2, y + 34);

  canvas.setFont(&fonts::FreeSans12pt7b);
  canvas.drawString(line1, x + w / 2, y + 82);
  canvas.drawString(line2, x + w / 2, y + 118);
}

static void drawScreen()
{
  char txLine[48];
  char rxLine[48];
  char rxDetail[48];

  if (hasSent) {
    snprintf(txLine, sizeof(txLine), "Addr 0x%04lX  Cmd 0x%02X",
             static_cast<unsigned long>(sentAddress), sentCommand);
  } else {
    snprintf(txLine, sizeof(txLine), "Ready to send");
  }

  if (hasReceived) {
    snprintf(rxLine, sizeof(rxLine), "%s  Addr 0x%04lX  Cmd 0x%02X",
             rxProtocol, static_cast<unsigned long>(rxAddress), rxCommand);
    snprintf(rxDetail, sizeof(rxDetail), "Raw 0x%08lX",
             static_cast<unsigned long>(rxRaw));
  } else {
    snprintf(rxLine, sizeof(rxLine), "No signal received");
    snprintf(rxDetail, sizeof(rxDetail), "Waiting for IR");
  }

  canvas.fillSprite(TFT_WHITE);
  canvas.drawRect(8, 8, 464, 464, TFT_BLACK);

  canvas.setTextDatum(middle_center);
  canvas.setTextColor(TFT_BLACK);
  canvas.setFont(&fonts::FreeSansBold24pt7b);
  canvas.drawString("CoreP4X IR", 240, 36);

  canvas.setFont(&fonts::FreeSans9pt7b);
  canvas.drawString("Tap screen to send NEC", 240, 80);

  drawPanel(104, "SEND", TFT_BLUE, txLine,
            hasSent ? "NEC frame sent" : "Tap anywhere");
  drawPanel(270, "RECEIVE", TFT_DARKGREEN, rxLine, rxDetail);

  canvas.setFont(&fonts::FreeSans9pt7b);
  canvas.drawString("Point an IR remote at the receiver at any time", 240, 448);
  canvas.pushSprite(0, 0);
}

void setup()
{
  auto cfg = M5.config();
  cfg.serial_baudrate = 115200;
  M5.begin(cfg);

  M5.Display.setRotation(0);
  M5.Display.setBrightness(160);
  canvas.createSprite(M5.Display.width(), M5.Display.height());

  IrReceiver.begin(IR_RX_PIN, DISABLE_LED_FEEDBACK);
  IrSender.begin(DISABLE_LED_FEEDBACK);
  IrSender.setSendPin(IR_TX_PIN);

  Serial.printf("IR TX pin: %u, RX pin: %u\n", IR_TX_PIN, IR_RX_PIN);
  drawScreen();
}

void loop()
{
  M5.update();

  if (M5.Touch.getDetail().wasClicked()) {
    sentAddress = nextAddress;
    sentCommand = nextCommand;
    hasSent = true;

    Serial.printf("Send NEC: addr=0x%04X, cmd=0x%02X\n",
                  sentAddress, sentCommand);
    IrSender.sendNEC(sentAddress, sentCommand, 0);

    ++nextAddress;
    ++nextCommand;

    IrReceiver.restartAfterSend();
    delay(20);
    drawScreen();
  }

  if (IrReceiver.decode()) {
    const auto& data = IrReceiver.decodedIRData;

    snprintf(rxProtocol, sizeof(rxProtocol), "%s",
             getProtocolString(data.protocol));
    rxAddress = data.address;
    rxCommand = data.command;
    rxRaw = data.decodedRawData;
    hasReceived = true;

    Serial.printf("Receive: protocol=%s, addr=0x%04lX, cmd=0x%02X, raw=0x%08lX\n",
                  rxProtocol, static_cast<unsigned long>(rxAddress),
                  rxCommand, static_cast<unsigned long>(rxRaw));

    IrReceiver.resume();
    drawScreen();
  }

  delay(5);
}

画面をタップすると、プログラムは NEC フレームを 1 回送信し、その後、受信モジュールがこの信号を受信するのを待ちます。画面上部には送信したアドレスとコマンド、下部には受信したプロトコル、アドレス、コマンド、生データが表示され、シリアルにも送受信結果が出力されます。

説明
赤外線通信は距離、角度、環境光の影響を受けます。

任意の赤外線信号の記録と再生

このサンプルは、受信モジュールが受信した任意の 1 フレームの生の mark/space タイミングを保存し、画面にプロトコル名、ビット数、タイミング数、フレーム時間、先頭の tick 値を表示します。その後、IrSender.sendRaw() で元のタイミングのまま再送します。プロトコルが IRremote のデコード表にない場合(UNKNOWN と表示)でも、記録と再生は可能です。

受信モジュールの出力は搬送波を除去したエンベロープ信号であるため、元の搬送波周波数を復元できません。そのため、サンプルでは常に 38 kHz で再送し、High/Low のタイミングは実際に受信した信号を使用します。

cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
#define RAW_BUFFER_LENGTH 750
#include <IRremote.hpp>
#include <M5Unified.h>

static constexpr uint8_t IR_TX_PIN = 49;
static constexpr uint8_t IR_RX_PIN = 13;
static constexpr uint8_t IR_FREQUENCY_KHZ = 38;
static constexpr uint32_t REPLAY_DELAY_MS = 1000;
static constexpr uint8_t RAW_HEAD_COUNT = 6;

M5Canvas canvas(&M5.Display);

static uint8_t replayData[RAW_BUFFER_LENGTH];
static uint16_t replayLength = 0;
static bool replayPending = false;
static uint32_t replayAtMs = 0;
static bool hasReceived = false;
static bool hasSent = false;

static char rxProtocol[16] = "--";
static uint16_t rxBits = 0;
static uint32_t rxDurationMs = 0;
static uint8_t rxHead[RAW_HEAD_COUNT] = {};
static uint8_t rxHeadCount = 0;

static void drawPanel(int y, int h, const char* title, uint16_t accent,
                      const char* line1, const char* line2,
                      const char* line3 = nullptr)
{
  constexpr int x = 24;
  constexpr int w = 432;

  canvas.fillRect(x, y, w, h, TFT_BLACK);
  canvas.drawRect(x, y, w, h, TFT_DARKGREY);
  canvas.fillRect(x, y, 6, h, accent);

  canvas.setTextDatum(middle_center);
  canvas.setTextColor(accent, TFT_BLACK);
  canvas.setFont(&fonts::FreeSansBold18pt7b);
  canvas.drawString(title, x + w / 2, y + 32);

  canvas.setTextColor(TFT_WHITE, TFT_BLACK);
  canvas.setFont(&fonts::FreeSans12pt7b);
  canvas.drawString(line1, x + w / 2, y + 72);
  canvas.drawString(line2, x + w / 2, y + 101);
  if (line3) canvas.drawString(line3, x + w / 2, y + 130);
}

static void drawScreen()
{
  char rxLine1[64];
  char rxLine2[64];
  char rxLine3[72];
  char txLine[48];
  char txDetail[48];
  char stateLine[48];

  if (hasReceived) {
    snprintf(rxLine1, sizeof(rxLine1), "Protocol: %s   Bits: %u",
             rxProtocol, rxBits);
    snprintf(rxLine2, sizeof(rxLine2), "Raw: %u   Time: %lu ms",
             replayLength, static_cast<unsigned long>(rxDurationMs));

    int offset = snprintf(rxLine3, sizeof(rxLine3), "Ticks:");
    for (uint8_t i = 0; i < rxHeadCount &&
           offset < static_cast<int>(sizeof(rxLine3)); ++i) {
      offset += snprintf(rxLine3 + offset, sizeof(rxLine3) - offset,
                         " %u", rxHead[i]);
    }
  } else {
    snprintf(rxLine1, sizeof(rxLine1), "Waiting for any IR frame");
    snprintf(rxLine2, sizeof(rxLine2), "IR signals accepted");
    snprintf(rxLine3, sizeof(rxLine3), "Raw timing will be captured");
  }

  if (replayPending) {
    const uint32_t now = millis();
    const uint32_t remaining =
        replayAtMs > now ? replayAtMs - now : 0;
    snprintf(stateLine, sizeof(stateLine), "REPLAY IN %lu.%01lu s",
             static_cast<unsigned long>(remaining / 1000),
             static_cast<unsigned long>((remaining % 1000) / 100));
    snprintf(txLine, sizeof(txLine), "Raw frame queued");
    snprintf(txDetail, sizeof(txDetail), "Protocol-independent replay");
  } else if (hasSent) {
    snprintf(stateLine, sizeof(stateLine), "REPLAY COMPLETE");
    snprintf(txLine, sizeof(txLine), "Last frame replayed");
    snprintf(txDetail, sizeof(txDetail), "Listening for next signal");
  } else {
    snprintf(stateLine, sizeof(stateLine), "LISTENING");
    snprintf(txLine, sizeof(txLine), "No frame queued");
    snprintf(txDetail, sizeof(txDetail), "Receive -> wait 1 s -> send");
  }

  const uint16_t stateColor =
      replayPending ? TFT_CYAN : (hasSent ? TFT_GREEN : TFT_YELLOW);

  canvas.fillSprite(TFT_BLACK);
  canvas.drawRect(8, 8, 464, 464, TFT_DARKGREY);
  canvas.setTextDatum(middle_center);

  canvas.setTextColor(TFT_WHITE, TFT_BLACK);
  canvas.setFont(&fonts::FreeSansBold24pt7b);
  canvas.drawString("IR REPLAY", 240, 46);

  canvas.setTextColor(stateColor, TFT_BLACK);
  canvas.setFont(&fonts::FreeSansBold12pt7b);
  canvas.drawString(stateLine, 240, 94);

  drawPanel(126, 176, "CAPTURED", TFT_CYAN,
            rxLine1, rxLine2, rxLine3);
  drawPanel(318, 124, "NEXT SEND", TFT_DARKGREEN,
            txLine, txDetail);

  canvas.setTextColor(TFT_DARKGREY, TFT_BLACK);
  canvas.setFont(&fonts::FreeSans9pt7b);
  canvas.drawString("Received carrier is unavailable; replay uses 38 kHz",
                    240, 458);
  canvas.pushSprite(0, 0);
}

static bool isReplayable(const IRData& data)
{
  // Any completed frame is valid as long as the raw buffer did not overflow.
  if (data.flags & IRDATA_FLAGS_WAS_OVERFLOW) return false;
  return data.rawlen >= 4 && data.rawlen <= RAW_BUFFER_LENGTH;
}

void setup()
{
  auto cfg = M5.config();
  cfg.serial_baudrate = 115200;
  M5.begin(cfg);

  M5.Display.setBrightness(160);
  canvas.createSprite(M5.Display.width(), M5.Display.height());

  IrReceiver.begin(IR_RX_PIN, DISABLE_LED_FEEDBACK);
  IrSender.begin(IR_TX_PIN);

  Serial.printf("IR replay ready: TX=%u, RX=%u, delay=%lu ms\n",
                IR_TX_PIN, IR_RX_PIN,
                static_cast<unsigned long>(REPLAY_DELAY_MS));
  drawScreen();
}

void loop()
{
  M5.update();

  if (!replayPending && IrReceiver.decode()) {
    const auto& data = IrReceiver.decodedIRData;

    if (isReplayable(data)) {
      replayLength = data.rawlen - 1;
      IrReceiver.compensateAndStoreIRResultInArray(replayData);

      snprintf(rxProtocol, sizeof(rxProtocol), "%s",
               getProtocolString(data.protocol));
      rxBits = data.numberOfBits;

      uint32_t totalTicks = 0;
      for (uint16_t i = 0; i < replayLength; ++i) {
        totalTicks += replayData[i];
      }
      rxDurationMs = totalTicks * MICROS_PER_TICK / 1000;

      rxHeadCount = replayLength < RAW_HEAD_COUNT
                  ? replayLength : RAW_HEAD_COUNT;
      memcpy(rxHead, replayData, rxHeadCount);

      hasReceived = true;
      hasSent = false;
      replayPending = true;
      replayAtMs = millis() + REPLAY_DELAY_MS;

      // Freeze the raw buffer until the captured frame is retransmitted.
      IrReceiver.stop();
      Serial.printf("Queued: protocol=%s, bits=%u, raw=%u, time=%lu ms, flags=0x%02X\n",
                    rxProtocol, rxBits, replayLength,
                    static_cast<unsigned long>(rxDurationMs), data.flags);
      drawScreen();
    } else {
      Serial.printf("Ignored overflow frame: rawlen=%u\n", data.rawlen);
      IrReceiver.resume();
    }
  }

  if (replayPending) {
    const uint32_t now = millis();
    if (static_cast<int32_t>(now - replayAtMs) >= 0) {
      IrSender.sendRaw(replayData, replayLength, IR_FREQUENCY_KHZ);
      replayPending = false;
      hasSent = true;

      // Start reception only after transmission is complete.
      IrReceiver.start();
      Serial.printf("Replayed %u raw timing entries at %u kHz\n",
                    replayLength, IR_FREQUENCY_KHZ);
      drawScreen();
    } else {
      static uint32_t lastRefresh = 0;
      if (now - lastRefresh >= 100) {
        lastRefresh = now;
        drawScreen();
      }
    }
  }

  delay(1);
}

書き込み後、任意の赤外線リモコンを CoreP4X の赤外線受信モジュールに向けて 1 回信号を送信すると、画面にキャプチャ結果が表示されます。1 秒のカウントダウン後、赤外線 LED が保存したタイミングで自動的に 1 回再送します。

シリアル出力例:

Queued: protocol=NEC, bits=32, raw=67, time=68 ms, flags=0x00
Replayed 67 raw timing entries at 38 kHz

Queued: protocol=UNKNOWN, bits=0, raw=53, time=72 ms, flags=0x00
Replayed 53 raw timing entries at 38 kHz

API

CoreP4X の赤外線送受信は IRremote ライブラリを使用します。このページのサンプルでは主に以下のインターフェースを使用します:

  • IrReceiver.decode():赤外線フレームの受信を完了し、プロトコルを解析します。
  • IrReceiver.compensateAndStoreIRResultInArray():受信した mark/space タイミングを保存します。
  • IrSender.sendRaw():保存したタイミングに従って赤外線信号を再送します。
  • IrReceiver.stop() / IrReceiver.start():待機中は受信を停止してバッファが次のフレームで上書きされるのを防ぎ、送信完了後に再開します。

その他の関連 API については以下のドキュメントを参照してください:

Page Tools
PDF
On This Page