Saving data on the SD card

Let's assume that now you need to save data to the SD card, data that can be used later offline in a PC.

Let's attach a DHT22 like we did in Chapter 3, Building a Home Thermostat with the ESP8266, and read its value and log it in file on the microSD card.

Using the same libraries for the SPI and SD card:

#include <SPI.h> 
#include <SD.h> 
#include <DHT.h> 
const int chipSelect = D8; 

Define the DHT type, since the library can work with DHT11 and DHT22:

#define DHTTYPE DHT22 
#define DHTPIN  4 
#define DEV_TYPE  "dht" 
DHT dht(DHTPIN, DHTTYPE, 11);  
float humidity, temp_f;  // Values read from sensor 

Define the function that will read the temperature and update the global variables humidity and temp_f with the humidity and temperature:

void gettemperature()  
{ 
  int runs=0; 
  do { 
       delay(2000); 
       temp_f = dht.readTemperature(false);      
       humidity = dht.readHumidity();           
 
       if(runs > 0) 
           Serial.println("##Failed to read from DHT sensor! ###"); 
       runs++; 
    } 
    while(isnan(temp_f) && isnan(humidity)); 
} 

Initialize the SD card and do the first reading for humidity and temperature:

void setup() 
{ 
  // Open serial communications and wait for port to open: 
  Serial.begin(115200); 
  Serial.print("Initializing SD card..."); 
  // see if the card is present and can be initialized: 
  if (!SD.begin(chipSelect)) { 
    Serial.println("Card failed, or not present"); 
    // don't do anything more: 
    return; 
  } 
  Serial.println("card initialized."); 
  gettemperature(); 
} 

Every three seconds, read the temperature and humidity, opening an existing file and appending the temperature in the DATALOG.TXT file. At the end, close the file:

void loop() 
{ 
  // make a string for assembling the data to log: 
  String dataString = ""; 
  gettemperature(); 
  dataString += String(temp_f); 
  // open the file. note that only one file can be open at a time, 
  // so you have to close this one before opening another.
// to write to file you need FILE_WRITE as second parameter.
// to read from the file SD.open(file_name) should be used.
File dataFile = SD.open("datalog.txt", FILE_WRITE); // if the file is available, write to it: if (dataFile) { dataFile.println(dataString); dataFile.close(); // print to the serial port too: Serial.println(dataString); } // if the file isn't open, pop up an error: else { Serial.println("error opening datalog.txt"); } delay(3000); }

Check that the microSD card on a PC shows the created file:

Open the file to view the logged data:

If your data is sensitive you can encrypt the data and then write it to the SD card. In case the SD card is lost, no one will be able to see your data.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.207.145