const int BUTTON_PIN = 7; // Arduino pin connected to button's pin
const int RELAY_PIN = 3; // Arduino pin connected to relay's pin
volatile bool buttonPressed = false; // Flag to indicate if button is pressed
volatile unsigned long ledOnTime = 0; // Time when LED was turned on
void setup() {
Serial.begin(9600); // initialize serial
pinMode(BUTTON_PIN, INPUT_PULLUP); // set arduino pin to input pull-up mode
pinMode(RELAY_PIN, OUTPUT); // set arduino pin to output mode
cli(); // zaustavimo prekide
TCCR1A = 0; // Set timer to normal mode
TCCR1B = (1 << WGM12) | (1 << CS11) | (1 << CS10); // Timer mode: CTC, Prescaler: 64
OCR1A = 249; // Compare match value for 1 ms
TIMSK1 = (1 << OCIE1A); // Enable timer compare interrupt
sei(); // konačno dozvolimo prekide
}
void loop() {
}
ISR(TIMER1_COMPA_vect) {
static unsigned long lastDebounceTime = 0; // Time when button was last debounced
static bool lastButtonState = HIGH; // Previous state of the button
bool buttonState = digitalRead(BUTTON_PIN);
// Debounce the button
if (buttonState != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > 50) {
if (buttonState == LOW) {
buttonPressed = true;
ledOnTime = millis();
}
}
lastButtonState = buttonState;
// Check if LED should be on
if (buttonPressed && (millis() - ledOnTime < 5000)) {
digitalWrite(RELAY_PIN, HIGH);
} else {
digitalWrite(RELAY_PIN, LOW);
buttonPressed = false;
}
}