m5stack / M5Core2

M5Core2 Arduino Library
MIT License
263 stars 115 forks source link

Add check SD function, pls #66

Closed SlimRG closed 2 months ago

SlimRG commented 2 years ago

I write SD check funtion, but has no idea, how to integrate it inside your lib. Can you help me? Thanks!

Function:

bool check_SD(bool prevState, uint8_t ssPin = TFCARD_CS_PIN, SPIClass& spi = SPI, uint32_t frequency = 4000000, const char* filePath = "/.checker") {
  bool tmp_status = prevState;

  // Check inizialization of SD 
  if (!tmp_status) tmp_status = SD.begin(ssPin, spi, frequency);

  // Check type of SD
  if (tmp_status)  tmp_status = SD.cardType() != CARD_NONE;

  // Deep check (SD lib has some bugs, so it can fix them)
  if (tmp_status) {
    tmp_status = SD.exists(filePath);
    if (!tmp_status) {
      File checkFile = SD.open(filePath, FILE_WRITE);
      if (checkFile) {
        tmp_status = checkFile.write('O');
        checkFile.close();
      }
      else tmp_status = false;
    }
  }
  if (tmp_status) {
    File checkFile = SD.open(filePath, FILE_READ);
    if (checkFile) {
      tmp_status = checkFile.size();
      checkFile.close();
    }
    else tmp_status = false;
  }

  // Close SD lib if no SD found
  bool difference = tmp_status != prevState;
  if (!tmp_status && difference) SD.end();

  return tmp_status;
}

Where:

bool prevState - previous state of SD. const char* filePath - path to file for check

Tinyu-Zhao commented 2 years ago

In fact, if the SD card is not inserted, there is a relevant prompt.

image