
Arduino入門
ToughC5 の microSD カード関連 API とサンプルプログラムです。
3.3.9M5ToughC50.2.220.2.28ToughC5 の microSD カードは M5IOE1 と ESP32-C5 の両方で制御されます。カードのイネーブル信号 PYB_TF_EN は M5IOE1 GPIO6 に、検出信号 TF_DET は M5IOE1 GPIO14 に接続されています。
#include <Arduino.h>
#include <SPI.h>
#include <SD.h>
#include <M5Unified.h>
#include <M5GFX.h>
#include <utility/M5IOE1_Class.hpp>
static constexpr uint8_t SD_SPI_CS_PIN = 10;
static constexpr uint8_t SD_SPI_SCK_PIN = 9;
static constexpr uint8_t SD_SPI_MOSI_PIN = 7;
static constexpr uint8_t SD_SPI_MISO_PIN = 8;
static constexpr auto M5IOE1_TF_EN_PIN = m5::M5IOE1_Class::gpio6;
static constexpr auto M5IOE1_TF_DET_PIN = m5::M5IOE1_Class::gpio14;
static bool prepareTfCard()
{
auto& ioe1 = M5.getIOExpander(0);
// TF_3V3_L3B is enabled by M5IOE1 G6 (PYB_TF_EN).
ioe1.setHighImpedance(M5IOE1_TF_EN_PIN, false);
ioe1.setDirection(M5IOE1_TF_EN_PIN, true);
ioe1.digitalWrite(M5IOE1_TF_EN_PIN, true);
// TF_DET is connected to M5IOE1 G14 and is active low.
ioe1.setDirection(M5IOE1_TF_DET_PIN, false);
ioe1.setPullMode(M5IOE1_TF_DET_PIN, m5::IOExpander_Base::pull_up);
bool detLevel = true;
if (!ioe1.getInputLevel(M5IOE1_TF_DET_PIN, &detLevel)) {
return false;
}
return !detLevel;
}
void setup() {
M5.begin();
M5.Display.setRotation(1);
M5.Display.setFont(&fonts::FreeMono12pt7b);
if (!prepareTfCard()) {
M5.Display.print("\n TF card not detected\n");
while (true)
delay(1000);
}
SPI.begin(SD_SPI_SCK_PIN, SD_SPI_MISO_PIN, SD_SPI_MOSI_PIN, SD_SPI_CS_PIN);
if (!SD.begin(SD_SPI_CS_PIN, SPI, 25000000)) {
M5.Display.print("\n SD card not detected\n");
while (true)
;
} else {
M5.Display.print("\n SD card detected\n");
}
delay(1000);
M5.Display.print("\n SD card write test...\n");
auto file = SD.open("/WriteTest.txt", FILE_WRITE, true);
if (file) {
file.print("Hello, world! \nSD card write success! \n");
file.close();
M5.Display.print(" SD card write success\n");
} else {
M5.Display.print(" Failed to create TXT file\n");
}
delay(1000);
M5.Display.print("\n SD card read test...\n");
auto picture01 = SD.open("/TestPicture01.png", FILE_READ, false);
if (picture01) {
picture01.close();
M5.Display.print(" PNG file 01 detected\n");
} else {
M5.Display.print(" PNG file 01 not detected\n");
}
auto picture02 = SD.open("/TestPicture02.png", FILE_READ, false);
if (picture02) {
picture02.close();
M5.Display.print(" PNG file 02 detected\n");
} else {
M5.Display.print(" PNG file 02 not detected\n");
}
delay(1000);
}
void loop() {
M5.Display.drawPngFile(SD, "/TestPicture01.png");
delay(500);
M5.Display.drawPngFile(SD, "/TestPicture02.png");
delay(500);
}FAT32 でフォーマットした microSD カードを用意し、ルートディレクトリに TestPicture01.png と TestPicture02.png という名前で、解像度 320*240 の PNG 画像を 2 枚保存します。サンプル画像 1 と サンプル画像 2 もダウンロードできます。画像の解像度が 320*240 でない場合、プログラムは所定の表示方法を使用するため、表示に問題が生じることがあります。
プログラムは microSD カードに WriteTest.txt というテキストファイルを作成して文字列を書き込み、その後カード内の 2 枚の PNG 画像を繰り返し表示します。
サンプルの実行結果を次に示します。


ToughC5 の microSD カードの例では、Arduino 標準の SD ライブラリと M5GFX ライブラリの drawPngFile を使用します。関連 API については以下のドキュメントを参照してください。