Raspberry Pi- GPIO Events in Python

前端 未结 4 980
暗喜
暗喜 2020-12-13 10:47

I am using the GPIO pins on my Raspberry Pi with a PIR sensor to detect motion. When the sensor detects motion I want to then move the software onto other functions.

4条回答
  •  生来不讨喜
    2020-12-13 10:53

    kapcom01 gives some great ideas but it's better to make not make a lot of instructions in the a interrupt.

    Usually you put a flag to 1 when the callback is call and you make the processing in the main function. In thes manner there is no risk of freesing the programm.

    Somethings like this :

         from time import sleep
         import RPi.GPIO as GPIO
    
    
    
         def init():
             # make all your initialization here
             flag_callback = False
             # add an interrupt on pin number 7 on rising edge
             GPIO.add_event_detect(7, GPIO.RISING, callback=my_callback, bouncetime=300)
    
    
         def my_callback():
             # callback = function which call when a signal rising edge on pin 7
             flag_callback = True
    
    
         def process_callback():
             # TODO: make process here
             print('something')
    
    
         if __name__ == '__main__':
         # your main function here
    
         # 1- first call init function
         init()
    
         # 2- looping infinitely 
         while True:
             #3- test if a callback happen
             if flag_callback is True:
                 #4- call a particular function
                 process_callback()
                 #5- reset flagfor next interrupt
                 flag_callback = False
        pass
    

提交回复
热议问题