2017-05-13 273 views
-5

我做了倒车雷达raspberry pipython无限while循环蟒蛇

这是代码:

import RPi.GPIO as GPIO 
import time 
#from picamera import PiCamera 
from time import sleep 
from gpiozero import MotionSensor 
import smtplib 

sender = '*****@gmail.com' 
reciever = '*****@gmail.com' 

def BlueLED(): #Blue LED Function 

    GPIO.output(27, GPIO.HIGH) 
    time.sleep(3) 
    GPIO.output(27, GPIO.LOW) 


def RedLED(): #Red LED Function 

    GPIO.output(22,GPIO.HIGH) 
    time.sleep(3) 
    GPIO.output(22, GPIO.LOW) 

def Buzzer(): #Buzzer Function 

    GPIO.output(17, GPIO. HIGH) 
    time.sleep(3) 
    GPIO.output(17, GPIO.LOW) 


def email(sender,reciever,msg): 
    try : 
     server = smtplib.SMTP('smtp.gmail.com',587) 
     server.ehlo() 
     server.starttls() 
     server.login(sender,'******') 
     server.sendmail(sender,reciever,msg) 
     server.close() 

     print('Email sent!') 

    except : 
     print('Error') 

try : 

    GPIO.setmode(GPIO.BCM) 
    #camera = PiCamera() 
    pir = MotionSensor(4) 
    GPIO.setwarnings(False) 


    GPIO.setup(27, GPIO.OUT) #blueLED 
    GPIO.setup(22, GPIO.OUT) #redLED 
    GPIO.setup(17, GPIO.OUT) #buzzer 
    GPIO.setup(18, GPIO.OUT) #tempsensor 

    GPIO.setup(21, GPIO.IN, pull_up_down = GPIO.PUD_UP) #entry button 

    count = 0 

    while True : 

     if (pir.motion_detected): 
      print('Motion Detected') 

      #Calling the buzzer function 
      #Buzzer() 

      #The content that is going to be sent via email 


      msg = """Subject : Car Park 

      (Picture) """ 

      email(sender,reciever,msg) 




      print('\nPlease press the button for the gate to open') 



      while True : 

       if(GPIO.input(21) == False): 
        if (count < 5): 
         BlueLED() 
         print('\nThere are ',(5-count), ' parking spaces empty ') 

        else : 
         RedLED() 
         print('\nSorry but the parking is full') 

        count = count + 1 



except Exception as ex : 
    print('Error occured',ex) 

我的问题是,第一个while循环不工作,也就是说,如果运动传感器触发什么也没有发生,但你可以压制按钮和计数增加。我猜这有一个简单的解决方案,但似乎没有想到。会爱你的帮助,谢谢

+0

这是很清楚你的问题是什么。 “我的问题是第一个while循环不起作用”是什么意思? – Carcigenicate

+0

因为我有两个while循环,循环整个程序的循环不是无限循环(尽管这是它应该做的)。这意味着当运动传感器触发任何类型的运动时,什么都不会发生。第二个while循环控制计数器和按钮工作正常。因此,当按下按钮时,计数器会增加,即使不会发生这种情况,因为运动传感器应该先触发,然后才能按下按钮。希望这是明确的 –

回答

0

你的第二个while循环没有断点!!! 您的第一个while循环运行,直到它检测到运动,然后进入第二个循环,并且第二个循环永远运行。 如果你想要两个循环同时工作,那么你应该使用线程! 如果不是,则在第二个循环中创建一个中断点。

简单的例子:

import time 
count=0 
count2=0 
while True: #starting first loop 
    count+=1 # counting to 100 to start second loop 
    if count==100: 
     print("its 100 entering second loop") 
     time.sleep(1) 
     while True: # entering second loop 
      count2+=1 #counting to 100 to exit second loop 
      if count2==100: 
       print("its 100 exitin second loop") 
       time.sleep(1) 
       count=0 
       count2=0 
       break # exiting second loop this is the break point 
+0

你能否更好地解释你指的是什么意思? –

+0

你必须有东西退出第二个循环才能返回到第一个循环一个简单的break命令 - 添加了一个例子 –