按下按钮关闭Raspberry Pi Python

时间:2015-05-04 11:09:15

标签: python button raspberry-pi shutdown headless

我正在为监控摄像机编写脚本。我已将其编程为在检测到动作时拍摄照片(PIR传感器),然后将照片附加到电子邮件中,并附加到选定的收件人。但是因为我在没有连接屏幕,鼠标或键盘的情况下运行它,所以我无法在不拔插头的情况下关闭设备!所以我创建了一个脚本来按下按钮关闭计算机(这本身可以正常工作)但是,因为其余的代码是循环的,我不知道放在哪里。请记住,我需要能够在代码中的任何位置关闭它。 如果您有任何想法,他们将不胜感激 谢谢 詹姆斯

import os, re
import sys
import smtplib
import RPi.GPIO as GPIO
import time
import picamera
inport os
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import time
import RPi.GPIO as gpio
GPIO.setmode(GPIO.BCM)
GPIO_PIR = 4
print ("PIR Module Test (CTRL-C to exit)")
GPIO.setup(GPIO_PIR,GPIO.IN)     
Current_State  = 0
Previous_State = 0
try:
  print ("Waiting for PIR to settle ...")
  while GPIO.input(GPIO_PIR)==1:
    Current_State  = 0
  print ("  Ready")
  while True :
    Current_State = GPIO.input(GPIO_PIR)
    surv_pic = open('/home/pi/Eaglecam/surveillance.jpg', 'wb')
    if Current_State==1 and Previous_State==0:
      print("  Motion detected!")
      with picamera.PiCamera() as cam:
        cam.capture(surv_pic)
        surv_pic.close()
      print('  Picture Taken')
      SMTP_SERVER = 'smtp.gmail.com'
      SMTP_PORT = 587       
      sender = '**************'
      password = "**********"
      recipient = '**************'
      subject = 'INTRUDER DETECTER!!'
      message = 'INTRUDER ALLERT!! INTRUDER ALERT!! CHECK OUT THIS PICTURE OF THE INTRUDER! SAVE THIS PICTURE AS EVIDENCE!'
      directory = "/home/pi/Eaglecam/"
      def main():
          msg = MIMEMultipart()
          msg['Subject'] = 'INTRUDER ALERT'
          msg['To'] = recipient
          msg['From'] = sender
          files = os.listdir(directory)
          jpgsearch = re.compile(".jpg", re.IGNORECASE)
          files = filter(jpgsearch.search, files)
          for filename in files:
              path = os.path.join(directory, filename)
              if not os.path.isfile(path):
                  continue
              img = MIMEImage(open(path, 'rb').read(), _subtype="jpg")
              img.add_header('Content-Disposition', 'attachment', filename=filename)
              msg.attach(img)
          part = MIMEText('text', "plain")
          part.set_payload(message)
          msg.attach(part)
          session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
          session.ehlo()
          session.starttls()
          session.ehlo
          session.login(sender, password)
          session.sendmail(sender, recipient, msg.as_string())
          session.quit()
      if __name__ == '__main__':   
        print('  Email Sent')
      Previous_State=1
    elif Current_State==0 and Previous_State==1:
      print("  Ready")
      Previous_State=0
      time.sleep(0.01)
    import time
    import RPi.GPIO as gpio
except KeyboardInterrupt:
  print('Quit')
  GPIO.cleanup()

这是脚本的关闭部分。我将它放在循环中的哪个位置?

    gpio.setmode(gpio.BCM)
    gpio.setup(7, gpio.IN, pull_up_down=gpio.PUD_UP)
    buttonReleased = True
    while buttonReleased:
        gpio.wait_for_edge(7, gpio.FALLING)
        buttonReleased = False
        for i in range(1):
            time.sleep(0.1)
            if gpio.input(7):
                buttonReleased = True
                break

1 个答案:

答案 0 :(得分:1)

此项目不需要两个单独的脚本。

你可以通过几种方式做到这一点。

  1. 创建一个名为shutdownButton或其他的全局布尔变量。使用GPIO引脚的回调函数,并在回调中设置shutdownButton = True。然后将主循环更改为while not shutdownButton:而不是while True:
  2. 您可以将主循环更改为while gpio.input(7):而不是while True:(假设您将引脚向上拉,然后将其与开关接地)。
  3. 然后最后添加一个像os.system('sudo shutdown -h now')这样的关闭,或者调用你想要运行的其他脚本来清理它。关键是你只需要一个函数在按下按钮时突破你的主循环,然后在程序结束时关闭你的pi。
    还有其他方法可以做到这一点(我个人喜欢Adafruit的内核补丁,允许将电源开关配置添加到/etc/modprobe.d ...)但我只列出了直接应用于您的问题的方法。