#include <TM1637.h>
#define Serial Serial1
#define CLK 10
#define DIO 11
#define led 18
#define fan 19
#define hourBtn 20 // 24
#define minBtn 17
#define sw 2
TM1637 tm(CLK, DIO);
uint8_t HH = 0;
uint8_t MM = 0;
int h = 0;
int m = 0;
int s = 60;
unsigned long timeNow = 0;
void setup(){
Serial.begin(115200);
Serial.println("Initiate...");
pinMode(led, OUTPUT);
pinMode(fan, OUTPUT);
pinMode(hourBtn, INPUT_PULLUP);
pinMode(minBtn, INPUT_PULLUP);
pinMode(sw, INPUT_PULLUP);
tm.init();
tm.set(BRIGHT_TYPICAL);
tm.display(4, 0x39); // :
}
void loop(){
// reset timer
if(!digitalRead(hourBtn) && !digitalRead(minBtn)){
HH = 0;
MM = 0;
delay(250);
}
// hour adjustment
if(!digitalRead(hourBtn)){
HH++;
if(HH > 99) HH = 0;
delay(250);
}
// minute adjustment
if(!digitalRead(minBtn)){
MM++;
if(MM >= 60) MM = 0;
delay(250);
}
if(millis() - timeNow >= 250){
timeNow = millis();
// display time
tm.display(0, HH/10);
tm.display(1, HH%10);
tm.display(2, MM/10);
tm.display(3, MM%10);
// turn of fan and light
digitalWrite(fan,0);
digitalWrite(led,0);
// sync timer
m = MM;
h = HH;
}
// when the switch is pressed
while(!digitalRead(sw)){
delay(1000);
s--;
if(s <= 0){
s = 59;
m--;
if(m < 0){
if(h > 0) {
m = 59;
h--;
}
else{
m = 0;
h = 0;
}
}
}
// fan and light will be off when the timer is over
if(h == 0 && m == 0){
digitalWrite(fan,0);
digitalWrite(led,0);
}
// turn on fan and light
else{
digitalWrite(fan,1);
digitalWrite(led,1);
}
// display time
tm.display(0, h/10);
tm.display(1, h%10);
tm.display(2, m/10);
tm.display(3, m%10);
}
}