Controller.jpg (30700Bytes)
LM386_Amp.jpg (24727Bytes)
Last year I wanted to add sound to a bot so I wrote a program that plays wave files. I later rewrote it so that it would be completely interrupt driven so that I could have it play audio files while doing other tasks. While this was writhen to run on the BahBots controller it can probably modified to also work on an Arduino Mega.
Features:
- Plays 8bit wave formated audio files at up to 22ksps (stereo) or up to 44ksps (mono)
- Works on any AVR Mega part with 4k RAM or more.
- Used double buffering to overcome FAT32 file IO latency.
- Uses PWM on Timer2 for Digital to Analog Conversion (pins OC2A & OC2B)
- Uses Timer1 for sample updates
- Needs very few (or no) external parts except for the amplifier and speaker
- Used attached MicroSD card for wave files (FAT32 formated)
- Allows for many hours of audio files.
- Written in Bascom-AVR compiled Basic
Hardware used for this example:
- Bahbots controller (see: https://www.robotshop.com/letsmakerobots/node/23310 )
- 16x2 LCD Display for showing filename of the current wave file.
- Small home made audio amp based on an LM386 with a cheap speaker.
- 7.2volt Li Ion battery pack
When using the code there are two main commands, PlayWaveFile and GetWaveFileInfo. All that is needed is to play the file is the command:
PlayWaveFile “my_sound.wav”
The code will then start playing the wave file but also continue to the next line of code while its playing the file.
PlayWaveFile will also call GetWaveFileInfo when it starts playing a new file but you can use GetWaveFileInfo prior to playing the file so that you can get info about the file (I.E. Stereo or mono, Bits per second and more) before playing it.
There is a significant amount of CPU utilization when playing a stereo wave file but if you use mono and a lower bit rate (16k is good) then there is a good amount of CPU left for other tasks. Keep in mind not to bind the cpu in an interrupt or it could affect the audio quality!
Since it uses Timer2 for the PWM DAC it is not possible to play 16bit audio files. It is very easy to convert them to 8bits using Microsoft’s Sound Recorder program. Just load the original wave file, then select Save As and press the Format Change button at the bottom (make sure to use PCM as the format). You can select bit rates and stereo or mono. If using an MP3 as the original file, you will also need to first convert them to the wav file format and then use the Sound Recorder to go from 16bits to 8 bits. You can use something like Audacity for this.
The program code can me found here: http://bahbots.com/forum/viewtopic.php?f=2&t=2
Here are is a pic of the Controller showing the MicroSD and also the LM386 amplifier.
Let me know what people think and if modifications could be made to make it more useful.
-Glen
https://www.youtube.com/watch?v=2jiLZEFJQWk