While toying with PWM I connected a speaker to my Netduino. I got some noise from it in no-time, but regulated sounds was a challenge. I got some help from a good friend of me and with his help I crafted the attached class. Driving it is very simple if you are familiar with ancient BASIC-dialects.
For my example I connected an old PC-speaker to pin 9 and ground.
First we need to initialize the speaker:
Speaker PCSpeaker = new Speaker(Pins.GPIO_PIN_D9);Then we have three methods, as mentioned before I took the syntax from BASIC.
For a simple beep:
PCSpeaker.Beep();
To produce a 440 hertz tone for 5 ticks:
PCSpeaker.Sound(440, 5);
To play a simple melody:
PCSpeaker.Play("cdec cdec"); // Are you sleeping? Are you sleeping? PCSpeaker.Play("efg efg"); // Brother John, Brother John, PCSpeaker.Play("gagfec gagfec"); // Morning bells are ringing! Morning bells are ringing! PCSpeaker.Play("c<g>c c<g>c"); // Ding, dang, dong. Ding, dang, dong.
The syntax of the Play-method is the same as in BASIC and according to the Music Macro Language. Here's a summary:
// Octave and tone commands: // Ooctave Sets the current octave (0 - 6). // < or > Moves up or down one octave. // A - G Plays the specified note in the current octave. // Nnote Plays a specified note (0 - 84) in the seven octave // range (0 is a rest). // // Duration and tempo commands: // Llength Sets the length of each note (1 - 64). L1 is whole note, // L2 is half note, etc. // ML Sets music legato. // MN Sets music normal. // MS Sets music staccato. // Ppause Specifies a pause (1 - 64). P1 is a whole-note pause, // P2 is a half-note pause, etc. // Ttempo Sets the tempo in quarter notes per minute (32 - 255). // // Suffix commands: // # or + Turns preceding note into a sharp. // - Turns preceding note into a flat. // . Plays the preceding note 3/2 as long as specified.
After this class was done I made a simple keyboard, see this video for more details:
http://www.youtube.com/watch?v=m0FUJ579bp0
In QBasic there were a lot of people who liked to put up some (part of) songs, I found these quite nice:
- http://www.madhouseb...iew&view=qbasic
- http://www.network54...asic Play Music
- http://www.scribd.co...irit-Qbasic-txt
You can just use these strings for the Speaker.Play()-method to get the same result!
Downloads:
- Speaker.zip (Just the driver and a very simple sample project)
- NetduinoKeyboard.zip (The keyboard-project from the movie)