import machine
import network
import time
import urequests
import ujson
# WiFi credentials
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# ThingSpeak API settings
THINGSPEAK_API_KEY = "V6XLVG6IBUBJLMGY"
THINGSPEAK_URL = "http://api.thingspeak.com/update"
# ldr sensor connected to an analog pin
LDR_SENSOR_PIN = machine.ADC(1)
# Function to read analog pin
def read_ldr():
ldr_data = LDR_SENSOR_PIN.read_u16()
return ldr_data
# Function to send data to ThingSpeak
def send_data_to_thingspeak(ldr):
data = {
"api_key": THINGSPEAK_API_KEY,
"field1": ldr,
}
response = urequests.post(THINGSPEAK_URL, data=ujson.dumps(data), headers={"Content-Type": "application/json"})
response.close()
# Initialize the Wi-Fi connection
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(WIFI_SSID, WIFI_PASSWORD)
# Wait for the Wi-Fi connection to establish
while not wifi.isconnected():
time.sleep(1)
print("Connected to Wi-Fi")
if __name__== "__main__":
try:
while True:
ldr = read_ldr()
print(f"Lux: {ldr}")
send_data_to_thingspeak(ldr)
print("Data sent to ThingSpeak")
time.sleep(15) # Send data every 15 seconds (adjust the interval as needed)
except KeyboardInterrupt:
pass