使用 RPi GPIO 在 python 内启动和停止应用程序?

Start and stop application within python using the RPi GPIO?

我正在使用这个 python 脚本:

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()

(没有子进程)当我按下按钮(GPIO 4)时,LED 亮起,再次按下它,它就熄灭了。效果很好。我目前正在使用 2 个脚本来启动和停止应用程序。这些在 Python 之外使用时工作正常。当我尝试实现子流程时,事情开始变得不稳定。

脚本是:

#!/bin/bash
FILENAME=$(date +"%Y%m%d_%H%M")
rec -c 2 -b 24 -r 48000 -C 320.99 /mnt/usb/${FILENAME}.mp3
exit

#!/bin/bash
reco=`pidof -s rec`
kill $reco
exit

进程将启动,它会保持 运行,但 python 脚本不会关闭它,除非我按 ctrl+c,破坏了使用 GPIO 的意义切换。

我要实现的是:

switch = high -> application starts
switch = low -> application stops

Wait/loop这样一按开关就可以重新开始录音了

我怎样才能让它正常工作?

由于您试图终止在 start.sh 中启动的进程。这是我推荐的:

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()