Tutorial 3 Timer interrupts and an interactive music box game

The PSR-28N08A-JQ speaker




The Audio amplifier LM4862's datasheet



Task 1: Use the normal timer/counter mode and the serial monitor to play notes (20 points)

This task will show you how to develop an interactive interface to play music notes.
First, we are going to place the major piece of code into a function called the 'interrupt service routine' or ISR.

We will use the overflow mode, which means when the TIMER1 counter overflows, it triggers a sub-function called ISR to run a piece of code. When it finishes, it returns back to the location where it jumped to the ISR.



The ISR vector for the overflow mode is called TIMER1 OVF, in the Arduino C, the name of this vector is TIMER1_OVF_vect
Here is the example code for Task 1.

The TIMSK1 register:





Here is the hardware connection:



Install two jumpers.



Select 'No line ending' in your monitor to avoid double printing. Follow the steps in the following demo video to play all the notes on the list.





Task 2: An interactive music box game

2.1 Static Local Variables within a Function: (show results in your report) (10 points)
A static local variable retains its value between successive calls to the function where it is declared. Unlike regular local variables that are created and destroyed with each function call, a static local variable is initialized only once, the first time the function is called, and its value persists throughout the program's execution.

In the following function, although the 'counter' variable' is being declared and assgined a 0 each time myFunction() is called, it retains its value throughout out the calls which means it will increase by 1 each time it is called rather than being reset back to 0 each time.

Run the following piece of code to verify this:

void myFunction() { static int counter = 0; // Initialized once, retains value counter++; Serial.print("Counter: "); Serial.println(counter);}void setup() { Serial.begin(9600);}void loop() { myFunction(); delay(1000);}

2.2 Play the test song (20 points)

Set TIMER3's prescaler to 1:256.



Here is the code template.
The key point here is to develop the state machine. The frame of the code is already given. State transition will be covered in class. Please refer to the lecture video when you develop your state transition.

Here is the demo:



Task 2.3 Develop the music game (50 points)

From the template you can see that there are four songs stored in the 'notes[][]' list - The test song, copy song, fail song, and sccuess song.
The test song is for Task 2.2 so it won't be used here. When the user presses 'r', it triggers the gaming mode and the copy song will play. The user needs to press a button to duplicate the copy song's rythm within a reasonable error in note durations in order to trigger the success song. Otherwise, the fail song will play.

Here is the demo:



Here is the code template.