MayFly Data Logger Code

//Sample sketch for logging light and temp/humidity data to microSD card on EnviroDIY Mayfly v1.0

//This sketch does not put the logger to sleep; it is constantly power, so it's not intended for long-term deployments


#include <Arduino.h>

#include<DHT.h>             // This library is for temp & humid sensor

#include <Wire.h>           // This library is included with the Arduino IDE, and allows communication with I2C/TWI devices

#include "Sodaq_DS3231.h"   // Install this library to interact with the Real Time Clock

#include <SD.h>             // This library is for the SD CARD

#include <SPI.h>

#include <OneWire.h>

#include <DallasTemperature.h>


//Data wire is plugged into port 7 on Mayfly

#define ONE_WIRE_BUS 7

#define SD_SS_PIN 12


#define FILE_NAME "Datafile.txt"

#define LOGGERNAME "Mayfly Light/Humidity/Temperature Logger"  

#define DATA_HEADER "DateTime_UTC,Loggertime,BatteryV,Humidity_percent,Temp_C,Water_temp,Light"

#define DHTPIN 5       // Specifies the pin connected to the DHT signal.

#define DHTTYPE DHT11   // DHT 11

DHT dht(DHTPIN, DHTTYPE);

OneWire oneWire(ONE_WIRE_BUS);

// Pass the OneWire reference to Dallas Temp

DallasTemperature sensors(&oneWire);

String dataRec = "";


int currentminute;

int  currentyear;

int  currentmonth;

int  currentdate;

int  currenthour;

long currentepochtime = 0;  

//float boardtemp = 0.0;

float lightpercent = 0;


int batteryPin = A6;        // select the input pin for the potentiometer

int batterysenseValue = 0;  // variable to store the value coming from the sensor

float batteryvoltage;       // the calculated battery voltage in volts

//****************************************************************************************************************************

//****************************************************************************************************************************

void setup ()

{


    Serial.begin(57600);

    Serial.println("Mayfly SHT40-Light Logger");

    pinMode(8, OUTPUT);

    pinMode(9, OUTPUT);

    pinMode(20, OUTPUT);

    greenred4flash();   //blink the LEDs to show the board is on    

    sensors.begin();

    Wire.begin();

    rtc.begin();

    dht.begin();  //start dht sensor


    setupLogFile();


    Serial.println("---------------EnviroDIY Mayfly: ver 1.1------------ ");

    Serial.println("|                                                  | ");

    Serial.println("|Contact: Douglas Fessler                          | ");

    Serial.println("|Date: April 21, 2022                              | ");

    Serial.println("|Email: FESSLER.DOUGLAS@GMAIL.COM                  | ");

    Serial.println("|                                                  | ");

    Serial.println("---------------------------------------------------- ");





    getNow();

    getDateTime();


}

//****************************************************************************************************************************

//****************************************************************************************************************************

void loop ()

{

     sensors. requestTemperatures();  //send command to get waterprobe temp

     float tempF = sensors.getTempFByIndex(0);

     tempF = tempF - .7;

     digitalWrite(8, HIGH);   // turn on the green LED to let you know a sample is being taken

     dataRec = createDataRecord();

     int light = analogRead(A4);     // read the analog light sensor

     lightpercent = light/10.23;     // scales light reading as a percentage

     

    // float h = dht.readHumidity();

     //float t = dht.readTemperature();

     dataRec += ",";

     addFloatToString(dataRec, dht.readHumidity(),2,2);

     dataRec += ",";

     addFloatToString(dataRec, dht.readTemperature(true),2,2);

     dataRec += ",";

     addFloatToString(dataRec, tempF,2,2);

     dataRec += ",";

     addFloatToString(dataRec, lightpercent, 2, 1);

     dataRec += light;

     delay(10);

     logData(dataRec);

     Serial.print("Data Record: ");

     Serial.println(dataRec);       // print the data record to the serial monitor

     String dataRec = "";

     digitalWrite(8, LOW);  

 

   

     delay(1000);

}

//****************************************************************************************************************************

//****************************************************************************************************************************

void setupLogFile()

{

  //Initialise the SD card

  if (!SD.begin(SD_SS_PIN))

  {

    Serial.println("Error: SD card failed to initialise or is missing.");


    for (int r=1; r <= 10; r++)   // flash the red LED 10 times to let you know there's no memory card

    {

      digitalWrite(9, HIGH);

      delay(400);

      digitalWrite(9, LOW);

      delay(200);

    }

  }


  //Check if the file already exists

  bool oldFile = SD.exists(FILE_NAME);  


  //Open the file in write mode

  File logFile = SD.open(FILE_NAME, FILE_WRITE);


  //Add header information if the file did not already exist

  if (!oldFile)

  {

    logFile.println(LOGGERNAME);

    logFile.println(DATA_HEADER);

  }


  //Close the file to save it

  logFile.close();  

}


//****************************************************************************************************************************

//****************************************************************************************************************************

void logData(String rec)

{

  //Re-open the file

  File logFile = SD.open(FILE_NAME, FILE_WRITE);


  //Write the CSV data

  logFile.println(rec);


  //Close the file to save it

  logFile.close();  

}

//****************************************************************************************************************************

//****************************************************************************************************************************

String createDataRecord()

{

    //Create a String type data record in csv format

    String data = getDateTime();

   data += ",";


    batterysenseValue = analogRead(batteryPin);

    batteryvoltage = (3.3/1023.) * 4.7 * batterysenseValue;


   data += currentepochtime;

    data += ",";


   addFloatToString(data, batteryvoltage, 4, 2);


  return data;

}

//****************************************************************************************************************************

//****************************************************************************************************************************

static void addFloatToString(String & str, float val, char width, unsigned char precision)

{

  char buffer[10];

  dtostrf(val, width, precision, buffer);

  str += buffer;

}

//****************************************************************************************************************************

//****************************************************************************************************************************

String getDateTime()

{

  String dateTimeStr;

 

  //Create a DateTime object from the current time

 DateTime dt(rtc.makeDateTime(rtc.now().getEpoch()));

 

  currentepochtime = (dt.get());    //Unix time in seconds


  currentyear = (dt.year());

  currentmonth = (dt.month());

  currentdate = (dt.date());

  currenthour = (dt.hour());

  currentminute = (dt.minute());

 

  //Convert it to a String

  dt.addToString(dateTimeStr);

  return dateTimeStr;  

}

//***************************************************************************************************************************

//***************************************************************************************************************************

// shows how long the board has been running counts up by seconds,minutes, hours

uint32_t getNow()

{

 

  currentepochtime = rtc.now().getEpoch();

  return currentepochtime;

}

//***************************************************************************************************************************

void greenred4flash()  // blink the red/green LEDs rapidly a few times at startup

{

  for (int i=1; i <= 4; i++){

  digitalWrite(8, HIGH);  

  digitalWrite(9, LOW);

  delay(50);

  digitalWrite(8, LOW);

  digitalWrite(9, HIGH);

  delay(50);

  }

  digitalWrite(9, LOW);

}