Pular para o conteúdo principal

Leitura/Gravação no Cartão SD

Este repositório descreve como Ler/Gravar de ou para o Cartão SD. Com isso, você consegue carregar dados do Cartão SD; uma demonstração simples será armazenar leituras de sensores no Cartão SD.

Inicializando o Cartão SD no Wio Terminal

Inclua as bibliotecas Seeed_FS como a seguir. E inicialize o Cartão SD usando: SD.begin(SDCARD_SS_PIN, SDCARD_SPI), onde SPI é usado para se comunicar com o Cartão SD no Wio Terminal.

#include <SPI.h>
#include <Seeed_FS.h>
#include "SD/Seeed_SD.h"

File myFile; //Intialise the file Class and named it myFile

void setup() {
Serial.begin(115200);
while (!Serial) {
}

Serial.print("Initializing SD card...");
if (!SD.begin(SDCARD_SS_PIN, SDCARD_SPI)) {
Serial.println("initialization failed!");
while (1);
}
Serial.println("initialization done.");

Gravando no Cartão SD

Para gravar no Cartão SD, é necessário primeiro abrir o arquivo. Existem diferentes modos para o sistema de arquivos, então é preciso indicar qual modo usar ao abrir o arquivo; os modos são os seguintes:

MODO DE ARQUIVONome Definido
WRITEFILE_WRITE
READFILE_READ
APPENDFILE_APPEND

Para abrir o arquivo, é usada a função membro da Classe File open, que recebe 2 parâmetros da seguinte forma:

open(const char *filepath, uint8_t mode = FILE_READ) //default mode is READ

Neste caso, abre-se um arquivo txt chamado test.txt e é usado FILE_WRITE. Para escrever dentro de um arquivo txt pode-se usar a função println (Classe File):

  // open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
myFile = SD.open("test.txt", FILE_WRITE); //Writing Mode

// if the file opened okay, write to it:
if (myFile) {
Serial.print("Writing to test.txt...");
myFile.println("testing 1, 2, 3."); //Writing this to the txt file
// close the file:
myFile.close();
Serial.println("done.");
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}

Observação: Um arquivo por vez, portanto feche um arquivo quando terminar.

Lendo do Cartão SD

Para ler um arquivo do Cartão SD, também é necessário abrir o arquivo. Desta vez, usando o modo FILE_READ para apenas ler o arquivo.

Usando a função membro File availble() para verificar a disponibilidade do arquivo e read() para imprimir o conteúdo dentro do arquivo.

myFile = SD.open("test.txt", FILE_READ); //Read Mode
if (myFile) {
Serial.println("test.txt:");

// read from the file until there's nothing else in it:
while (myFile.available()) {
Serial.write(myFile.read());
}
// close the file:
myFile.close();
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
}

Código Completo

#include <SPI.h>
#include <Seeed_FS.h>
#include "SD/Seeed_SD.h"

File myFile;

void setup() {
Serial.begin(115200);
while (!Serial) {
}
Serial.print("Initializing SD card...");
if (!SD.begin(SDCARD_SS_PIN, SDCARD_SPI)) {
Serial.println("initialization failed!");
while (1);
}
Serial.println("initialization done.");

// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
myFile = SD.open("test.txt", FILE_WRITE);

// if the file opened okay, write to it:
if (myFile) {
Serial.print("Writing to test.txt...");
myFile.println("testing 1, 2, 3.");
// close the file:
myFile.close();
Serial.println("done.");
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}

// re-open the file for reading:
myFile = SD.open("test.txt", FILE_READ);
if (myFile) {
Serial.println("test.txt:");

// read from the file until there's nothing else in it:
while (myFile.available()) {
Serial.write(myFile.read());
}
// close the file:
myFile.close();
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
}

void loop() {
// nothing happens after setup
}

Leitura/Gravação da Flash usando QSPI

Como a biblioteca FS foi atualizada e introduzimos SFUD nos sistemas, agora você pode acessar a Flash no Wio Terminal usando QSPI.

Código de Exemplo Completo

Este exemplo demonstra Ler/Apagar/Gravar:

#include <sfud.h>

#define SFUD_DEMO_TEST_BUFFER_SIZE 1024
static uint8_t sfud_demo_test_buf[SFUD_DEMO_TEST_BUFFER_SIZE];
static void sfud_demo(uint32_t addr, size_t size, uint8_t *data);

#define SERIAL Serial

void setup()
{
SERIAL.begin(115200);
while(!SERIAL) {};
while(!(sfud_init() == SFUD_SUCCESS));
#ifdef SFUD_USING_QSPI
sfud_qspi_fast_read_enable(sfud_get_device(SFUD_W25Q32_DEVICE_INDEX), 2);
#endif
sfud_demo(0, sizeof(sfud_demo_test_buf), sfud_demo_test_buf);
}

void loop()
{

}
/**
* SFUD demo for the first flash device test.
*
* @param addr flash start address
* @param size test flash size
* @param size test flash data buffer
*/
static void sfud_demo(uint32_t addr, size_t size, uint8_t *data) {
sfud_err result = SFUD_SUCCESS;
const sfud_flash *flash = sfud_get_device_table() + 0;
size_t i;
/* prepare write data */
for (i = 0; i < size; i++) {
data[i] = i;
}
/* erase test */
result = sfud_erase(flash, addr, size);
if (result == SFUD_SUCCESS) {
SERIAL.println("Erase the flash data finish");
} else {
SERIAL.println("Erase flash data failed");
return;
}
/* write test */
result = sfud_write(flash, addr, size, data);
if (result == SFUD_SUCCESS) {
SERIAL.println("Write the flash data finish");
} else {
SERIAL.println("Write the flash data failed");
return;
}
/* read test */
size_t BaseTime = micros();
result = sfud_read(flash, addr, size, data);
size_t CostTime = micros() - BaseTime;
if (result == SFUD_SUCCESS) {
SERIAL.println("Read the flash data success.");
SERIAL.println("Offset (h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\r\n");
for (i = 0; i < size; i++) {
if (i % 16 == 0) {
SERIAL.print("0x");
SERIAL.print(addr + i,HEX);
SERIAL.print("\t");
}
SERIAL.print(data[i],HEX);
SERIAL.print("\t");
if (((i + 1) % 16 == 0) || i == size - 1) {
SERIAL.println("");
}
}
SERIAL.println(" ");
} else {
SERIAL.println("Read the flash data failed.");
}
/* data check */
for (i = 0; i < size; i++) {
if (data[i] != i % 256) {
SERIAL.println("Read and check write data has an error.");
break;
}
}
if (i == size) {
SERIAL.println("The flash test is success.\r\n");
SERIAL.print("read costTime: ");
SERIAL.print(CostTime);
SERIAL.println(" us");
}
}
Loading Comments...