#define BUTTON_PIN 2
#define RESET_BUTTON_PIN 3
#define LED_PIN_3 6
#define LED_PIN_2 7
#define LED_PIN_1 8
#define LED_PIN_0 9
// Verbesserte Entprell-Logik
volatile unsigned long lastInterruptTime = 0;
const unsigned long DEBOUNCE_TIME = 150; // Höherer Wert für bessere Entprellung
volatile bool flagSet = false;
void setup() {
Serial.begin(9600);
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(RESET_BUTTON_PIN, INPUT_PULLUP);
pinMode(LED_PIN_0, OUTPUT);
pinMode(LED_PIN_1, OUTPUT);
pinMode(LED_PIN_2, OUTPUT);
pinMode(LED_PIN_3, OUTPUT);
updateLEDs(0);
attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), inkrementISR, FALLING);
}
// Korrigierte ISR mit verbesserter Entprellung
void inkrementISR() {
unsigned long currentTime = millis();
// Nur wenn genug Zeit seit letztem Ereignis vergangen ist
if (currentTime - lastInterruptTime >= DEBOUNCE_TIME) {
flagSet = true;
lastInterruptTime = currentTime;
}
}
void updateLEDs(uint8_t value) {
digitalWrite(LED_PIN_0, value & 0x01);
digitalWrite(LED_PIN_1, value & 0x02);
digitalWrite(LED_PIN_2, value & 0x04);
digitalWrite(LED_PIN_3, value & 0x08);
}
// Entprellung für Reset-Taster
bool entprellen(bool &previousState, unsigned long &lastDebounceTime, int pin) {
bool currentState = digitalRead(pin);
unsigned long currentTime = millis();
if (currentState != previousState && (currentTime - lastDebounceTime >= 50)) {
lastDebounceTime = currentTime;
bool pressed = (currentState == LOW && previousState == HIGH);
previousState = currentState;
return pressed;
}
return false;
}
void loop() {
static uint8_t countValue = 0;
static bool previousResetState = HIGH;
static unsigned long lastDebounceTimeReset = 0;
if (flagSet) {
flagSet = false;
// Warte bis Prellen vorbei ist
unsigned long start = millis();
while (millis() - start < 50) {
// Warte aktiv bis 50ms vergangen sind
}
if (digitalRead(BUTTON_PIN) == LOW) {
countValue = (countValue + 1) % 16;
Serial.print("Zählwert: ");
Serial.println(countValue);
updateLEDs(countValue);
}
}
// 2. Reset-Taster verarbeiten
if (entprellen(previousResetState, lastDebounceTimeReset, RESET_BUTTON_PIN)) {
countValue = 0;
Serial.println("Zähler zurückgesetzt auf 0");
updateLEDs(countValue);
}
}