// For: https://forum.arduino.cc/t/interrupt-freezes-arduino-and-stops-code-from-working/1081767
//
// Changes:
// - Using the KISS rule.
// - Changed to hd4470 library.
// - It is not possible to use I2C (interrupt driven).
// or delay() in a interrupt. Serial.print() should be avoided.
// - Interrupt at falling edge to toggle the background.
//
// Conclusion:
// This does not feel right.
// The button can be checked in the loop().
// A interrupt makes debouncing harder.
// The Encoder library can deal with the encoder:
// https://www.pjrc.com/teensy/td_libs_Encoder.html
//
#include <Wire.h>
#include <hd44780.h>
#include <hd44780ioClass/hd44780_I2Cexp.h>
hd44780_I2Cexp lcd;
// LCD geometry
const int LCD_COLS = 16;
const int LCD_ROWS = 2;
const int encoderCLK = 19;
const int encoderDT = 45;
const int encoderBtn = 18;
bool backlight = true; // the current status of the backlight
volatile bool trigger = false; // to send a trigger from interrupt routine
void setup()
{
Serial.begin(115200);
pinMode(encoderBtn, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(encoderBtn), lcd_power_toggle, FALLING);
Wire.begin(); // not really needed, lcd.begin will do this
int status = lcd.begin(LCD_COLS, LCD_ROWS); // also turn on backlight
if(status) // non zero status means it was unsuccesful
{
Serial.println("Display was not found");
}
lcd.setCursor(0, 0); // column, row
lcd.print( "To Freeze Or");
lcd.setCursor(0, 1); // column, row
lcd.print( "Not To Freeze");
}
void loop()
{
if(trigger)
{
trigger = false; // reset the trigger
backlight = !backlight; // toggle between true and false
if( backlight)
{
lcd.backlight(); // turn backlight on.
}
else
{
lcd.noBacklight(); // turn backlight off.
}
}
delay(20); // slow down the sketch, avoid button bounce trouble.
}
void lcd_power_toggle()
{
trigger = true;
}