Rotary encoder via GPIO (Digital Volume Control)

This short guide and python script is adapted from the Savetheclocktower project found on GitHub


This script is for those who want a physical volume button on a Recalbox project, like arcade machines. This script is useful for arcade terminals with speakers that do not have their own physical volume knob, or that would have difficulty moving the speaker control knob near the user.

This script uses a standard 5-pin rotary encoder and has been tested on Adafruit's encoder. 5 wires are required for this rotary encoder :

  • three for the button part (A, B and ground).

  • two for the key part (common and ground)

Here is a reference for the Raspberry Pi GPIO pins :



Board #

button A



button B



ground button

ground pin below the GPIO 26


common key



ground key

ground pin facing the GPIO 13


You can use the pins you want; just update the script if you change them. If you don't have a push button in your rotary encoder, leave the pins unoccupied. Any ground pin can be used, these pins are just suggested because of their proximity.

Volume daemon

The script below works as follows : it uses the specified pins, and when the knob is rotated in any way, uses the states of pins A and B to determine whether the knob has been rotated left or right. Thus, it knows whether to increase or decrease the volume of the system in response, which it does with the Amixer command line program.

  1. To install the script in your Recalbox: You must first connect to your Recalbox via ssh like this.

  2. Mount the partition read-write : mount -o remount, rw /

  3. Create/edit your script in /recalbox/scripts via nano : nano /recalbox/scripts/

  4. Copy and paste the bottom script into the file, then save the file with Ctrl+X :

    #!/usr/bin/env python2
    The daemon responsible for changing the volume in response to a turn or press
    of the volume knob.
    The volume knob is a rotary encoder. It turns infinitely in either direction.
    Turning it to the right will increase the volume; turning it to the left will
    decrease the volume. The knob can also be pressed like a button in order to
    turn muting on or off.
    The knob uses two GPIO pins and we need some extra logic to decode it. The
    button we can just treat like an ordinary button. Rather than poll
    constantly, we use threads and interrupts to listen on all three pins in one
    import os
    import signal
    import subprocess
    import sys
    import threading
    from RPi import GPIO
    from multiprocessing import Queue
    DEBUG = False
    # ========
    # The two pins that the encoder uses (BCM numbering).
    GPIO_A = 26
    GPIO_B = 19
    # The pin that the knob's button is hooked up to. If you have no button, set
    # this to None.
    GPIO_BUTTON = 13
    # The minimum and maximum volumes, as percentages.
    # The default max is less than 100 to prevent distortion. The default min is
    # greater than zero because if your system is like mine, sound gets
    # completely inaudible _long_ before 0%. If you've got a hardware amp or
    # serious speakers or something, your results will vary.
    VOLUME_MIN = 60
    VOLUME_MAX = 96
    # The amount you want one click of the knob to increase or decrease the
    # volume. I don't think that non-integer values work here, but you're welcome
    # to try.
    # When the knob is turned, the callback happens in a separate thread. If
    # those turn callbacks fire erratically or out of order, we'll get confused
    # about which direction the knob is being turned, so we'll use a queue to
    # enforce FIFO. The callback will push onto a queue, and all the actual
    # volume-changing will happen in the main thread.
    QUEUE = Queue()
    # When we put something in the queue, we'll use an event to signal to the
    # main thread that there's something in there. Then the main thread will
    # process the queue and reset the event. If the knob is turned very quickly,
    # this event loop will fall behind, but that's OK because it consumes the
    # queue completely each time through the loop, so it's guaranteed to catch up.
    EVENT = threading.Event()
    def debug(str):
    if not DEBUG:
    class RotaryEncoder:
    A class to decode mechanical rotary encoder pulses.
    Ported to RPi.GPIO from the pigpio sample here:
    def __init__(self, gpioA, gpioB, callback=None, buttonPin=None, buttonCallback=None):
    Instantiate the class. Takes three arguments: the two pin numbers to
    which the rotary encoder is connected, plus a callback to run when the
    switch is turned.
    The callback receives one argument: a `delta` that will be either 1 or -1.
    One of them means that the dial is being turned to the right; the other
    means that the dial is being turned to the left. I'll be damned if I know
    yet which one is which.
    self.lastGpio = None
    self.gpioA = gpioA
    self.gpioB = gpioB
    self.callback = callback
    self.gpioButton = buttonPin
    self.buttonCallback = buttonCallback
    self.levA = 0
    self.levB = 0
    GPIO.setup(self.gpioA, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(self.gpioB, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.add_event_detect(self.gpioA, GPIO.BOTH, self._callback)
    GPIO.add_event_detect(self.gpioB, GPIO.BOTH, self._callback)
    if self.gpioButton:
    GPIO.setup(self.gpioButton, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.add_event_detect(self.gpioButton, GPIO.FALLING, self._buttonCallback, bouncetime=500)
    def destroy(self):
    def _buttonCallback(self, channel):
    def _callback(self, channel):
    level = GPIO.input(channel)
    if channel == self.gpioA:
    self.levA = level
    self.levB = level
    # Debounce.
    if channel == self.lastGpio:
    # When both inputs are at 1, we'll fire a callback. If A was the most
    # recent pin set high, it'll be forward, and if B was the most recent pin
    # set high, it'll be reverse.
    self.lastGpio = channel
    if channel == self.gpioA and level == 1:
    if self.levB == 1:
    elif channel == self.gpioB and level == 1:
    if self.levA == 1:
    class VolumeError(Exception):
    class Volume:
    A wrapper API for interacting with the volume settings on the RPi.
    def __init__(self):
    # Set an initial value for last_volume in case we're muted when we start.
    self.last_volume = self.MIN
    def up(self):
    Increases the volume by one increment.
    return self.change(self.INCREMENT)
    def down(self):
    Decreases the volume by one increment.
    return self.change(-self.INCREMENT)
    def change(self, delta):
    v = self.volume + delta
    v = self._constrain(v)
    return self.set_volume(v)
    def set_volume(self, v):
    Sets volume to a specific value.
    self.volume = self._constrain(v)
    output = self.amixer("set 'PCM' unmute {}%".format(v))
    return self.volume
    def toggle(self):
    Toggles muting between on and off.
    if self.is_muted:
    output = self.amixer("set 'PCM' unmute")
    # We're about to mute ourselves, so we should remember the last volume
    # value we had because we'll want to restore it later.
    self.last_volume = self.volume
    output = self.amixer("set 'PCM' mute")
    if not self.is_muted:
    # If we just unmuted ourselves, we should restore whatever volume we
    # had previously.
    return self.is_muted
    def status(self):
    if self.is_muted:
    return "{}% (muted)".format(self.volume)
    return "{}%".format(self.volume)
    # Read the output of `amixer` to get the system volume and mute state.
    # This is designed not to do much work because it'll get called with every
    # click of the knob in either direction, which is why we're doing simple
    # string scanning and not regular expressions.
    def _sync(self, output=None):
    if output is None:
    output = self.amixer("get 'PCM'")
    lines = output.readlines()
    if DEBUG:
    strings = [line.decode('utf8') for line in lines]
    last = lines[-1].decode('utf-8')
    # The last line of output will have two values in square brackets. The
    # first will be the volume (e.g., "[95%]") and the second will be the
    # mute state ("[off]" or "[on]").
    i1 = last.rindex('[') + 1
    i2 = last.rindex(']')
    self.is_muted = last[i1:i2] == 'off'
    i1 = last.index('[') + 1
    i2 = last.index('%')
    # In between these two will be the percentage value.
    pct = last[i1:i2]
    self.volume = int(pct)
    # Ensures the volume value is between our minimum and maximum.
    def _constrain(self, v):
    if v < self.MIN:
    return self.MIN
    if v > self.MAX:
    return self.MAX
    return v
    def amixer(self, cmd):
    p = subprocess.Popen("amixer {}".format(cmd), shell=True, stdout=subprocess.PIPE)
    code = p.wait()
    if code != 0:
    raise VolumeError("Unknown error")
    return p.stdout
    if __name__ == "__main__":
    gpioA = GPIO_A
    gpioB = GPIO_B
    gpioButton = GPIO_BUTTON
    v = Volume()
    def on_press(value):
    print("Toggled mute to: {}".format(v.is_muted))
    # This callback runs in the background thread. All it does is put turn
    # events into a queue and flag the main thread to process them. The
    # queueing ensures that we won't miss anything if the knob is turned
    # extremely quickly.
    def on_turn(delta):
    def consume_queue():
    while not QUEUE.empty():
    delta = QUEUE.get()
    def handle_delta(delta):
    if v.is_muted:
    if delta == 1:
    vol = v.up()
    vol = v.down()
    print("Set volume to: {}".format(vol))
    def on_exit(a, b):
    debug("Volume knob using pins {} and {}".format(gpioA, gpioB))
    if gpioButton != None:
    debug("Volume button using pin {}".format(gpioButton))
    debug("Initial volume: {}".format(v.volume))
    encoder = RotaryEncoder(GPIO_A, GPIO_B, callback=on_turn, buttonPin=GPIO_BUTTON, buttonCallback=on_press)
    signal.signal(signal.SIGINT, on_exit)
    while True:
    # This is the best way I could come up with to ensure that this script
    # runs indefinitely without wasting CPU by polling. The main thread will
    # block quietly while waiting for the event to get flagged. When the knob
    # is turned we're able to respond immediately, but when it's not being
    # turned we're not looping at all.
    # The 1200-second (20 minute) timeout is a hack; for some reason, if I
    # don't specify a timeout, I'm unable to get the SIGINT handler above to
    # work properly. But if there is a timeout set, even if it's a very long
    # timeout, then Ctrl-C works as intended. No idea why.
  5. Make the script executable : chmod +x /recalbox/scripts/

  6. To enable the volume control script starting with your system, follow these steps:touch ~/ && chmod u+x ~/

  7. Open the script in the nano editor :nano ~/

  8. Finally, copy and paste the following into the file and save with Ctrl+X :python /recalbox/scripts/

  9. Reboot your Recalbox using the command : reboot

  10. Take advantage of the new volume control for your hardware :)

Script Modifications

These changes can all be found under the "Settings" section of the script.

Tip : Please wait 3 seconds after the Emulations menu appears BEFORE touching the rotary encoder. Rotating the encoder earlier may block the script and make the encoder insensitive.

If you want to change the two default pins used by the encoder, change the following lines in the script. Be sure to use the BCM numbering codes.

GPIO_A = 26

GPIO_B = 19

If you want to change the pin to which the push button is hooked, then change the corresponding line in the script below. Be sure to use the BCM numbering codes. If you don't have a button, set this parameter to None.


If you want to change the volume range (i.e.: min & max) that the script modulates on the Raspberry Pi, then edit the corresponding lines in the script below. The figures are expressed as a percentage. The default max is less than 100 to avoid distortion. The default min is greater than zero because if your system is like mine, the sound becomes completely inaudible long before 0%. Depending on your hardware amplifier or quality of your speakers (or something else maybe), your results may vary.



If you want the volume of your system to change faster and be more sensitive, change the corresponding line in the script below.

The default setting is 1, change to 2 to double the rate of volume change.


How to uninstall the script

Repeat steps 7 and 8 above, but deleting the line added in step 8 or commenting on it by adding a hash, e.g. :

#python /recalbox/scripts/


I would like to thank Substring for their help in making this guide and the modification of Recalbox possible.

I would also like to thank the other developers of Recalbox for making this wonderful project available.

And I would like to thank savetheclocktower for the original project code and for his help in converting to Python2.