#define USE_TIMER_1 true
#include <LiquidCrystal_I2C.h>
#include "DHTesp.h"
#include "TimerInterrupt.h"
#include <TimerInterrupt.hpp> //https://github.com/khoih-prog/TimerInterrupt
#include <ISR_Timer.hpp> //https://github.com/khoih-prog/TimerInterrupt
#include "ISR_Timer.h"
LiquidCrystal_I2C lcd(0x27,16,2);
DHTesp dhtSensor;
ISR_Timer ISR_timer;
const int buttonPin = 2;
const int DHT_PIN = A2;
#define TIMER_INTERVAL_MS 20L
#define TIMER_INTERVAL_5S 5000L
#define TIMER_INTERVAL_HS 500L
volatile TempAndHumidity data;
volatile int buttonState;
volatile unsigned long buttonLastPressed;
bool flag = true;
void TimerHandler(){
ISR_timer.run();
}
void buttonInterrupt(){
buttonLastPressed = millis();
Serial.println("pressed at " + String(buttonLastPressed));
flag = true;
}
void get_values()
{
noInterrupts();
data = dhtSensor.getTempAndHumidity();
//Serial.println("reading at .. " + String(millis()));
interrupts();
//if not in timeout
if(flag)
print_values();
}
void print_values(){
//noInterrupts();
lcd.backlight();
lcd.setCursor(0,0);
lcd.print("Temp: " + String(data.temperature, 2) + "C");
lcd.setCursor(0,1);
lcd.print("Humidity: " + String(data.humidity, 1) + "%");
//interrupts();
}
void setup() {
lcd.init();
lcd.begin(16, 2);
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(115200);
// INIT DHT
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
// Button Interrupt
attachInterrupt(digitalPinToInterrupt(buttonPin), buttonInterrupt, CHANGE);
// Timer INIT
ITimer1.init();
if (ITimer1.attachInterruptInterval(TIMER_INTERVAL_MS, TimerHandler))
Serial.println("Starting ITimer OK, millis() = " + String(millis()));
else
Serial.println("Can't set ITimer. Select another freq. or timer");
ISR_timer.setInterval(TIMER_INTERVAL_HS, get_values);
}
void loop() {
//check timeout
if(millis() - buttonLastPressed >= TIMER_INTERVAL_5S){
lcd.clear();
lcd.noBacklight();
flag = false;
}
}