Tone Generator with a Potentiometer
Setup
- connect the tap of the potentiometer to ADC0 pin 26
- connect the ends of the potentiometer to GND and 3.3VREF
- make sure to use the GND pin that is isolated
- connect the speaker between GND and pin 15 in the lower left corner
Then load and run the code
Tone Generator Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
|
Note that the try/except is key so that whn you stop the program the PWM signal does not continue to generate sound.
Code Explanation
- We set up an ADC pin to read the potentiometer value.
- We configure a PWM output pin connected to your speaker.
- We set a 50% duty cycle for the PWM, which creates a square wave.
- In the main loop, we:
- Read the current value from the potentiometer
- Map this value to a frequency range (100Hz to 2000Hz, but you can adjust this)
- Update the PWM frequency
- Add a small delay to prevent excessive updates
When you turn the potentiometer, it changes the voltage at the ADC pin, which we read and convert to a frequency value for the PWM output.
Challenges
- Try to change the maximum frequency to be 4000Hz.
- What is the highest frequency that you can hear?
- Hook a display up to provide a visual model of a sine wave that changes the frequency