如何在 Python 中满足特定条件时触发功能

How to trigger function when certain condition is met in Python

我一直在研究一种自动浇水植物,我希望它能在水箱空和满时给我发送电子邮件。一切正常,但是,我需要能够设置一个条件,在满足条件时仅触发一次电子邮件功能。相反,只要满足条件,它就会无限地每秒发送电子邮件。

例如:根据传感器,水箱已满,发送电子邮件"Water tank full"

传感器检测到水箱已空,发送邮件"Water tank empty"

除非水位发生变化,否则这种情况只会发生一次。

并且在满足不同的条件之前不要做任何事情。因此,只要有水,循环就会一直持续下去而不会触发任何条件。

一旦没有更多的水,就会触发条件。没水的时候也一样,然后我再加水

代码如下:

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()

只需将其锁定为上次看到的状态,并且仅在其不同时才采取行动

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()

也使用有意义的名字

与其不断查看 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