Volume control via Piicodev POT

Hiya again Josh.

This is solvable :slight_smile:
I know your new to code so I’ll keep things super basic.
Apologies in advance if I dumb it down too much.

This code using buttons below is what you’re talking about

def increase_volume():
    Popen(['amixer', 'set', 'Speaker', '5%+'])

def decrease_volume():
    Popen(['amixer', 'set', 'Speaker', '5%-'])

These are called functions and you would call them like this.

if pot_is_all_the_way_to_the_right():
   increase_volume() # does everything under the "increase_volume" definition.
elif pot_is_all_the_way_to_the_left():
   decrease_volume() # does everything under the "decrease_volume" definition.

but we can do better.


### ** UNTESTED CODE ** 
##Code stolen from: 
##https://core-electronics.com.au/guides/piicodev-potentiometer-getting-started-guide/
from PiicoDev_Potentiometer import PiicoDev_Potentiometer
from subprocess import Popen

pot = PiicoDev_Potentiometer() # Initialise the potentiometer
pot.maximum = 100 # set the range of output values
pot.minimum = 0   # if minimum or maximum are ommitted, they will default to 0 and 100 respectively

while true: #infinite loop
   #prepending f in from of the string allows us to embed variables in a string
   pot_value_as_percentage = f"{pot.value}%" 
   #set the volume to be whatever the pot's value.
   Popen(['amixer', 'set', 'Speaker', pot_value_as_percentage])

You will need to expand on this code and integrate it to your OS environment. You might also consider using BASH not python just because bash is the right level above the metal for this task. That’s just taste.

I hope this gives you a flavour of how you might proceed. :coffee:

Good luck.
Pix :heavy_heart_exclamation:

P.S.

You might also like to have the code automatically run when the raspberry pi boots up.
I tackled this a few years ago and you can follow my steps towards the bottom of this article under the heading “software”.

P.P.S

@Michael can import the piicodev micropython modules in vanilla python like I have above? (or is there a better way?) :question:

2 Likes