Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
MQTT-Group3/Chen Yiyan-README
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
62 lines (49 sloc)
1.52 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import paho.mqtt.client as mqtt | |
from machine import Pin, ADC, PWM | |
# Constants | |
BROKER = "broker.hivemq.com" | |
PORT = 1883 | |
TOPIC_LIGHT = "home/light/intensity" | |
TOPIC_MOTION = "home/motion" | |
TOPIC_CONTROL = "home/control" | |
CLIENT_ID = "ESP8266_LightControl" | |
# Pin setup | |
light_sensor = ADC(Pin(32)) # Light sensor pin | |
motion_sensor = Pin(14, Pin.IN) # Motion sensor pin | |
led = PWM(Pin(15), freq=5000) # LED pin | |
# MQTT setup | |
client = mqtt.Client(CLIENT_ID) | |
client.connect(BROKER, PORT, 60) | |
def read_light_sensor(): | |
return light_sensor.read() | |
def read_motion_sensor(): | |
return motion_sensor.value() | |
def control_led(brightness): | |
led.duty(brightness) | |
def on_message(client, userdata, message): | |
payload = message.payload.decode("utf-8") | |
if message.topic == TOPIC_CONTROL: | |
if payload == "on": | |
control_led(1023) # Full brightness | |
elif payload == "off": | |
control_led(0) # Turn off | |
client.on_message = on_message | |
client.subscribe(TOPIC_CONTROL) | |
client.loop_start() | |
try: | |
while True: | |
light_intensity = read_light_sensor() | |
motion_detected = read_motion_sensor() | |
# Adjust LED brightness based on light intensity | |
if light_intensity < 3000: | |
control_led(1023) | |
else: | |
control_led(0) | |
# Publish sensor data | |
client.publish(TOPIC_LIGHT, light_intensity) | |
client.publish(TOPIC_MOTION, motion_detected) | |
time.sleep(1) | |
finally: | |
client.loop_stop() | |
client.disconnect() |