import machine
from machine import SoftI2C, Pin, Timer
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
import time
import dht
# Initialize HC-SR04 sensor
TRIG_PIN = 2
ECHO_PIN = 4
trigger = Pin(TRIG_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
# Initialize DHT sensor
sensor = dht.DHT22(Pin(12)) # Assuming same pin as HC-SR04
I2C_ADDR = 0x27
totalColumns = 16
totalRows = 2
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=10000) # For ESP32
# Initialize the LCD
lcd = I2cLcd(i2c, I2C_ADDR, totalRows, totalColumns)
# 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(temp, temp_f, hum):
lcd.clear()
time.sleep(0.1) # Sleep before clearing the display
lcd.putstr("Object Count:")
lcd.putstr(str(object_count))
time.sleep(2) # Sleep before moving to next line
lcd.move_to(0, 2)
lcd.putstr('Temp:{:.1f}C {:.1f}F'.format(temp, temp_f))
lcd.putstr('Humidity: {:.1f}%'.format(hum))
time.sleep(3) # Sleep before printing humidity
def main(timer):
global object_count
distance = measure_distance()
if distance < 20: # Adjust threshold as needed
object_count += 1
try:
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
temp_f = temp * (9 / 5) + 32.0
update_display(temp, temp_f, hum)
except OSError as e:
print('Failed to read DHT sensor.')
# Set up a timer to run the main function periodically
timer = Timer(0)
timer.init(period=500, mode=Timer.PERIODIC, callback=main)
# Keep the program running
while True:
time.sleep(2)