print("Automatic Light Sensor Detector")
print("This program integrates Ultrasonic sensor with ESP32")
#Import libraries/modules
import Ultrasonic_library
from machine import Pin, SoftI2C, PWM, ADC #softI2C kena ada if sda & scl wujud
import OLED_library
from utime import sleep
#Declare pin connection of ultrasonic and create an object
#Called Sensor using OOp (Object Oriented Programming)
#OOP format --> library name, class name (........)
Sensor = Ultrasonic_library.HCSR04 (trigger_pin=25, echo_pin=33, echo_timeout_us=500*2*30)
#Declare pin on OLED Display
i2c_oled = SoftI2C(scl=Pin(22), sda=Pin(21))
oled_width = 128 #based on spec
oled_height = 64 #based on spec
screen = OLED_library.SSD1306_I2C(oled_width, oled_height,i2c_oled)
#pin LDR
LDR = ADC(Pin(34, Pin.IN))
LDR.atten(ADC.ATTN_11DB)
#adc.read()
#Declare input and output pin
#Remarks: LED and buzzer as Output and Ultrasonic sensor will be Input
led_white = Pin(12, Pin.OUT)
buzzer = PWM(Pin(23), Pin.OUT)
#Initialize the count variable
count = 0
while True:
ldr_value = LDR.read()
#Let's test Sensor!
jarak_in_mm = Sensor.distance_mm()
#Display the distance from the object
print('Distance from an object is : ',jarak_in_mm, 'mm') #choose mm if u want while number
print('--------------------------------------------------')
print('\n')
#Display on OLED screen
screen.fill(0)
screen.text('Object detected:', 0, 0,) #x-axis, y-axis
screen.text(str (jarak_in_mm) , 0, 20,)
screen.text ('mm' , 60, 20,)
screen.show()
#Making decision on how close the object
if jarak_in_mm < 0 and ldr_value > 853: #Twillight
led_white.on()
sleep (10)
led_white.off()
elif jarak_in_mm < 1000 and ldr_value > 8: #lux 100,000 = Direct sunlight:
#Count object detected
count += 1
print("Count:", count)
#LED ON
led_white.on()
sleep(10)
led_white.off()
elif jarak_in_mm < 1000 and ldr_value < 853:
#Count object detected
count += 1
print("Count:", count)
#LED ON
led_white.on()
sleep(10)
led_white.off()
elif jarak_in_mm > 1000 and ldr_value < 8:
count = count
print("Count:", count)
#Turn OFF the LED
led_white.off()
sleep(10)
elif jarak_in_mm > 1000 and ldr_value < 853:
count = count
print("Count:", count)
#Turn OFF the LED
led_white.off()
sleep(10)
else:
led_white.off()
sleep (5)