Untitled
unknown
c_cpp
a year ago
2.6 kB
4
Indexable
/* Button Press Detection with Interrupts * Authors: Ron And Nitsan * Purpose: Activate LED and buzzer after a set number of button presses within a time limit */ // Pin Definitions const int BUTTON_PIN = 2; // Pin connected to the button const int LED_PIN = 5; // Pin connected to the LED const int BUZZER_PIN = 6; // Pin connected to the buzzer // Configuration const int PRESS_THRESHOLD = 5; // Number of presses required const unsigned long TIME_WINDOW = 5000; // Time limit in milliseconds // Variables volatile int pressCount = 0; // Count of button presses volatile bool buttonPressed = false; // Tracks if button press has occurred unsigned long lastPressTime = 0; // Time of last button press void setup() { Serial.begin(9600); // Initialize serial communication for debugging // Pin Modes pinMode(LED_PIN, OUTPUT); // Set LED pin as output pinMode(BUZZER_PIN, OUTPUT); // Set buzzer pin as output pinMode(BUTTON_PIN, INPUT_PULLUP); // Set button pin as input with pull-up resistor // Interrupt Setup attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), buttonPressISR, FALLING); } void loop() { // Check if the button press flag is set if (buttonPressed) { // Record time of button press and reset the flag lastPressTime = millis(); pressCount++; buttonPressed = false; // Reset the flag } // Check if enough time has passed since the last button press if (millis() - lastPressTime >= TIME_WINDOW) { pressCount = 0; // Reset press count if time limit exceeded } // Check if the required number of presses is reached if (pressCount >= PRESS_THRESHOLD) { activateAlert(); // Activate LED and buzzer pressCount = 0; // Reset press count } // Ensure LED and buzzer are turned off digitalWrite(LED_PIN, LOW); noTone(BUZZER_PIN); // Debug: Print current time Serial.print("Current time: "); Serial.println(millis()); } // Interrupt Service Routine for button press void buttonPressISR() { buttonPressed = true; // Set flag indicating button press } // Function to activate the LED and buzzer void activateAlert() { unsigned long alertStartTime = millis(); // Record start time of alert // Keep LED and buzzer on for 5 seconds while (millis() - alertStartTime < 5000) { digitalWrite(LED_PIN, HIGH); // Turn on LED tone(BUZZER_PIN, 576); // Play buzzer tone at 576 Hz } // Ensure LED and buzzer are turned off digitalWrite(LED_PIN, LOW); noTone(BUZZER_PIN); }
Editor is loading...
Leave a Comment