/*
Demonstrate Timer Interrupt, Audio:
1. Install the TimerOne library by using the Library Manager in the
Arduino IDE (Sketch -> Include Library -> Manage Libraries…).
In the “Search” box enter “TimerOne” by Paul Stoffregen,
Click on the library in the search result then click the “Install” button.
Demonstrate Timer Interrupt, Audio: Using the Timer1 library,
hookup an LED and a passive piezo speaker (the one with NO white label) to digital pins.
In the loop() function, blink the LED twice per second using the delay() function. (500 msec)
Using a timer interrupt, in the ISR make a 1kHz (1 msec on/off) tone by toggling
the state of the digital pin connected to the piezo speaker.
DO NOT USE TONE() FOR THIS!
TOGGLE THE PIN LIKE THE EXAMPLES IN THE LECTURE.
What you are learning from this:
Normally delay() is a blocking function and nothing else can happen while it’s running.
Therefore, it would be impossible for you to both blink an LED
and toggle the speaker pin to make a 1kHz tone.
However, an interrupt will always immediately run no matter what else is happening.
So, the interrupt will run exactly on time since it’s hooked to a timer
and will toggle the piezo pin at exactly a 1kHz rate no matter what else is happening.
NOTE: SEEMS THAT THE ISR FOR TONE AT 1Khz slows down the delay (blink rate) for the LED
*/
#include <TimerOne.h>
//constants to hold LED and BUZZER PINS
const byte LED_Pin = 13;
const byte buzzer_Pin = 9;
int LED_delayDT = 500; //msec
// global variables to hold the LED and buzzer states
bool LED_State = LOW;
bool buzzer_State = LOW;
void setup() {
//Initialize timer1.
Timer1.initialize();
//Associate the ISR will timer1 and set the period.
int buzzer_OnTime = 1000; // (1 msec = 1KHz), interrupt timer in usec
Timer1.attachInterrupt(BuzzBuzzer, buzzer_OnTime);
//Set the LED pin as an OUTPUT
pinMode(LED_Pin, OUTPUT);
pinMode(buzzer_Pin, OUTPUT);
//Set the baud rate in bits per second
Serial.begin(9600);
}
void loop() {
delay(LED_delayDT); // this delay seems more like 5 seconds in Wokwi
blinkLED();
delay(LED_delayDT);
blinkLED();
}
// INTERRUPT SERVICE ROUTINE BuzzBuzzer at 10khz
void BuzzBuzzer(void) {
buzzer_State = !buzzer_State;
digitalWrite(buzzer_Pin, buzzer_State);
}
//function call using delay to blink LED. this just flips state and digitalWrite
void blinkLED() {
digitalWrite(LED_Pin, LED_State);
LED_State = !LED_State;
}