#include <Wire.h>
#include <RTClib.h>
RTC_DS3231 rtc;
byte pbNg = 4;
byte ledNg = 2;
byte pbGood = 7;
byte ledGood = 8;
bool btnNgState;
bool btnGoodState;
bool prevBtnNgState = LOW;
bool prevBtnGoodState = LOW;
bool ngButtonPressed = false;
bool goodButtonPressed = false;
unsigned long lastDebounceTimeNg = 0;
unsigned long lastDebounceTimeGood = 0;
unsigned long debounceDelay = 50; // Adjust debounce delay as needed
void setup() {
pinMode(pbNg, INPUT);
pinMode(ledNg, OUTPUT);
pinMode(pbGood, INPUT);
pinMode(ledGood, OUTPUT);
Serial.begin(115200);
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}
if (rtc.lostPower()) {
Serial.println("RTC lost power, let's set the time!");
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
}
void loop() {
// Check buttons with debounce
buttonNg();
buttonGood();
}
void buttonNg() {
// Read the state of the button
int reading = digitalRead(pbNg);
// Check if the button state has changed
if (reading != prevBtnNgState) {
// Reset the debounce timer
lastDebounceTimeNg = millis();
}
// Check if the debounce delay has passed
if ((millis() - lastDebounceTimeNg) > debounceDelay) {
// Update the button state only if there's a change after debounce
if (reading != btnNgState) {
btnNgState = reading;
// Handle button press
if (btnNgState && !ngButtonPressed) { // Button pressed, and it was not pressed before
ngButtonPressed = true;
digitalWrite(ledNg, HIGH);
Serial.print("Button Ng pressed at ");
printDateTime();
} else if (!btnNgState && ngButtonPressed) { // Button released
digitalWrite(ledNg, LOW); // Turn off the LED when button is not pressed
ngButtonPressed = false;
}
}
}
// Update the previous button state
prevBtnNgState = reading;
}
void buttonGood() {
// Read the state of the button
int reading = digitalRead(pbGood);
// Check if the button state has changed
if (reading != prevBtnGoodState) {
// Reset the debounce timer
lastDebounceTimeGood = millis();
}
// Check if the debounce delay has passed
if ((millis() - lastDebounceTimeGood) > debounceDelay) {
// Update the button state only if there's a change after debounce
if (reading != btnGoodState) {
btnGoodState = reading;
// Handle button press
if (btnGoodState && !goodButtonPressed) { // Button pressed, and it was not pressed before
goodButtonPressed = true;
digitalWrite(ledGood, HIGH);
Serial.print("Button Good pressed at ");
printDateTime();
} else if (!btnGoodState && goodButtonPressed) { // Button released
digitalWrite(ledGood, LOW); // Turn off the LED when button is not pressed
goodButtonPressed = false;
}
}
}
// Update the previous button state
prevBtnGoodState = reading;
}
void printDateTime() {
DateTime now = rtc.now();
Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.print(" ");
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();
}