// Fnu Shoaib Ahmed, 652420658, fahme8
// Lab 8 - Interrupt Service Routines (ISR)
// Description - This code uses interrupts to handle button presses and toggles between two states on an LCD.
// It displays elapsed time in the default state and scrolls a message when an interrupt is triggered.
// Assumptions - Buttons use pull-up resistors; pins 2 and 3 are used for interrupts as required by the lab.
// References - I used prelab links for understanding Interrupt Service Routines (ISR) and I used Lab 3 for scrolling functionality.
#include <LiquidCrystal.h>
// Pin definitions
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 6, d7 = 7;
const int buttonPin1 = 2; // Interrupt 0 (pin 2)
const int buttonPin2 = 3; // Interrupt 1 (pin 3)
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
volatile int state = 0;
unsigned long startTime = 0;
unsigned long lastUpdateTime = 0; // For tracking the last display update
unsigned long scrollUpdateTime = 0; // For scrolling timing
void setup() {
lcd.begin(16, 2);
pinMode(buttonPin1, INPUT_PULLUP);
pinMode(buttonPin2, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(buttonPin1), button1ISR, FALLING);
attachInterrupt(digitalPinToInterrupt(buttonPin2), button2ISR, FALLING);
startTime = millis();
}
void loop() {
if (state == 0) {
// Update every second to avoid unnecessary refreshing
if (millis() - lastUpdateTime >= 1000) {
lastUpdateTime = millis();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("System on for: ");
lcd.setCursor(0, 1);
lcd.print((millis() - startTime) / 1000);
lcd.print(" seconds");
}
}
else if (state == 1) {
// Scroll the message in State 1
if (millis() - scrollUpdateTime >= 500) { // Adjust delay to control scroll speed
scrollUpdateTime = millis();
lcd.scrollDisplayLeft();
}
}
}
void button1ISR() {
state = 1;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Interrupt received!");
lcd.setCursor(0, 1);
lcd.print("Press button 2 to continue");
scrollUpdateTime = millis(); // Reset scroll timer
}
void button2ISR() {
if (state == 1) {
startTime = millis(); // Reset timer
state = 0;
lastUpdateTime = millis(); // Reset display update time
lcd.clear();
}
}