当按下按钮时,python 脚本会在 Raspberry Pi 上自动运行 [英] When press button, python script runs automatically on Raspberry Pi
问题描述
在网上找不到教程.
当我按下按钮时,我想要运行一些 python 脚本.我不想先在 Raspberry Pi 的终端上运行 python 脚本,然后像一些教程提到的那样等待按钮被按下.我还希望整个脚本在我按下按钮后运行,而不是我必须在脚本运行的整个持续时间内按下按钮.
基本上,我希望脚本无需将 HDMI 显示器或鼠标连接到 Raspberry Pi 或 GUI 即可运行.只需按一下按钮.
另外,如果有人有关于如何使用 GPIO 设置按钮的图表和真正有用的代码.
我该怎么做??我在上面找不到任何东西,看起来很简单.
您将始终需要一些程序来监视您的输入,无论是来自键盘、鼠标还是连接到 GPIO 的按钮.对于键盘和鼠标,操作系统为您提供了这些.因此,要从 GPIO 引脚触发程序,您需要编写如下脚本:
将 RPi.GPIO 导入为 GPIO导入时间导入子流程GPIO.setmode(GPIO.BCM)GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)而真:input_state = GPIO.input(18)如果 input_state == False:subprocess.call(东西)# 阻塞直到完成(取决于应用程序)
这是一个按钮电路(来自
Can't find tutorial online.
When I press a button, I want some python script to run. I don't want to run the python script first on the Raspberry Pi's terminal and then wait for the button to be pressed like some tutorials mention. I also want the whole script to run after I press the button, not that I have to press the button for the whole duration of the script to run.
Basically, I want the script to run without having to have a HDMI monitor or mouse connected to Raspberry Pi or a GUI thing. Just the press of a button.
Also if anyone has diagrams on how to set up the button with the GPIO and code that would be really helpful.
How do I do this?? I can't find anything on it and it seems so simple.
You will always need some program to monitor your input, whether it be from a keyboard, mouse, or a button wired to GPIO. In the case of the keyboard and mouse the OS provides this for you. So to trigger programs from a GPIO pin you will need to write a script much like this:
import RPi.GPIO as GPIO
import time
import subprocess
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
while True:
input_state = GPIO.input(18)
if input_state == False:
subprocess.call(something)
# block until finished (depending on application)
Here's a button circuit (from this tutorial)
这篇关于当按下按钮时,python 脚本会在 Raspberry Pi 上自动运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!