-
1Step 1
To use the Volume Control library, there are a few prerequisites:
- An ATmega168/328p / based Arduino at 16Mhz
- A fairly recent version of the Arduino IDE
- The Volume Control library itself
- A small speaker or piezo
-
2Step 2
With all of these things ready, follow this tutorial to install the .zip library where the Arduino IDE can see it.
-
3Step 3
The most basic example to get Volume control working is as follows:
#include "Volume.h" // Include the Volume library Volume vol(6); // Plug your speaker into Pin 5 or 6 void setup() { vol.begin(); } void loop() { // vol.delay() replaces the standard delay function (Timer0's prescaler has been altered, throwing the default delay() 64 x faster!) vol.tone(1000, 255); // 100% volume vol.delay(1000); vol.tone(1000, 192); // 75% volume vol.delay(1000); vol.tone(1000, 127); // 50% volume vol.delay(1000); vol.tone(1000, 51); // 20% volume vol.delay(1000); vol.tone(1000, 12); // 5% volume vol.delay(1000); }
-
4Step 4
After plugging in a speaker from Pin 6 to GND, you should hear 1KHz tone at several volume levels!
-
5Step 5
Some things you should know:
- 16 Mhz only! This does not seem to work at 8MHz, because of the speed needed for the ultrasonic PWM.
- Only confirmed working on ATmega168/328/p/b. (Uno)
- Only pins 5 & 6 can be used. This is because their PWM is tied to the high-speed Timer0.
- The function arguments for vol.tone() are NOT the same as the standard tone(). Read more about this on the GitHub README.
- This uses Timer0 and Timer1. Timer0 is normally used for timekeeping like delay() and millis(), but by changing it's clock prescaler for ultrasonic PWM the standard delay() function runs 64x faster! To fix this, use vol.delay() instead which fixes this mathematically behind the scenes.
Discussions
Become a Hackaday.io Member
Create an account to leave a comment. Already have an account? Log In.
How do you stop the sound from playing.
I tried to stop the sound with noTone but it kept playing. I figured out you can stop it by setting the volume to 0 but that doesn't work for the project i'm doing.
Are you sure? yes | no
Awesome !
I need such a thing to drive a speaker (to be a metronome) on a DIY eDrum.
I'd like to drive it via a transistor , to allow more current than the 20mA allowed by the Atmega ? Is that possible ?
Are you sure? yes | no
Should be fine! The high-speed PWM frequency used is 62,500Hz, which is higher than your hearing range, and lower than the upper limits of most transistors. :)
Are you sure? yes | no