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!

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

1 Answer 1

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) 
7
  • 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
    CommentedAug 24, 2016 at 11:44
  • There may be some bouncing happening. I've added a delay, which might help smooth things out a little.
    – goobering
    CommentedAug 24, 2016 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
    CommentedAug 24, 2016 at 12:03
  • Ha. Yeah, that's a cockup on my part. Updated again!
    – goobering
    CommentedAug 24, 2016 at 12:05
  • Thank you so much! I'll now have to incoporate this into my other scripts! It works perfectly!
    – Meep
    CommentedAug 24, 2016 at 12:18

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.