This is a very (very) simple Arduino sketch to control playing media with physical buttons. It uses 3 pins on the Arduino (Leonardo in my case) to control media next, media previous, and media play/pause. It has been tested on Linux and Android, but it should work on anything that can use a usb HID. This sketch depends on HID-Project by NicoHood, which can be installed from the library manager in the IDE.
Download: Zipped .ino
media_control.zip MD5: 0e59c85f7c5114792aa8e33371f72107
// Media control buttons
// 09/13/2020 grim@shnisugah.com
#include "HID-Project.h"
const int buttons[] = {7, 8, 9};
const int debounce = 300;
int readkey() {
int buttonstate;
for (int i=0; i<3; i++) {
buttonstate = digitalRead(buttons[i]);
if (buttonstate == 0) {
return buttons[i];
}
}
return 0;
}
void keydec(int key) {
if (key == buttons[0]) {
// previous
Consumer.write(MEDIA_PREVIOUS);
}
if (key == buttons[1]) {
// playpause
Consumer.write(MEDIA_PLAY_PAUSE);
}
if (key == buttons[2]) {
// next
Consumer.write(MEDIA_NEXT);
}
}
void setup() {
for (int i=0; i<3; i++) {
pinMode(buttons[i], INPUT_PULLUP);
}
Consumer.begin();
}
void loop() {
int kstat = readkey();
if ( kstat > 0 ) {
keydec(kstat);
delay(debounce);
}
}