from machine import Pin, I2C, Timer
import time
import dht
from i2c_lcd import I2cLcd # Import the I2C LCD library
# Initialize HC-SR04 sensor
TRIG_PIN = 14
ECHO_PIN = 27
trigger = Pin(TRIG_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
# Initialize I2C communication for LCD display
i2c = I2C(scl=Pin(22), sda=Pin(21))
lcd = I2cLcd(i2c, 0x27, 2, 16) # Change the address and dimensions according to your LCD
# Initialize object count
object_count = 0
def measure_distance():
# Generate 10-microsecond pulse to TRIG pin
trigger.on()
time.sleep_us(10)
trigger.off()
# Measure duration of pulse from ECHO pin
duration_us = pulse_in(echo, 1)
distance_cm = 0.017 * duration_us # Calculate distance in cm
return distance_cm
def pulse_in(pin, level):
while pin.value() != level:
pass
start_time = time.ticks_us()
while pin.value() == level:
pass
end_time = time.ticks_us()
return time.ticks_diff(end_time, start_time)
def update_display():
lcd.clear()
lcd.putstr("Object Count:")
lcd.move_to(0, 1)
lcd.putstr(str(object_count))
def main(timer):
global object_count
distance = measure_distance()
if distance < 20: # Adjust threshold as needed
object_count += 1
update_display()
time.sleep(0.5) # Debounce time
# Set up a timer to run the main function periodically
timer = Timer(0)
timer.init(period=100, mode=Timer.PERIODIC, callback=main)
# Keep the program running
while True:
time.sleep(1)