#Lab23_Interrupts_PIR_Case.py
# https://randomnerdtutorials.com/micropython-interrupts-esp32-esp8266/
# ปุ่มกดดับปล่อยติด
# 1 ประกาศ/เรียกใช้โมดูล
from machine import Pin, ADC, PWM
import math
import time

# 2 ประกาศตัวแปร/สร้างตัวแปรต่างๆ
led1 = Pin(23,Pin.OUT)
led2 = Pin(22,Pin.OUT)
led3 = Pin(18,Pin.OUT)

PIR = Pin(19, Pin.IN)
button = Pin(21,Pin.IN)

motion = False
# Function Interrupt
def handle_interrupt(pin):
    led1.off()
    print('Press Button! Interrupt')
    if button.value() == 1:
        for i in range(5):
            led2.on()
            time.sleep(0.5)
            led2.off()
            time.sleep(0.5)
        print("Mission Complete ....")

# Function Interrupt
def handle0_interrupt(pin):
    global motion
    motion = True
    global interrupt_pin
    interrupt_pin = pin
    if motion:
        print('Motion detected! Interrupt caused by:', interrupt_pin)
        led1.off()
        led3.value(1)
        time.sleep(5)
        led3.value(0)
        print('Motion stopped!')
        motion = False

button.irq(trigger=Pin.IRQ_RISING, handler=handle_interrupt)
PIR.irq(trigger=Pin.IRQ_RISING, handler=handle0_interrupt)

'''
The irq() method accepts the following arguments:

trigger: this defines the trigger mode. There are 3 different conditions:
Pin.IRQ_FALLING: to trigger the interrupt whenever the pin goes from HIGH to LOW;
Pin.IRQ_RISING: to trigger the interrupt whenever the pin goes from LOW to HIGH.
3: to trigger the interrupt in both edges (this means, when any change is detected)
handler: this is a function that will be called when an interrupt is detected, in this case the handle_interrupt() function.
'''

# 3 คำสั่ง/การควบคุม การอ่าน
while True:
    led1.on()
    time.sleep(0.5)
    led1.off()
    time.sleep(0.5)
'''
    if motion:
        print('Motion detected! Interrupt caused by:', interrupt_pin)
        led1.off()
        led3.value(1)
        time.sleep(5)
        led3.value(0)
        print('Motion stopped!')
        motion = False
'''
$abcdeabcde151015202530fghijfghij