print("This program integrates OLED screen with ESP32")

# Credits to https://RandomNerdTutorials.com & program edited accordingly

#1. Import all neccessary modules and libraries
from machine import Pin, SoftI2C #SoftI2c kene ada if ada sda & scl wujud
from utime import sleep
from machine import Pin
import ssd1306 #this is oled Library

motion = False

#1. create function for interupt handling
def handle_interrupt(pin): #def is for function
  global motion
  motion = True
  global interrupt_pin
  interrupt_pin = pin 
#2.Declare pin on OLED display
led_red = Pin(12, Pin.OUT) #OUT = output
pir = Pin(14, Pin.IN)
i2c_oled = SoftI2C(scl=Pin(22), sda=Pin(21))

#3.Define the OLED Display parameter
oled_width = 128 #based on spec
oled_height = 64 #based on spec

#4. Set interupt pin on PIR sensor by using irq() method
pir.irq(trigger=Pin.IRQ_RISING, handler=handle_interrupt)

#5. create an object called "oled"
#Remark: object format "library name.class name"
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c_oled)

#5. Let test the OLED
#Remark: the font color is default set to 1(white)
#Create text to be displayed on OLED screen
#. Time to test! Now we can compare the output of LED when there is motion or no motion 
while True:
  if motion == True:
    # Clear the OLED display
    oled.fill(0)
    oled.show()
    oled.text('Motion Detected!', 0, 20)
    oled.show()
    print('Motion detected! Interrupt caused by:', interrupt_pin, 'LED Blue = ON' )
    for i in range(10):
     led_red.on()
     sleep(0.5)
     led_red.off()
     sleep(0.5)
    print('Motion stopped! Blue Led = OFF')
    motion = False
    # Clear the OLED display
    oled.fill(0)
    oled.show()
  elif motion == False:
    oled.text('No Motion Detect', 0, 20)
    oled.show()