This example will show you how to use a potentiometer to control the volume of a Mixer object in CircuitPython. The onboard button will control playback of the audio file.
- Board 3.3V to potentiometer voltage (red wire)
- Board pin A0 to potentiometer signal (white wire)
- Board GND to potentiometer ground (black wire)
CircuitPython Code
You can access the code and necessary libraries by downloading the Project Bundle.
To do this, click on the Download Project Bundle button in the window below. It will download as a zipped folder.
# SPDX-FileCopyrightText: 2023 ladyada for Adafruit Industries
#
# SPDX-License-Identifier: MIT
import audiobusio
import audiocore
import board
import digitalio
import keypad
import analogio
import audiomixer
SOUND_FILE = "StreetChicken.wav"
power = digitalio.DigitalInOut(board.EXTERNAL_POWER)
power.switch_to_output(value=True)
analog_pin = analogio.AnalogIn(board.A0)
keys = keypad.Keys((board.BUTTON,), value_when_pressed=False)
i2s = audiobusio.I2SOut(board.I2S_BIT_CLOCK, board.I2S_WORD_SELECT, board.I2S_DATA)
music = audiocore.WaveFile(SOUND_FILE)
mixer = audiomixer.Mixer(voice_count=1, sample_rate=music.sample_rate, channel_count=1,
bits_per_sample=music.bits_per_sample, samples_signed=True)
i2s.play(mixer)
sound = False
last_pot = 0
while True:
if abs(last_pot - analog_pin.value) > 1000:
last_pot = analog_pin.value
volume = 1.0 - last_pot / 65535
print(volume)
mixer.voice[0].level = volume
if sound and not mixer.voice[0].playing:
print("Playing now!")
mixer.voice[0].play(music)
event = keys.events.get()
if event and event.pressed:
print("click")
sound = not sound
mixer.voice[0].stop()
After downloading the Project Bundle, plug your board into the computer's USB port with a known good USB data+power cable. You should see a new flash drive appear in the computer's File Explorer or Finder (depending on your operating system) called CIRCUITPY. Unzip the folder and copy the following items to the board's CIRCUITPY drive:
- lib folder
- code.py
- StreetChicken.wav
Your CIRCUITPY drive should look like this after copying the lib folder, the audio file and the code.py file:
When you press the onboard button, the audio file will either begin playing in a loop or stop. You can twist and turn the potentiometer to increase or decrease the volume of the audio playback.
Page last edited January 22, 2025
Text editor powered by tinymce.