From f8878d3c37b910d7973d3a35de673f5c141f0223 Mon Sep 17 00:00:00 2001 From: cryptogopher Date: Sun, 9 Oct 2022 20:34:25 +0200 Subject: [PATCH] Replace tone() with custom timer --- button.ino | 2 ++ metronom.ino | 38 ++++++++++++++++++++++++++++---------- 2 files changed, 30 insertions(+), 10 deletions(-) diff --git a/button.ino b/button.ino index e90ac79..a29d8c5 100644 --- a/button.ino +++ b/button.ino @@ -1,5 +1,7 @@ volatile unsigned long lastButtonPress = millis(); +// Debouncing na timerze: +// https://github.com/khoih-prog/TimerInterrupt/blob/master/examples/SwitchDebounce/SwitchDebounce.ino void initButton() { pinMode(BUTTON_PIN, INPUT_PULLUP); // Order of ISRs matter: RISING should be invoked first diff --git a/metronom.ino b/metronom.ino index 733347e..fb853f9 100644 --- a/metronom.ino +++ b/metronom.ino @@ -1,15 +1,16 @@ #include "SAMDTimerInterrupt.h" #include "SAMD_ISR_Timer.h" -#define HW_TIMER_INTERVAL_MS 10 -SAMDTimer ITimer(TIMER_TC3); -SAMD_ISR_Timer ISR_Timer; +SAMDTimer TaskTimer(TIMER_TC3); +SAMDTimer BuzzerTimer(TIMER_TC5); +SAMD_ISR_Timer TasksISRs; -void TimerHandler(void) { ISR_Timer.run(); } +void TasksHandler(void) { TasksISRs.run(); } const int COUNTDOWN = 240; const int PERIOD_MS = 1000; +const int BUZZER_FREQ = 300; const uint BUTTON_PIN = 6; const uint BUTTON_LED_PIN = 5; @@ -28,10 +29,25 @@ void setup() { initTemperature(); initTube(); - ITimer.attachInterruptInterval_MS(10, TimerHandler); - ISR_Timer.setInterval(PERIOD_MS, runMetronome); - ISR_Timer.setInterval(PERIOD_MS, readTemperature); - ISR_Timer.setInterval(PERIOD_MS, updateTube); + pinMode(BUZZER_PIN, OUTPUT); + BuzzerTimer.attachInterrupt(BUZZER_FREQ *2, buzz); + BuzzerTimer.disableTimer(); + + TaskTimer.attachInterruptInterval_MS(25, TasksHandler); + TasksISRs.setInterval(PERIOD_MS, runMetronome); + TasksISRs.setInterval(PERIOD_MS, readTemperature); + TasksISRs.setInterval(PERIOD_MS, updateTube); +} + +volatile bool buzzing = false; +void buzz() { + digitalWrite(BUZZER_PIN, buzzing ? LOW : HIGH); + buzzing = !buzzing; +} + +void stopBuzzer() { + BuzzerTimer.disableTimer(); + digitalWrite(BUZZER_PIN, LOW); } void runMetronome() { @@ -40,8 +56,10 @@ void runMetronome() { digitalWrite(BUTTON_LED_PIN, countdown % 2 ? HIGH : LOW); } else if (countdown == 0) { - //tone(BUZZER_PIN, 300, 100); + TasksISRs.setTimeout(100, stopBuzzer); + BuzzerTimer.enableTimer(); } } -void loop() {} +void loop() { +}