How can I use a different timer in each interrupt?
I followed a tutorial on using the <TimerOne.h> library but i'm not able to add another timer. Should I be using a different library?
Im making an automated green house, this is what I have so far. With timer2 my goal is to turn the light on for 12 hours and off for 12 hours.
Im using an Arduino mega.
#include <TimerOne.h>
//Soil moisture sensor and pumps
const int dry = 455;
const int wet = 164;
int pump1 = 6;
int pump2 = 7;
int soilMoisturePercentage;
int soilMoisture = "OFF";
//light
int light = 2;
int lightOnOrOff = "OFF";
const int systemOn = "ON";
#define active_Low;
void setup() {
Serial.begin(9600);
pinMode(light, OUTPUT);
pinMode(pump1, OUTPUT);
pinMode(pump2, OUTPUT);
Timer1.initialize(1000000);
Timer1.attachInterrupt(checkSoil);
Timer2.initialize();
Timer2.attachInterrupt(checkLight);
}
void loop() {
int sensorVal = analogRead(A0);
int soilMoisturePercentage = map(sensorVal, wet, dry, 100, 0);
Serial.print(soilMoisturePercentage);
Serial.println("%");
if(soilMoisturePercentage <=35){
soilMoisture = "ON";
}
}
void checkSoil(){
if(soilMoisture == "ON"){
digitalWrite(pump1, LOW);
soilMoisture = "OFF";
return;
}
if(soilMoisture == "OFF"){
digitalWrite(pump1, HIGH);
return;
}
}
That is seriously misguided. Timers are not designed for such long intervals. Timer0 on the AVR is already used to clock the millis() and micros() functions, and those are what you should use for an application like that. Or even, an RTC, since if you lose power, you lose track of CPU time.
That is another reason to not use timers. millis() and micros() have almost no limit of the number of things you can time using them. You could time 200 pumps if you like.
Oops -- my intention was to set the return value to true, so that one could use the timer as a flag for a test whether the routine did anything or whether it did nothing because it was too soon.
int checkMoisture(void) {
int retval = false; // for one-shot actions like if(checkDiurnal()){...}
static unsigned long previousMillis = 0;
unsigned long currentMillis = millis();
unsigned interval = 500;
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
retval = true;
int sensorVal = analogRead(A0);
int soilMoisturePercentage = map(sensorVal, wet, dry, 100, 0);
Serial.print(soilMoisturePercentage);
Serial.println("%");
if (soilMoisturePercentage <= 35) {
soilMoisture = "ON";
}
}
return retval;
}
so in loop you could count cycles or send a message, or whatever with: