print("This program integrates PIR sensor with ESP32")
 
# Credits to https://RandomNerdTutorials.com & program edited accordingly
 
 #1. Import all necessary modules/library
from machine import Pin #this is to declare pin 14 & 12
from utime import sleep #utime is for python
 
 #2. Initialize the motion parameter
motion = False  #Initially there is no movement
 
 #3. Create function interrupt handling 
 #Remarks : This function will be called everytime a motion is detected
def handle_interrupt(pin): #def is for function
  global motion
  motion = True
  global interrupt_pin  
  interrupt_pin = pin 
 
 #4. Declare input and output pin
 #Remark: LED as output and PiR sensor as input
led_red = Pin(12, Pin.OUT)  #OUT = Output
pir = Pin(14, Pin.IN) #IN = Input
 
 #5. Set interrupt pin on PIR sensor by using irq() method
pir.irq(trigger=Pin.IRQ_RISING, handler=handle_interrupt)
 
 #6. Time to test! Now we can compare the output of LED when there is motion or no motion
while True: #forever loop
  if motion == True:  #A motion has been detected
    print('Motion detected! Interrupt caused by:', interrupt_pin, 'LED Red = ON' )
    for i in range (10):
      led_red.on()
      sleep(0.5)
      led_red.off()
      sleep(0.5)
    print('Motion stopped! LED Red = OFF')  # No motion
    motion = False