from machine import Pin
import time
# Set up the IR sensor
ir_sensor = Pin(15, Pin.IN) # GPIO 15 as input pin
counter = 0 # Initialize a counter variable
# Function to monitor the IR sensor
def count_objects():
global counter
previous_state = ir_sensor.value() # Initial state of the sensor
while True:
current_state = ir_sensor.value()
# Check if the state has changed from high to low (object detected)
if previous_state == 1 and current_state == 0:
counter += 1
print(f"Object detected! Count: {counter}")
previous_state = current_state
time.sleep(0.1) # Short delay to avoid bouncing issues
try:
count_objects()
except KeyboardInterrupt:
print("Counting stopped.")