Reputation: 63
I'm using this python script:
import RPi.GPIO as GPIO
import subprocess
from time import sleep
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(25, GPIO.OUT, initial=GPIO.LOW)
try:
while True:
if GPIO.input(4):
GPIO.output(25, 1)
subprocess.call("/script/start.sh", shell=True)
else:
GPIO.output(25, 0)
subprocess.call("/script/stop.sh", shell=True)
sleep(0.2)
finally:
GPIO.cleanup()
(Without subprocess) when I press the button (GPIO 4) an LED goes on, press it again and it's off. Works great. I'm currently using 2 scripts to start and stop an application. Those work fine when used outside of Python. When I try to implement the subprocess stuff things start to go wonky.
The scripts are:
#!/bin/bash
FILENAME=$(date +"%Y%m%d_%H%M")
rec -c 2 -b 24 -r 48000 -C 320.99 /mnt/usb/${FILENAME}.mp3
exit
and
#!/bin/bash
reco=`pidof -s rec`
kill $reco
exit
The process will be started, and it'll keep running, but the python script won't shut it down unless I hit ctrl+c, defeating the point of using the GPIO switch.
What I want to achieve is:
switch = high -> application starts
switch = low -> application stops
Wait/loop so I can start recording again if I press the switch.
How can I get this working properly?
Upvotes: 0
Views: 4051
Reputation: 2389
Since you're trying to kill the process you start in start.sh
. This is what I recommend:
import RPi.GPIO as GPIO
import signal
import subprocess
import os
from time import sleep
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(25, GPIO.OUT, initial=GPIO.LOW)
rec_proc = None
try:
while True:
if GPIO.input(4):
GPIO.output(25, 1)
if rec_proc is None:
rec_proc = subprocess.Popen("/script/start.sh",
shell=True, preexec_fn=os.setsid)
else:
GPIO.output(25, 0)
if rec_proc is not None:
os.killpg(rec_proc.pid, signal.SIGTERM)
rec_proc = None
sleep(0.2)
finally:
GPIO.cleanup()
Upvotes: 1