#import libraries
import machine
import time
import dht
from machine import Pin
#Set up DHT22 sensor (Temperature and Humidity)
#Data pin connected to GP6
dht_sensor = dht.DHT22(Pin(6))
#Set up PIR Motion Sensor
#OUT pin connected to GP28
pir_sensor = Pin(28, Pin.IN)
# Set up Relay Module
# IN pin connected to GP18
# The relay controls the conveyor belt motor (ON/OFF)
relay = Pin(18, Pin.OUT)
relay.value(0) # Initially, the conveyor belt is running (relay OFF)
# Variables for counting and sensor readings
product_count = 0 #Keeps track of the number of products detected by PIR
pir_state = 0 #Stores the previous PIR state to avoid multiple counts
temp_low = 15.0 # Lower limit for temperature (in degrees Celsius)
temp_high = 30.0 # Upper limit for temperature (in degrees Celsius)
humidity_low = 40.0 # Lower limit for humidity (in percentage)
humidity_high = 60.0 # Upper limit for humidity (in percentage)
# Function to stop the conveyor belt by activating the relay
def stop_belt():
relay.value(1) # Activate relay to stop the belt
print("Belt stopped due to abnormal conditions!")
# Function to start the conveyor belt by deactivating the relay
def start_belt():
relay.value(0) # Deactivate relay to run the belt
print("Belt operating normally.")
# Main loop to continuously monitor the sensors and control the belt
while True:
# Read PIR Sensor to detect product motion
current_pir_state = pir_sensor.value()
# If motion is detected (PIR value = 1), and it wasn't detected previously
if current_pir_state == 1 and pir_state == 0:
product_count += 1 # Increment product count
print(f"Product Count: {product_count}") # Display the count
pir_state = 1 # Update PIR state to avoid double counting
time.sleep(0.5) # Small delay to debounce PIR sensor
elif current_pir_state == 0:
pir_state = 0 # Reset PIR state if no motion is detected
# Read Temperature and Humidity from DHT22 sensor
try:
dht_sensor.measure() # Measure temperature and humidity
temperature = dht_sensor.temperature() # Get temperature reading
humidity = dht_sensor.humidity() # Get humidity reading
print(f"Temperature: {temperature:.1f}C, Humidity: {humidity:.1f}%") # Display readings
except OSError as e:
print("Failed to read DHT22 sensor.") # Handle sensor reading error
temperature = None # Set temperature to None if error occurs
humidity = None # Set humidity to None if error occurs
# Check environmental conditions and control the conveyor belt
if temperature is not None and humidity is not None:
# If temperature or humidity is out of the defined range, stop the belt
if (temperature < temp_low or temperature > temp_high or
humidity < humidity_low or humidity > humidity_high):
stop_belt()
else:
start_belt() # If conditions are normal, keep the belt running
time.sleep(2) # Wait 2 seconds before the next loop iteration