from machine import Pin
import network
import time
import dht
import wifi
import thing_speak as tsp
# Set up pin configurations
led_pin = 12
led = Pin(led_pin, Pin.OUT)
light_sensor_pin = 27
light_sensor = Pin(light_sensor_pin, Pin.IN)
dht_pin = 14
dht_sensor = dht.DHT22(Pin(dht_pin))
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)
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print("Connected!")
def update_thingspeak():
previous_light_state = -1
while True:
dht_sensor.measure()
# Get temperature and humidity readings
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
print("Temperature:", temperature, "Humidity:", humidity)
print("Updating to ThingSpeak...")
# Check if the light state changes when the LED turns on/off
current_light_state = light_sensor.value()
if previous_light_state != current_light_state:
previous_light_state = current_light_state
tsp.update_all(temperature, humidity, current_light_state)
else:
tsp.update_temp_and_hum(temperature, humidity)
time.sleep(5)
# Test reading API commands
last_command = tsp.read_command()
if last_command == "100":
led.on()
elif last_command == "0":
led.off()
time.sleep(5)
if __name__ == "__main__":
# Connect to WiFi
connect_to_wifi()
# Start updating ThingSpeak and processing commands
update_thingspeak()