#include <LiquidCrystal_I2C.h>
#include <Wire.h>
const int potPIN = 32;
// I2C Pins
const int sdaPIN = 21;
const int sclPIN = 22;
// I2C
#define I2C_ADRSS 0x27
#define LCD_COLUMNS 16
#define LCD_ROWS 2
// Push button
const int pushButton = 18;
int oldValue = LOW;
LiquidCrystal_I2C lcd(I2C_ADRSS, LCD_COLUMNS, LCD_ROWS);
// time
unsigned long previousTime;
unsigned long currentTime;
// LED Pins
const int redLED = 5;
// Buzzer pin
const int buzzer = 17;
// States
typedef enum {
setting,
running,
finished
} process_states_t;
// State Initialisation
process_states_t currentState = setting;
int chosenSeconds = 0;
int originalSeconds = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Wire.begin(sdaPIN, sclPIN);
pinMode(pushButton, INPUT);
pinMode(redLED, OUTPUT);
pinMode(buzzer, OUTPUT);
// Initialise LCD
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Hello!");
delay(1000);
lcd.clear();
}
void loop() {
int newValue = digitalRead(pushButton);
if (newValue != oldValue) {
if (newValue == HIGH) {
if (currentState == setting) {
currentState = running;
previousTime = millis();
lcd.clear();
} else if (currentState == running) {
currentState = setting;
lcd.clear();
}
} else if (currentState == finished) {
noTone(buzzer);
digitalWrite(redLED, LOW);
currentState = setting;
lcd.clear();
}
delay(50);
oldValue = newValue;
}
switch(currentState){
case running: {
lcd.setCursor(0, 0);
int minPart1 = chosenSeconds / 60;
int secPart1 = chosenSeconds % 60;
char buffer1[32];
sprintf(buffer1, "Ticking: %d:%02d ", minPart1, secPart1);
lcd.setCursor(0, 0);
lcd.print(buffer1);
currentTime = millis();
if (currentTime - previousTime >= 1000) {
chosenSeconds--;
previousTime = millis();
}
int progress = (chosenSeconds * 10) / originalSeconds;
lcd.setCursor(0, 1);
for (int i = 0; i < 16; i++) {
if (i < progress) {
lcd.write(255);
} else {
lcd.write(' ');
}
}
if (currentState == running && chosenSeconds == 0) {
digitalWrite(redLED, HIGH);
tone(buzzer, 256);
currentState = finished;
lcd.clear();
}
// Serial.println(myTime);
break;
}
case finished: {
lcd.setCursor(0, 0);
lcd.print("TIME UP!");
break;
}
default:
int potData = analogRead(potPIN);
int timeInSec = (potData * 3600) / 4095;
int minPart = timeInSec / 60;
int secPart = timeInSec % 60;
char buffer[32];
sprintf(buffer, "Set Time: %d:%02d ", minPart, secPart);
lcd.setCursor(0, 0);
lcd.print(buffer);
chosenSeconds = timeInSec;
originalSeconds = timeInSec;
}
}