Arduinoに関するメモです。

サンプルコード

  • EEPROMの読み書き
#include "Arduino.h"
#include "EEPROM.h"

typedef struct
{
  char ssid[32];
  char password[32];
} SETTINGS;

SETTINGS _settings;

void load_settings()
{
  EEPROM.get(0, _settings);
}

void save_settings()
{
  EEPROM.put(0, _settings);
  EEPROM.commit();
}

void setup()
{
  Serial.begin(115200);
  EEPROM.begin(sizeof(SETTINGS));

  //Serial.println("save settings...");
  //strcpy(_settings.ssid, "ssid");
  //strcpy(_settings.password, "password");
  //save_settings();

  Serial.println("load settings...");
  load_settings();
  Serial.printf("ssid=%s\n", _settings.ssid);
  Serial.printf("password=%s\n", _settings.password);
}

void loop()
{
}
  • SDカードの読み書き
#include "Arduino.h"
#include "FS.h"
#include "SD.h"
#include "SPI.h"

const int SDCARD_CS_PIN = 4; // M5STACK

bool read_file(const char *path, char *buffer)
{
  File file = SD.open(path);
  if (file)
  {
    int i = 0;
    while (file.available())
    {
      buffer[i] = file.read();
      i++;
    }
    buffer[i] = '\0';

    file.close();
    return true;
  }
  return false;
}

bool write_file(const char *path, char *buffer)
{
  //File file = SD.open(path, FILE_APPEND); // 追記
  File file = SD.open(path, FILE_WRITE);
  if (file)
  {
    file.print(buffer);
    file.close();
    return true;
  }
  return false;
}

void setup()
{
  Serial.begin(115200);

  if (!SD.begin(SDCARD_CS_PIN))
  {
    Serial.println("sdcard mount error.");
  }

  Serial.println("write file...");
  if (!write_file("/test.txt", "test ok?"))
  {
    Serial.println("write error.");
  }

  Serial.println("read file...");
  char buffer[512];
  if (read_file("/test.txt", buffer))
  {
    Serial.printf("buffer=%s\n", buffer);
  }
  else
  {
    Serial.println("read error");
  }
}

void loop()
{
}

参考資料

前の記事 次の記事