Teensy Music!

Finally got Music and Lights program previously working on Arduino Uno ported over to the Teensy 3.1!

(Did this the night before the SuperBowl, so had the NFL on the brain).

The Teensy supports an add-on to the Arduino IDE (software editor) called Teensyduino.  This permits taking the same Arduino sketches and using them on the Teensy, in theory with no modifications!

Well in reality I did have to make a few updates to the code to get the same Arduino code to work on the Teensy, but they were generally very minor.  Here are the 3 changes I had to make:

1. Rename pins.

Pins used for LEDs and the Audio speaker output were renamed.  This just because the LEDs and speaker were simply hooked up to different pins than they were in the Arduino Uno incarnation.

int num_leds = 12; // WRITE HERE TOTAL NUMBER OF LEDS CONNECTED
int speaker_connect = 23; // WRITE HERE WHICH PIN THE SPEAKER IS CONNECTED TO
int leds[] = {22,21,20,19,18,17,16,15,14,13,12,11}; // WRITE HERE WHICH PIN THE LEDS ARE CONNECTED TO: 1, 2, 3, 4, 5 ....

Here is the pinout diagram showing the location of the pins for reference.  The LEDs can be connected to any of the digital pins (in gray, 0 to 23).  The speaker is driven by a PWM output (the ones in the darker pink).


2. Rename note #defines.

#define statements used to represent the musical note values had to be updated as there were conflicts with additional reserved terms in the Teensy core library.  The code already had to account for an Arduino conflict for the A notes, e.g. “A5” had to be renamed “AA5” as “A5” is reserved for port A, pin 5.   But the Teensyduino library also found conflict with C5, B5, etc. so all notes were given the new nomenclature, AAx (Note A), Abx (Note A flat), BBx (Note B), Bbx (Note B flat), etc.  This was an easy rename and maintains backward compatibility if I want to run it again on Arduino.

3. Turn off tone between notes.

The play_note function in my code had to be modified to turn off the tone() applied to a particular pin between notes.  The Arduino Uno library appeared to handle playing tones back to back of different frequencies no problem.  The Teensy required the addition of a noTone() call between notes for the songs to play back reliably.   To debug this I had the program do a musical scale to see what notes were having problems and it seemed to be randomly dependent on how many notes were in a song as to whether a note was played or not.  Definitely signing up on the Teensy forum (http://forum.pjrc.com) was very helpful to resolving this problem.  I also got a hint from the Arduino tone reference documentation on using noTone().  Again, this is backward compatible to running on the Arduino.

Overall I was pretty happy with how I was able to start using the Teensy almost right away with an existing Arduino sketch!

Here is the Sketch if you’re interested to try it:  

Must do more!