如何在Python中满足某些条件时触发函数

时间:2016-12-29 19:06:03

标签: python raspberry-pi3

我一直在做一个自给自足的工厂,我想让它在水箱空了以及装满时给我发电子邮件。一切正常但是,我需要能够设置一个条件,只有在满足条件时触发电子邮件功能。相反,只要满足条件,它就会无限地发送并每秒发送一次电子邮件。

例如:根据传感器水箱已满,发送电子邮件"水箱满#34;

根据传感器,水箱是空的,发送电子邮件"水箱空了"

除非水位发生变化,否则应该只发生一次。

在满足不同条件之前不要做任何事情。因此,只要有水,循环就会永远持续,不会触发任何条件。

一旦没有水,那么条件就会触发。当没有水然后重新填充时也一样

以下是代码:

import RPi.GPIO as GPIO, feedparser 
from time import sleep
import smtplib, os, sys 
from email.mime.text import MIMEText 
from email.MIMEMultipart import MIMEMultipart

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)

#Set up GPIO Inputs
# Yellow Input
GPIO.setup(2, GPIO.IN)

def send_email(msg):
    USERNAME = "myemail@gmail.com"
    PASSWORD = "my_email_password"
    MAILTO "recipient email"

    msg['From'] = USERNAME
    msg['To'] = MAILTO

    server = smtplib.SMTP('smtp.gmail.com:587')
    server.ehlo_or_helo_if_needed()
    server.starttls()
    server.ehlo_or_helo_if_needed()
    server.login(USERNAME, PASSWORD)
    server.sendmail(USERNAME, MAILTO, msg.as_string())
    server.quit()

    print "Email sent to: "+ MAILTO 
    return

def Send_nowater_email():
  print"No water"
  msg = MIMEMultipart()
  msg.attach(MIMEText('Water tank empty'))
  msg['Subject'] = 'Plant notification'
  send_email(msg)
  return

def Send_watered_email():
  msg = MIMEMultipart()
  msg.attach(MIMEText('Water tank full'))
  msg['Subject'] = 'Plant notification'
  send_email(msg)
  return 

while True: 
  Input_yellow = GPIO.input(2)
  print Input_yellow

  if Input_yellow == False:
    Send_watered_email()

  if Input_yellow == True:
    Send_nowater_email()

2 个答案:

答案 0 :(得分:2)

将其锁定到上次看到的状态,只有在其不同的

时才会执行
current_state = None
while True: 
  is_empty = GPIO.input(2)
  if current_state != is_empty:
      current_state = is_empty
      if is_empty == False:
         Send_watered_email()
      if is_empty == True:
         Send_nowater_email()

也使用有意义的名字

答案 1 :(得分:2)

不要继续查看Input_yellow,而是尝试在Input_yellow中查找更改。这样的事情会对你有帮助,

current = False
while True: 
  Input_yellow = GPIO.input(2)
  print Input_yellow

  if Input_yellow == False and current == True:
    Send_watered_email()
    current = False

  if Input_yellow == True and current == False:
    Send_nowater_email()
    current = True