python 从树莓派中听取GPIO输入 - 打开菜单并关闭电源

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 从树莓派中听取GPIO输入 - 打开菜单并关闭电源相关的知识,希望对你有一定的参考价值。

# Import the RPi.GPIO and OS
import RPi.GPIO as GPIO
import os
import sys
import time

# GPIO port setup
GPIO.setmode(GPIO.BCM)

# Power switch: will send a shutdown message to the OS
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# Reset switch: will look for a running emulator process, and send it an interrupt signal
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# Looks for an emulator process and send an interrupt signal if found
def exitEmulator(channel):
    print('exitEmulator')
    pids = [pid for pid in os.listdir('/proc') if pid.isdigit()]

    for pid in pids:
        try:
            commandpath = open(os.path.join('/proc', pid, 'cmdline'), 'rb').read()
            if commandpath[0:24] == '/opt/retropie/emulators/':
                os.system('kill -QUIT %s' % pid)
                print('kill -QUIT %s' % pid)
        except IOError:
            continue

# Sends a poweroff command to the OS
def powerOff(channel):
    print('poweroff')
    os.system('poweroff')

# Here we just wire the  GPIO inputs to their respective callback functions
GPIO.add_event_detect(17, GPIO.RISING, callback=powerOff, bouncetime=500)
GPIO.add_event_detect(18, GPIO.RISING, callback=exitEmulator, bouncetime=500)

# And... nothing more to do. let's wait.
while True:
    time.sleep(10)

以上是关于python 从树莓派中听取GPIO输入 - 打开菜单并关闭电源的主要内容,如果未能解决你的问题,请参考以下文章

树莓派实验1:GPIO点亮led灯

在树莓派中为 python 3 安装 mysql 连接器

树莓派接入巴法云

如何在树莓派上安装python和GPIO库

在树莓派中开启激动人心的 Perl 之旅

树莓派中python通过队列实现进程交互