gmc
Posts: 123
Joined: Fri Mar 09, 2012 11:31 am
Location: Cheshire, UK
Contact: Website

GPIO to start script?

Thu Aug 06, 2015 6:14 pm

I've managed to setup a headless Pi with mpc which streams internet radio and plays via my bluetooth speakers. Since this is headless I want to setup a on/off switch where when when the button is off it will run this once:

Code: Select all

mpc stop
And when the button is in the on position it will run this once:

Code: Select all

mpc play 1
I thought I could have a script running which monitors one of the GPIO pins and when it changes state then run a script to start/stop the radio. The problem is it only needs to run this once.

Any ideas on how I go about doing this?

User avatar
rpdom
Posts: 15892
Joined: Sun May 06, 2012 5:17 am
Location: Chelmsford, Essex, UK

Re: GPIO to start script?

Thu Aug 06, 2015 6:28 pm

If I understand correctly, you want something to run a command every time the switch changes, yes?

So perhaps if you set a script running that does something like this

Code: Select all

Set_up_gpio
oldstate = read_gpio
while True
    state = read_gpio
    if state != oldstate
        if state == 1
            run "on" command
        else
            run "off" command
        endif
        oldstate = state
    endif
    sleep a bit
endwhile
That's not real code, just the flow of the program. I'll let you write the code in your preferred language :)

gmc
Posts: 123
Joined: Fri Mar 09, 2012 11:31 am
Location: Cheshire, UK
Contact: Website

Re: GPIO to start script?

Thu Aug 06, 2015 6:32 pm

Thanks - just what I was looking for. I couldn't get my head around the logic but it seems pretty simple with your script.

Massi
Posts: 1691
Joined: Fri May 02, 2014 1:52 pm
Location: Italy

Re: GPIO to start script?

Thu Aug 06, 2015 6:51 pm

use interrupts instead of wasting cpu

gmc
Posts: 123
Joined: Fri Mar 09, 2012 11:31 am
Location: Cheshire, UK
Contact: Website

Re: GPIO to start script?

Thu Aug 06, 2015 6:58 pm

Good idea - will use interrupts.

User avatar
rpdom
Posts: 15892
Joined: Sun May 06, 2012 5:17 am
Location: Chelmsford, Essex, UK

Re: GPIO to start script?

Thu Aug 06, 2015 7:48 pm

It won't waste much cpu with a short sleep in there, even 0.1 second would do it.

Return to “Beginners”