Hi,
I'm very much a newbie at this and I've managed to cobble together various bits of example code to almost do what I need (for now!).
Basically, I'm using a DHT22 temp/humidity sensor and want to continually record the time, date, humidity and temperature to an SD card.
I've almost got it working - and I know where the problem lies - it's in that last bit of code that tries to write the semicolon and add the leading zero (i.e. the 'printDigits' routine / whatever it's called) - I can see I'm trying to call that outside of the scope but I don't know how to fix it. My head is thumping - I've been on this all day and need some paracetamol !
Excuse the horrific code - I'm stumbling my way through this and it's a lot harder than I thought it was going to be !
Additionally, if anyone can see a far more efficient way of doing what I'm trying to do, don't be shy ! I'm here to learn ![]()
Many thanks !
#include <SD.h>
#include <Time.h>
#include "DHT.h"
#define DHTPIN 2 // what pin we're connected to
#define DHTTYPE DHT22 // DHT 22 (AM2302)
// Connect pin 1 (on the left) of the sensor to +5V
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor
DHT dht(DHTPIN, DHTTYPE);
const int chipSelect = 4;
void setup() {
Serial.begin(9600);
dht.begin();
setTime(17,22,0,22,6,13); // set time to hh,mm,ss,dd,mm,yy
Serial.print("Initializing SD card...");
// make sure that the default chip select pin is set to
// output, even if you don't use it:
pinMode(10, OUTPUT);
// 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.");
}
void loop() {
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
float t = dht.readTemperature();
delay(1000);
// check if returns are valid, if they are NaN (not a number) then something went wrong!
if (isnan(t) || isnan(h)) {
Serial.println("Failed to read from DHT");
} else {
File dataFile = SD.open("datalog.txt", FILE_WRITE);
Serial.print(h);
Serial.print(",");
Serial.println(t);
// now send the data to the SD card
if (dataFile) { //if file is able to be opened
dataFile.print(hour());
printDigits(minute());
printDigits(second());
dataFile.print(minute());
dataFile.print(" ");
dataFile.print(day());
dataFile.print(" ");
dataFile.print(month());
dataFile.print(" ");
dataFile.print(year());
dataFile.println();
dataFile.print(h); //Now follow that with the humidity & temp data
dataFile.print(",");
dataFile.println(t);
dataFile.close(); //and close the file
}
}
}
void printDigits(int digits){
// utility function for clock display: prints preceding colon and leading 0
dataFile.print(":");
if(digits < 10)
dataFile.print('0');
dataFile.print(digits);
}