import network
from machine import Pin, PWM
import time
import dht
import json
from umqtt_simple import MQTTClient
AIO_USERNAME="Benita_Sharon"
AIO_KEY="aio_uHtn73OGrYzS902p9dQtGtXjuABn"
AIO_SERVER = "io.adafruit.com"
TEMPERATURE_LEVEL_FEED=f"{AIO_USERNAME}/feeds/temperature"
HUMIDITY_LEVEL_FEED=f"{AIO_USERNAME}/feeds/humidity"
AIO_FEED_MESSAGE = f"{AIO_USERNAME}/feeds/message"
# Pins and initial setup
TEMP_SENSOR_PIN = 28
fan_pwm = PWM(Pin(27))
fan_pwm.freq(1000)
fan_pwm.duty_u16(0)
DIR_PIN = Pin(7, Pin.OUT) # Direction pin
STEP_PIN = Pin(8, Pin.OUT) # Step pin
ENABLE_PIN = Pin(13, Pin.OUT) # Enable pin (optional)
ENABLE_PIN.off() # Enable motor driver
# Initialize DHT22 sensor
dht_sensor = dht.DHT22(Pin(TEMP_SENSOR_PIN))
# Connect to Wi-Fi
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("Wokwi-GUEST", "")
while not wlan.isconnected():
print("Connecting to WiFi...")
time.sleep(1)
print("Connected to WiFi:", wlan.ifconfig())
def connect_mqtt():
global client
client = MQTTClient("temperature-based-fan-control-1", AIO_SERVER, user=AIO_USERNAME, password=AIO_KEY)
try:
client.connect()
print("Connected to Adafruit IO!")
except Exception as e:
print("MQTT Connection Failed:", e)
machine.reset()
# Function to move stepper motor
def move_motor(steps, direction, speed=0.002):
step = int(steps)
if direction == "forward":
DIR_PIN.on() # Set direction forward
print("Moving forward")
elif direction == "backward":
DIR_PIN.off() # Set direction backward
print("Moving backward")
for _ in range(step):
STEP_PIN.on()
time.sleep(speed)
STEP_PIN.off()
time.sleep(speed)
def send_message(alert_msg):
send_data(AIO_FEED_MESSAGE, alert_msg)
print(f"Alert Sent: {alert_msg}")
def send_data(feed, value):
try:
payload = json.dumps({"value": value})
print(f"Sending {feed}: {payload}")
client.publish(feed, payload)
except Exception as e:
print(f"Failed to send {feed}: {e}")
connect_mqtt()
# Main loop
try:
connect_wifi()
client=connect_mqtt()
while True:
dht_sensor.measure()
temp = dht_sensor.temperature()
hum = dht_sensor.humidity()
# Log temperature and humidity
print(f"Temperature: {temp}°C, Humidity: {hum}%")
send_data(TEMPERATURE_LEVEL_FEED, temp)
send_data(HUMIDITY_LEVEL_FEED, hum)
# Automatic fan control
if temp > 30 and hum > 30:
fan_pwm.duty_u16(32768)
send_message("ITS TOO HOT! FAN TURNED ON")
move_motor(steps=100, direction="forward") # Move forward
time.sleep(5)
elif temp < 20 and hum < 20:
fan_pwm.duty_u16(32768)
send_message("ITS TOO COLD! FAN TURNED ON")
move_motor(steps=100, direction="backward") # Move forward
time.sleep(5)
else:
fan_pwm.duty_u16(0)
send_message("EVERYTHING IS FINE")
time.sleep(2) # Single delay after the entire condition
except KeyboardInterrupt:
print("Program stopped.")
fan_pwm.duty_u16(0) # Turn off fan
ENABLE_PIN.on() Loading
pi-pico-w
pi-pico-w