Saving Data on the SD card - uraich/IoT4AQ GitHub Wiki
The SD card interface and the SPI bus
SPI
SPI stands for Serial Peripheral Interface. For more details please see the SparkFun tutorial on SPI. Just like I2C, the SPI bus is a synchronous master - slave communication interface. It uses the following signals:
SPI signal name | GPIO line on the ESP32 | extension of abbreviation | explanation |
---|---|---|---|
SCLK | GPIO 18 | Serial clock | clock for synchronous communication |
MOSI | GPIO 23 | Master Out Slave In | data line |
MISO | GPIO 19 | Master In Slave Out | data line |
CS or SS (active low) | GPIO 5 | Chip Select | selects the SPI device |
As we can see from the table, SPI does not transmit an address for the device to be accessed but it uses a chip select instead. This allows to increase transfer speed since essentially only a shift register is needed to recuperate the serial data. SPI is used when high speed is needed as for SD cards or high resolution TFT screens.
The SD card
When the IoT4AQ system is offline, data can be saved on an SD card. The ESP32 supplies the SPI hardware interface and the Arduino SDK provides the libraries needed to access the card through a VFat file system.
The SD library provides two classes: SD class and File class, which allow to
- create and remove files and directories
- check if a file exists
- open and close files for reading and writing
- read and write files
The description of the library can be found at arduino.cc/reference/en/libraries/sd/
Typically, this is what you need to do in order to write a file:
#include "FS.h"
#include "SD.h"
#include "SPI.h"
void setup() {
File measFile;
Serial.begin(115200);
if (!SD.begin()) {
Serial.println("Card mount failed");
return;
if (SD.exists("/meas.txt"))
measFile = SD.open("/meas.txt",FILE_APPEND); // append to the file
else
measFile = SD.open("/meas.txt",FILE_WRITE); // create the file
// now we can write the file
measFile.println("Hello");
measFile.close()
}