// TM1637 SevenSegment Counter Wokwi Example
//
// https://wokwi.com/projects/339227323398095442
#include <TM1637.h>
#include "pitches.h"
#include <math.h>
TM1637 tm(2, 3);
const int btn_set_timers[4] = {300, 1800, 7200};
const int btn_set_pins[4] = {5, 6, 7};
const int btn_mode = 4;
const int DEBOUNCE_DELAY = 50;
int lastSteadyState = HIGH; // the previous steady state from the input pin
int lastFlickerableState = HIGH; // the previous flickerable state from the input pin
int currentState; // the current reading from the input pin
unsigned long lastDebounceTime = 0; // the last time the output pin was toggled
int pot_pins[4] = {A0, A1, A2, A3};
void setup() {
tm.init();
tm.set(BRIGHT_TYPICAL);
for (byte i = 0; i < 3; i = i + 1) {
pinMode(btn_set_pins[i], INPUT_PULLUP);
}
pinMode(btn_mode, INPUT_PULLUP);
for (byte i = 0; i < 4; i = i + 1) {
pinMode(pot_pins[i], INPUT);
}
Serial.begin(9600);
noTone(8);
}
int seconds_left = 0;
static unsigned long timer = millis();
int mode = 0;
// 0 init
// 1 timer
// 2 set time from pot
// 3 beep
int lcd_show_int(int value) {
tm.display(0, (value / 1000) % 10);
tm.display(1, (value / 100) % 10);
tm.display(2, (value / 10) % 10);
tm.display(3, value % 10);
return 0;
}
void loop() {
if (mode==0) {
mode = 1;
seconds_left = 9999;
lcd_show_int(seconds_left);
timer = millis();
} else if (mode==1) {
if (millis() - timer >= 1000) {
if (seconds_left > 0) {
seconds_left -= 1;
lcd_show_int(seconds_left);
} else {
mode = 3;
}
timer += 1000;
}
} else if (mode == 3) {
tone(8, NOTE_D5);
delay(300);
noTone(8);
delay(600);
} else if (mode==2) {
int pot_value = 0;
for (byte i = 0; i < 4; i = i + 1) {
int value = analogRead( pot_pins[i] );
value = (int) round (10 * value/1024);
pot_value = pot_value + value * pow(10,i);
}
seconds_left = pot_value;
lcd_show_int(seconds_left);
}
currentState = digitalRead( btn_mode );
if (currentState != lastFlickerableState) {
lastDebounceTime = millis();
lastFlickerableState = currentState;
}
if ((millis() - lastDebounceTime) > DEBOUNCE_DELAY) {
if (lastSteadyState == LOW && currentState == HIGH) {
if (mode != 2 ) {
mode=2;
} else {
mode = 1;
timer = millis();
}
}
lastSteadyState = currentState;
}
for (byte i = 0; i < 3; i = i + 1) {
int value = digitalRead( btn_set_pins[i] );
if ( value == LOW ) {
mode = 1;
seconds_left = btn_set_timers[i];
lcd_show_int(seconds_left);
timer = millis();
}
}
}