from machine import Pin, I2C
import time
from pico_i2c_lcd import I2cLcd
# Konfigurasi I2C untuk LCD
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
lcd = I2cLcd(i2c, 0x27, 2, 16)
# Konfigurasi Sensor Ultrasonic
TRIG = Pin(2, Pin.OUT)
ECHO = Pin(3, Pin.IN)
# Konfigurasi Push Button
button = Pin(4, Pin.IN, Pin.PULL_UP)
# Inisialisasi
vehicle_count = 0
# Fungsi untuk mengukur jarak
def measure_distance():
TRIG.low()
time.sleep_us(2)
TRIG.high()
time.sleep_us(10)
TRIG.low()
while ECHO.value() == 0:
pulse_start = time.ticks_us()
while ECHO.value() == 1:
pulse_end = time.ticks_us()
pulse_duration = pulse_end - pulse_start
distance = (pulse_duration * 0.0343) / 2
return distance
# Fungsi untuk menulis ke LCD
def update_lcd(count):
lcd.clear()
lcd.putstr(f"Vehicles: {count}")
# Main loop
lcd.putstr("System Ready")
time.sleep(2)
lcd.clear()
while True:
distance = measure_distance()
if distance < 50: # Jika jarak kurang daripada 10cm
vehicle_count += 1
if vehicle_count > 100: # Had maksimum kenderaan
vehicle_count = 100
update_lcd(vehicle_count)
time.sleep(1) # Elakkan pengiraan berganda
if button.value() == 0: # Reset apabila butang ditekan
vehicle_count = 0
update_lcd(vehicle_count)
time.sleep(5) # Debouncing