当按下按钮时,Python脚本会在Raspberry Pi上自动运行 [英] When press button, python script runs automatically on Raspberry Pi

查看:41
本文介绍了当按下按钮时,Python脚本会在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)而True: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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆