Skip to content

Instantly share code, notes, and snippets.

@bhouston
Created December 28, 2018 12:41
Show Gist options
  • Save bhouston/c6222bea997cad9c2c18a0423ead07ef to your computer and use it in GitHub Desktop.
Save bhouston/c6222bea997cad9c2c18a0423ead07ef to your computer and use it in GitHub Desktop.
#include <SPI.h>
#include <SD.h>
const int chipSelect = 4;
const int waterPumpRelayPin = 8;
const int moisture_minimum = 400;
const int watering_delay = 1000;
const int loop_delay_minutes = 5;
const int loop_delay = 60 * 1000 * loop_delay_minutes;
int loopCount = 0;
void setup_serial();
void setup_sd();
void log_line( String text );
void setup() {
setup_serial();
setup_sd();
pinMode(waterPumpRelayPin, OUTPUT);
log_line( "Moisture minimum: " + String( moisture_minimum ) );
}
void setup_serial() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.println("Serial connected.");
}
void setup_sd() {
Serial.println("Initializing SD card...");
// see if the card is present and can be initialized:
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
Serial.println("End of program." );
while( 1 ) { ; };
}
Serial.println("card initialized.");
}
void loop() {
log_line("Loop #" + String( loopCount ) );
loopCount ++;
int moisture_reading = analogRead( 0 );
log_line( "Moisture sensor: " + String( moisture_reading ) );
if( moisture_reading > moisture_minimum ) {
log_line( "Watering time: " + String( watering_delay ) );
digitalWrite(waterPumpRelayPin, HIGH);
delay(1000);
digitalWrite(waterPumpRelayPin, LOW);
}
log_line( "Loop delay: " + String( loop_delay ) );
delay( loop_delay );
}
void log_line( String text ) {
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
File dataFile = SD.open("datalog.txt", FILE_WRITE);
// if the file is available, write to it:
if (dataFile) {
dataFile.println(text);
dataFile.close();
// print to the serial port too:
Serial.println("Logging: " + text);
}
// if the file isn't open, pop up an error:
else {
Serial.println("Error opening datalog.txt");
Serial.println("End of program." );
while( 1 ) { ; };
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment