Play a tone, or ring tone tune, to any output pin for a fixed duration or until told to stop.
This will output a square wave of 50% duty cycle to any digital I/O Pin and requires the exclusive use of a timer. Multiple tone generators can be created but each one will require its own timer. In order to allow the output to be sent to any output pin then the pin toggling is done via software and hence the frequency range is limited to the audible spectrum.
Note that you must NOT connect a loudspeaker directly to the output pin as you will blow the pin. The reason being that for +5V micro processor and an 8Ω speaker then the current will be 5/8 = 625mA which is way in excess of the typical 40mA that a typical pin can provide.
The solution is to add a resistor in series with the loudspeaker. A value between 150Ω and 1kΩ would do the trick. Just don't expect a 'ghetto blaster' in terms of volume. For example: for +5v processor and using a 150Ω resistor with an 8Ω speaker then (roughly):
- total resistance = 150 + 8 = 158Ω
- total current = 5v / 158Ω = 32mA (which is within the ability of most processors)
- voltage across speaker = 5v * (8Ω / 158Ω) = 0.253V
- power for speaker = 32mA * 0.253V = 8mW
You can mix the outputs of multiple tone players into one speaker by adding a resistor from each output pin to one speaker connection and then connecting the other speaker connection to ground.
Whilst the tone player can play a range of different frequencies then there are some shortcuts defined in tone.h for different musical notes/octaves. Open up that file to see what they are called.
- attach - Attach a callback function that is called when the current tone has stopped playing.
- detach - Remove any callback registered with this tone player.
- isPlaying - Return TRUE if a tone or tune is currently playing or FALSE if not.
- play - Play a single tone or a whole tune.
- stop - Stop playing the current tone or tune.