import time
from machine import Pin, PWM, ADC
import network
import ntptime
import urequests # Required for HTTP requests to ThingSpeak
import gc # For garbage collection to free up memory
# Pin assignments
pir_pins = [25, 33] # Motion Sensors for bulbs 1 and 2
led_pins = [26, 27] # LEDs for bulbs 1 and 2
ldr_pins = [34, 35] # LDRs for bulbs 1 and 2
# Initialize components
pir_sensors = [Pin(p, Pin.IN) for p in pir_pins]
led_pwms = [PWM(Pin(p), freq=1000) for p in led_pins]
ldrs = [ADC(Pin(p)) for p in ldr_pins]
# Constants
DIM_BRIGHTNESS = 100 # Brightness level for dim mode
BRIGHT_BRIGHTNESS = 800 # Brightness level for bright mode
LIGHT_THRESHOLD = 500 # Light intensity threshold for turning on LEDs
MOTION_BRIGHTNESS_DURATION = 10 # Duration (seconds) for maintaining bright mode after motion
# ThingSpeak Configuration
THING_SPEAK_API_KEY = "9U1ELSLF51BDGUT9" # Replace with your ThingSpeak API Key
THING_SPEAK_URL = "http://api.thingspeak.com/update" # Ensure the correct URL
# Variables
current_states = ["Off"] * 2 # Now for two bulbs
motion_timers = [0, 0] # Track motion timeout for each LED
# Wi-Fi Credentials
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# Connect to Wi-Fi
def connect_to_wifi():
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(WIFI_SSID, WIFI_PASSWORD)
attempts = 0
while not sta_if.isconnected() and attempts < 10: # Retry up to 10 times
print(".", end="")
time.sleep(0.5)
attempts += 1
if sta_if.isconnected():
print(" Connected!")
else:
print(" Wi-Fi connection failed!")
return False
return True
# Synchronize time with NTP server
def synchronize_time():
try:
print("Synchronizing time with NTP server...")
ntptime.settime()
print("Time synchronized!")
except Exception as e:
print("Failed to synchronize time:", e)
# Send data to ThingSpeak
def send_to_thingspeak(motion, ldr_value, light_state):
try:
# Convert light_state to a numeric value for ThingSpeak
if light_state == "Off":
light_state_value = 0
elif light_state == "Dim":
light_state_value = 1
elif light_state == "Bright":
light_state_value = 2
# Prepare the query string with your ThingSpeak API Key and fields
url = f"{THING_SPEAK_URL}?api_key={THING_SPEAK_API_KEY}&field1={motion}&field2={ldr_value}&field3={light_state_value}"
response = urequests.get(url, timeout=10) # Set a timeout for the HTTP request
response.close() # Close the response to free up resources
print("Data sent to ThingSpeak.")
except Exception as e:
print("Error sending data to ThingSpeak:", e)
time.sleep(5) # Wait for a while before retrying
# Main program
if connect_to_wifi():
synchronize_time()
while True:
# Get current time
current_time = time.localtime()
formatted_time = f"{current_time[3]:02}:{current_time[4]:02}:{current_time[5]:02}"
print(f"Current Time: {formatted_time}")
for i in range(2): # Iterate through each LED and sensor pair for 2 bulbs
ldr_value = ldrs[i].read()
motion_detected = pir_sensors[i].value()
if ldr_value < LIGHT_THRESHOLD: # If light intensity is below threshold
if motion_detected == 1:
led_pwms[i].duty(BRIGHT_BRIGHTNESS)
print(f"Bulb {i+1}: Motion detected, LED Bright")
current_states[i] = "Bright"
motion_timers[i] = time.time()
elif time.time() - motion_timers[i] > MOTION_BRIGHTNESS_DURATION:
led_pwms[i].duty(DIM_BRIGHTNESS)
print(f"Bulb {i+1}: No motion, LED Dim")
current_states[i] = "Dim"
else:
led_pwms[i].duty(DIM_BRIGHTNESS) # Maintain dim state
else: # If light intensity is above threshold
led_pwms[i].duty(0)
print(f"Bulb {i+1}: Light intensity high, LED Off")
current_states[i] = "Off"
# Send data to ThingSpeak after every loop iteration
send_to_thingspeak(motion_detected, ldr_value, current_states[i])
gc.collect() # Collect garbage to free up memory
time.sleep(1) # Sleep for 1 second before next iteration
else:
print("Failed to connect to Wi-Fi. Exiting...")