from machine import Pin
import time
# Set up the IR sensor and LED
ir_sensor = Pin(2, Pin.IN) # GPIO 15 as input pin for IR sensor
led = Pin(1, Pin.OUT) # GPIO 2 as output pin for the LED
counter = 0 # Initialize a counter variable
# Function to monitor the IR sensor and control the LED
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}")
led.on() # Turn on the LED when an object is detected
else:
led.off() # Turn off the LED when no object is detected
previous_state = current_state
time.sleep(0.1) # Short delay to avoid bouncing issues
# Run the object counting function
try:
count_objects()
except KeyboardInterrupt:
print("Counting stopped.")
led.off() # Turn off the LED when the program is interrupted