#include <TM1637.h>
const int CLK = 2;
const int DIO = 3;
const int INCREMENT_BUTTON_PIN = 9; // Increment button pin
const int START_BUTTON_PIN = 10; // Start button pin
const int VALVE_PIN = 11; // Valve control pin
TM1637 tm(CLK, DIO);
void setup() {
tm.init();
tm.set(BRIGHT_TYPICAL);
pinMode(INCREMENT_BUTTON_PIN, INPUT_PULLUP); // Configure increment button pin as input with pull-up
pinMode(START_BUTTON_PIN, INPUT_PULLUP); // Configure start button pin as input with pull-up
pinMode(VALVE_PIN, OUTPUT); // Configure valve pin as output
pinMode(12, OUTPUT);
digitalWrite(VALVE_PIN, LOW); // Ensure valve is off initially
digitalWrite(12, HIGH);
}
unsigned int counter = 0;
bool lastIncrementButtonState = LOW;
bool currentIncrementButtonState;
bool lastStartButtonState = LOW;
bool currentStartButtonState;
bool timerRunning = false;
unsigned long timerStartTime = 0;
void loop() {
// Read the increment button state
currentIncrementButtonState = digitalRead(INCREMENT_BUTTON_PIN);
// Check for increment button press (falling edge)
if (lastIncrementButtonState == HIGH && currentIncrementButtonState == LOW && !timerRunning) {
counter++;
if (counter == 10000) {
counter = 0; // Reset counter after 9999
}
}
// Read the start button state
currentStartButtonState = digitalRead(START_BUTTON_PIN);
// Check for start button press (falling edge) and counter >= 15
if (lastStartButtonState == HIGH && currentStartButtonState == LOW && !timerRunning && counter >= 15) {
timerRunning = true;
timerStartTime = millis();
digitalWrite(VALVE_PIN, HIGH); // Turn on the valve
digitalWrite(12, LOW);
}
// Update the display if timer is not running
if (!timerRunning) {
tm.display(0, (counter / 1000) % 10);
tm.display(1, (counter / 100) % 10);
tm.display(2, (counter / 10) % 10);
tm.display(3, counter % 10);
} else {
// Handle countdown timer
unsigned long elapsedTime = (millis() - timerStartTime) / 1000;
if (elapsedTime < 30) {
int remainingTime = 30 - elapsedTime;
tm.display(0, (remainingTime / 1000) % 10);
tm.display(1, (remainingTime / 100) % 10);
tm.display(2, (remainingTime / 10) % 10);
tm.display(3, remainingTime % 10);
} else {
// Reset after timer ends
counter = 0;
timerRunning = false;
digitalWrite(VALVE_PIN, LOW); // Turn off the valve
digitalWrite(12, HIGH);
}
}
// Save the current button states for the next loop
lastIncrementButtonState = currentIncrementButtonState;
lastStartButtonState = currentStartButtonState;
// Debounce delay
delay(30);
}