1

I'm currently trying to make a music/mpd player on the raspberry pi using toggle switches to control play/pause; next and previous.I'm quite new to python and have made the play/pause work, but cant work out what I'm doing wrong with prev/next. I'm trying to write a program that would allow me to run "mpc prev" every time that the toggle changes from on to off (or off to on), but do nothing when it is staying still in one position, only when it changes.

import RPi.GPIO as GPIO
import time
from subprocess import call
GPIO.setmode(GPIO.BCM)

GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)

x = 2    
y = True
z = True
input_state = GPIO.input(23)
while x == 2:
    if input_state == False:
        x = 1
    elif input_state == True:
        x = 0

while True:
    if y == True and x == 1:
        call(["mpc", "prev"])
        y = False
        z = True
        x = 2
    elif z == True and x == 0:
        call(["mpc", "prev"])
        z = False
        y = True
        x = 2
    else:
        x = 2

Any ideas about how my code is wrong/how to improve it would be greatly appreciated!

  • Can you proof-read the last section of your code for formatting - it looks like your elif should be indented? – goobering Aug 24 '16 at 11:20
  • oh yeah,put it in the post wrong – Meep Aug 24 '16 at 11:23
3

I think this should work:

import RPi.GPIO as GPIO
import time
from subprocess import call
GPIO.setmode(GPIO.BCM)

GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)

previous_input_state = GPIO.input(23)

while True:
    current_input_state = GPIO.input(23)
    if(previous_input_state != current_input_state):
        call(["mpc", "prev"])
        previous_input_state = current_input_state
        time.sleep(0.2)
  • that ends up just cycling through all the songs and stopping at one when it's connected/ when current input is False, but I do like the idea of a previous input state, so ill try using that instead of my long and over-complex way. – Meep Aug 24 '16 at 11:44
  • There may be some bouncing happening. I've added a delay, which might help smooth things out a little. – goobering Aug 24 '16 at 11:54
  • It works really well! Would it be also be possible for it to do nothing when it is in the state for the first time, so that it doesn't swith song as soon as its run? – Meep Aug 24 '16 at 12:03
  • Ha. Yeah, that's a cockup on my part. Updated again! – goobering Aug 24 '16 at 12:05
  • Thank you so much! I'll now have to incoporate this into my other scripts! It works perfectly! – Meep Aug 24 '16 at 12:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.