import machine
import network
import time
import urequests
import ujson
# WiFi credentials
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# ThingSpeak API settings
THINGSPEAK_API_KEY = "YOUR_THINGSPEAK_API_KEY"
THINGSPEAK_URL = "https://api.thingspeak.com/update?api_key=" + THINGSPEAK_API_KEY + "&field1=0"
# LDR sensor connected to an analog pin
LDR_SENSOR_PIN = machine.ADC(1)
# Calibration data (replace with your own values)
calibration_data = {
1000: 100, # Example: LDR value 1000 corresponds to 100 lux
2000: 200, # Example: LDR value 2000 corresponds to 200 lux
# Add more calibration points as needed
}
# Function to read analog pin
def read_ldr():
ldr_data = LDR_SENSOR_PIN.read_u16()
return ldr_data
# Function to convert LDR values to lux
def ldr_to_lux(ldr_value):
# Interpolate lux value based on calibration data
ldr_values = sorted(calibration_data.keys())
lux_values = [calibration_data[ldr] for ldr in ldr_values]
# Interpolation
for i in range(len(ldr_values) - 1):
if ldr_values[i] <= ldr_value <= ldr_values[i + 1]:
lux_range = lux_values[i + 1] - lux_values[i]
ldr_range = ldr_values[i + 1] - ldr_values[i]
lux_per_unit_ldr = lux_range / ldr_range
return lux_values[i] + (ldr_value - ldr_values[i]) * lux_per_unit_ldr
return None # Return None for values outside the calibration range
# Function to send data to ThingSpeak
def send_data_to_thingspeak(ldr):
lux = ldr_to_lux(ldr)
if lux is not None:
data = {
"api_key": THINGSPEAK_API_KEY,
"field1": lux,
}
response = urequests.post(THINGSPEAK_URL, data=ujson.dumps(data), headers={"Content-Type": "application/json"})
response.close()
print(f"Lux: {lux}")
print("Data sent to ThingSpeak")
# 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()
send_data_to_thingspeak(ldr)
time.sleep(15) # Send data every 15 seconds (adjust the interval as needed)
except KeyboardInterrupt:
pass