Files
pirate_audio/buttons.py
2022-01-30 21:33:56 +01:00

70 lines
2.1 KiB
Python
Executable File

#!/bin/env python
import signal
import RPi.GPIO as GPIO
import requests
import time
print("""buttons.py - Detect which button has been pressed
This example should demonstrate how to:
1. set up RPi.GPIO to read buttons,
2. determine which button has been pressed
Press Ctrl+C to exit!
""")
# My music server URL
url = "http://192.168.0.114:6680/mopidy/rpc"
lastpress = 0
# The buttons on Pirate Audio are connected to pins 5, 6, 16 and 24
# Boards prior to 23 January 2020 used 5, 6, 16 and 20
# try changing 24 to 20 if your Y button doesn't work.
BUTTONS = [5, 6, 16, 24]
# These correspond to buttons A, B, X and Y respectively
LABELS = ['A', 'B', 'X', 'Y']
# Set up RPi.GPIO with the "BCM" numbering scheme
GPIO.setmode(GPIO.BCM)
# Buttons connect to ground when pressed, so we should set them up
# with a "PULL UP", which weakly pulls the input signal to 3.3V.
GPIO.setup(BUTTONS, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# "handle_button" will be called every time a button is pressed
# It receives one argument: the associated input pin.
def handle_button(pin):
global lastpress
if lastpress + 1 >= time.time():
print("dubbel")
return
label = LABELS[BUTTONS.index(pin)]
print("Button press detected on pin: {} label: {}".format(pin, label))
actions = { "A": "core.playback.resume",
"B": "core.playback.pause",
"X": "core.playback.next",
"Y": "core.playback.previous" }
js1 = { "method": actions[label], "jsonrpc": "2.0", "params": {}, "id": 1 }
js2 = requests.post(url, json=js1)
uri = js2.json()["result"]
print (actions[label], label, uri)
lastpress = time.time()
# Loop through out buttons and attach the "handle_button" function to each
# We're watching the "FALLING" edge (transition from 3.3V to Ground) and
# picking a generous bouncetime of 100ms to smooth out button presses.
for pin in BUTTONS:
GPIO.add_event_detect(pin, GPIO.FALLING, handle_button, bouncetime=100)
# Finally, since button handlers don't require a "while True" loop,
# we pause the script to prevent it exiting immediately.
signal.pause()