【问题标题】:GPIO Button Press to Execute Python 3 ProgramGPIO 按钮按下以执行 Python 3 程序
【发布时间】:2017-12-13 00:23:47
【问题描述】:

我在 Raspberry Pi 3 的引脚 23 上设置了一个 GPIO 按钮,我希望在按下该按钮时它可以执行另一个 python 脚本。当我运行初始程序时,它会打印“Button Pressed”,但不会执行第二个程序。 (我确实确保在程序中设置了权限。)非常感谢您的帮助!

    #!/usr/bin/env python
    import RPi.GPIO as GPIO
    import time
    import subprocess

    GPIO.setmode(GPIO.BCM)
    GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    while True:
        input_state = GPIO.input(23)
        if input_state == False:
            print('Button Pressed')
            subprocess.call('/home/pi/Downloads/PuttingItAllTogether.py', shell=True)
            time.sleep(0.2)

【问题讨论】:

  • 如果它正在打印“Button Pressed”,那么它应该正在运行您的脚本。您确定您的 /home/pi/Downloads/PuttingItAllTogether.py 脚本会产生输出吗?有没有检查脚本的退出状态(这是subprocess.call的返回值)?
  • 感谢您的帮助@larsks。我对编程很陌生。如何检查脚本的退出状态?我可以直接从 python 运行 /home/pi/Downloads/PuttingItAllTogether.py 并且它可以工作。衷心感谢您的帮助。
  • 就像我说的,它是对subprocess.call 的调用的返回值。将其保存在变量中并打印出来,如returnval = subprocess.call(...) 后跟print 语句。

标签: python raspberry-pi gpio


【解决方案1】:

你能不使用库“os”而使用“system”吗?

#!/usr/bin/env python
import RPi.GPIO as GPIO
import time
import os

GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)

while True:
    input_state = GPIO.input(23)
    if input_state == False:
        print('Button Pressed')
        os.system('/home/pi/Downloads/PuttingItAllTogether.py')
        time.sleep(0.2)

使用语法:

import os
os.system('shell command to execute')

【讨论】:

    猜你喜欢
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    • 2016-11-29
    • 1970-01-01
    • 2017-12-23
    • 2010-11-01
    • 1970-01-01
    相关资源
    最近更新 更多