#include <LiquidCrystal_I2C.h>
#define MILLIS_MAX 4294967295 // = (2^32 - 1)
#define PIN_BUTTON 32
#define DISPLAY_I2C_ADDR 0x27
#define DISPLAY_WIDTH 20
#define DISPLAY_HEIGHT 4
const unsigned short debounceDelay = 50; // [ms]
const unsigned short displayTime = 2000; // [ms]
// volatile since manipulated by an ISR
volatile unsigned long currentMillis;
volatile unsigned long lastDebounceMillis; // the last time the interrupt was triggered
volatile unsigned long millisAtButtonPushed;
volatile boolean LCDOn;
bool refreshNeeded = false;
LiquidCrystal_I2C lcd( DISPLAY_I2C_ADDR, DISPLAY_WIDTH, DISPLAY_HEIGHT );
unsigned long getMillisDelta( unsigned long millisStart, unsigned long millisEnd ) {
if ( millisEnd < millisStart ) return MILLIS_MAX - millisStart + millisEnd + 1;
else return millisEnd - millisStart;
}
void IRAM_ATTR isr_falling_edge() {
currentMillis = millis();
if ( getMillisDelta(lastDebounceMillis, currentMillis) > debounceDelay ) {
millisAtButtonPushed = currentMillis;
LCDOn = true;
}
}
void setup() {
Serial.begin( 115200 );
lcd.begin( DISPLAY_WIDTH, DISPLAY_HEIGHT );
lcd.init();
lcd.backlight();
lcd.println("Hello!!");
pinMode( PIN_BUTTON, INPUT_PULLUP );
attachInterrupt( PIN_BUTTON, isr_falling_edge, FALLING );
delay(500);
lcd.noDisplay();
lcd.noBacklight();
LCDOn = false;
refreshNeeded = true;
}
void loop() {
currentMillis = millis();
if ( LCDOn ) {
if (refreshNeeded) {
lcd.init();
lcd.backlight();
lcd.println("Now you see me..");
refreshNeeded = false;
}
Serial.println( "LCD should be on..." );
if ( getMillisDelta(millisAtButtonPushed, currentMillis) > displayTime ) {
lcd.noDisplay();
lcd.noBacklight();
LCDOn = false;
refreshNeeded = true;
}
}
else Serial.println( "LCD should be off..." );
delay(1000);
}