from machine import Pin
from utime import sleep
# Pin configurations
COUNTER_PIN = 18
EMERGENCY_BUTTON_PIN = 20
LED_PIN = 2
# Constants
COUNT_INTERVAL = 1
BOTTLES_PER_BOX = 20
DEBOUNCE_DELAY = 0.3
# Initialize pins
counter_pin = Pin(COUNTER_PIN, Pin.IN, Pin.PULL_UP)
emergency_button_pin = Pin(EMERGENCY_BUTTON_PIN, Pin.IN, Pin.PULL_UP)
led_pin = Pin(LED_PIN, Pin.OUT)
# Global variables
box_count = 0
bottle_count = 0
emergency_stop = False
def count_bottles():
global bottle_count, box_count
for _ in range(BOTTLES_PER_BOX):
if not emergency_stop:
sleep(COUNT_INTERVAL)
bottle_count += 1
print("Bottle counted:", bottle_count)
if bottle_count == BOTTLES_PER_BOX:
box_count += 1
bottle_count = 0
print("Box filled:", box_count)
else:
blink_led()
return
def emergency_stop_callback(pin):
global emergency_stop
if pin.value() == 0:
emergency_stop = not emergency_stop
print("Emergency stop activated.")
sleep(DEBOUNCE_DELAY)
def blink_led():
while emergency_stop:
led_pin.value(not led_pin.value())
sleep(DEBOUNCE_DELAY)
# Assign to emergency button pin
emergency_button_pin.irq(trigger=Pin.IRQ_FALLING, handler=emergency_stop_callback)
try:
print("Machine ready.")
while True:
if not emergency_stop:
count_bottles()
finally:
led_pin.value(0) # Turn off LED