For my HappyPlayer project I needed to control the audio volume using a rotary encoder and GPIOs. I used device tree overlays for this.
The encoder used is a standard type with an additional momentary switch when you press it. It needs 4 pins:
- Common GND -> Pi GND
- Momentary switch -> GPIO 6
- Rotary switch A -> GPIO 5
- Rotary switch B -> GPIO 13
To support the devices you could write a program in C or Python that polls the GPIOs or waits for an interrupt when a GPIO changes, but there’s an easier way. You can enable a device overlay in the linux kernel for them. The pins will automatically be pulled up and will issue an input event if their state changes. Add this to your “/boot/config.txt”:
# Overlays for buttons and rotary encoder # For overlay parameters see: https://github.com/raspberrypi/linux/blob/rpi-4.19.y/arch/arm/boot/dts/overlays/README # For key codes and axes see: https://github.com/torvalds/linux/blob/v4.12/include/uapi/linux/input-event-codes.h#L64 # Rotary axis, REL_HWHEEL dtoverlay=rotary-encoder,pin_a=5,pin_b=13,relative_axis=1,linux_axis=6 # Rotary push button, KEY_MUTE dtoverlay=gpio-key,gpio=6,label="rotary-switch",keycode=113
and reboot. This will map the rotary encoder and rotary switch to two input devices “rotary@5” and “button@6” which you can test with “evtest”. Select the input device and turn / press the control and you should see events coming in.
You can now handle those events in your own program or write a custom kernel module for it. Here you can find code for a volume controller kernel module using the rotary encoder.