import network
import time
import dht
from machine import Pin, PWM
from umqtt.simple import MQTTClient
import ubinascii
# WiFi Credentials
ssid = 'SpectrumSetup-55'
password = 'loudowner233'
# ThingSpeak MQTT Credentials
mqtt_server = 'mqtt.thingspeak.com'
channel_id = '2472863'
api_write_key = 'OPNJT3H56U6NQ8XF'
client_id = ubinascii.hexlify(machine.unique_id())
topic = b"channels/" + channel_id.encode() + b"/publish/" + api_write_key.encode()
# Initialize sensors and actuators
dht_sensor = dht.DHT11(Pin(4)) # DHT sensor connected to pin 4
motion_sensor = Pin(5, Pin.IN) # Motion sensor connected to pin 5
led = Pin(2, Pin.OUT) # LED connected to pin 2
servo = PWM(Pin(23), freq=50) # Servo motor connected to pin 23
def connect_wifi():
"""Connects the device to WiFi."""
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('Connecting to network...')
sta_if.active(True)
sta_if.connect(ssid, password)
while not sta_if.isconnected():
pass
print('Network connected:', sta_if.ifconfig())
def map_range(x, in_min, in_max, out_min, out_max):
"""Maps a value from one range to another."""
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
def set_servo_angle(angle):
"""Sets the servo motor to a specific angle."""
duty = map_range(angle, 0, 180, 40, 115)
servo.duty(int(duty))
def mqtt_connect():
"""Connects to the MQTT broker."""
client = MQTTClient(client_id, mqtt_server)
client.connect()
print("Connected to MQTT broker")
return client
# Connect to WiFi
connect_wifi()
# Connect to MQTT
mqtt_client = mqtt_connect()
while True:
try:
# Read sensor data
dht_sensor.measure()
temp = dht_sensor.temperature()
humidity = dht_sensor.humidity()
motion_detected = motion_sensor.value()
# LED control based on motion
if motion_detected:
led.on()
else:
led.off()
# Servo control based on temperature
if temp < 20:
set_servo_angle(0)
elif temp >= 20 and temp < 25:
set_servo_angle(90)
else:
set_servo_angle(180)
# Prepare data payload
payload = 'field1={}&field2={}&field3={}'.format(temp, humidity, motion_detected)
# Publish data to ThingSpeak
mqtt_client.publish(topic, payload)
print("Published data to ThingSpeak")
time.sleep(15) # Delay to match ThingSpeak's publishing rate limit
except OSError as e:
print("Failed to read sensor or publish data", e)