在树莓Pi上按下按钮时,使shell脚本仅运行*

2024-09-28 20:51:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作一种设备,它可以对它看到的所有东西进行反验证,但只能在我按下按钮时进行。为此,我使用了一个Python脚本,每当它检测到GPIO 18低时,就会运行mdk3命令。一般来说,我对Python不是很了解,所以我只是在网络上四处寻找适合我的用例的东西,但毫无用处。相反,我尝试重新调整其他代码的用途以适合我的用例。我的代码如下:

import RPi.GPIO as GPIO
import time
import subprocess
import os

FSU = "sudo mdk3 wlan0 d"

# Define a callback function that will be called by the GPIO event system:
def onButton(channel):
    if channel == 16:
        subprocess.run(FSU, capture_output=True, shell=True)



# Setup GPIO16 (can be changed) as an input with internal pull-up resistor to hold it HIGH until it is pulled down to GND by the connected button; this prevents involuntary deauthing
GPIO.setmode(GPIO.BCM)
GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# Register an edge detecting on RISING edge. When this event fires, the callback onButton() will be executed. Because of bouncetime=20, all edges 20 ms after a first rising edge will be ignored
GPIO.add_event_detect(16, GPIO.RISING, callback=onButton, bouncetime=20)

我对它的工作原理有一个基本的了解,并且(理论上)如果按下按钮,它应该运行一个指定的脚本。然而,也存在一些问题。主要是,在运行一次之后,它不会一直监视GPIO 16;它只穿过它一次就退出了。而且,即使在释放按钮之后,mdk3命令仍在运行。我对Python的了解有点有限,所以如果您能解释一下您做了什么以及为什么要这么做,那就太好了。谢谢


Tags: the代码import命令脚本eventgpiocallback