Volume Control startup script
-
Hi All,
Firstly I am running RPi 4.3 on a pi3 with a hifiberry mini amp and rotary encoder. What I am trying to do is get a python script to run on startup of emulationstation and then silently monitor the GPIO ports my encoder is attached to and then increase/decrease alsaaudio volume as required.
So I have coded it up ok, when I run my script on the command line I can get the script to print out the current alsa volume and then set a new volume.
What I am struggling with is how to get that script to initiate on startup and then run quietly. I added a line to rc.local that calls the script as I would on the command line. When emulation station boots it clearly calls that script as it prints out the volume ok and any tweaks to the encoder prints out to screen. However, the execution of emulation station halts. I took out of the script all of the print code incase that was causing it, but not it isn't that.
Should I be rewriting this as a daemon or something and calling that instead?
-
@bruceiow Post the contents of the file where you added your script (
/etc/rc.d/rc.local
?) -
Hi ya,
In m rc.local I put this line prior to exit 0
python /home/pi/encoder.py
This is the content of encoder.py:
from RPi import GPIO from time import sleep import alsaaudio clk = 22 dt = 23 GPIO.setmode(GPIO.BCM) GPIO.setup(clk, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(dt, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) m = alsaaudio.Mixer() vol = m.getvolume() vol1 = iter(vol) counter = vol1.next() clkLastState = GPIO.input(clk) try: while True: clkState = GPIO.input(clk) dtState = GPIO.input(dt) if clkState != clkLastState: if dtState != clkState: if counter < 100: counter += 1 else: if counter > 0: counter -= 1 print counter m.setvolume(counter) clkLastState = clkState sleep(0.01) finally: GPIO.cleanup()
-
@bruceiow Add an
&
at the end of the command you introduced, so the code is executed in background and the script does not block waiting for the program output:python /home/pi/encoder.py 2>/dev/null 1>&2 &
The more elegant solution would be to create a service for the script, something similar to https://www.raspberrypi-spy.co.uk/2015/10/how-to-autorun-a-python-script-on-boot-using-systemd/. This way you can start/stop the service when needed.
-
Thank you, that ambersand got it moving. I think I will revisit my code again as it now boots in ok, but it isn't running the code yet. I'll try the service route :)
-
Well I got it working :-)
I have created a repo on git incase anyone else needs to do this:
Contributions to the project are always appreciated, so if you would like to support us with a donation you can do so here.
Hosting provided by Mythic-Beasts. See the Hosting Information page for more information.