import machine
import network
import time
import urequests
import ujson
import math
# WiFi credentials
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = "<YOUR_WIFI_PASSWORD>" # Replace with your actual Wi-Fi password
# ThingSpeak API settings
THINGSPEAK_URL = "https://api.thingspeak.com/update"
THINGSPEAK_API_KEY = "FPUENL3IT4CV2A0R" # Replace with your ThingSpeak API key
# LDR sensor connected to an analog pin (GPIO 27)
LDR_SENSOR_PIN = machine.ADC(27)
# Constants for phototransistor characteristics
GAMMA = 0.7
RL10 = 50 # Resistance at 10 lux in kΩ
# Function to calculate lux based on ADC value
def calculate_lux(raw_adc):
# Convert ADC value (0 to 65535) to voltage (0 to 5V)
voltage = (raw_adc / 65535) * 5
# Calculate resistance based on voltage divider formula
resistance = 2000 * voltage / (1 - voltage / 5)
# Calculate lux using the given gamma and RL10
lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA))
return lux
# Function to read the LDR sensor
def read_ldr():
raw_adc = LDR_SENSOR_PIN.read_u16() # Read raw ADC value
lux = calculate_lux(raw_adc) # Convert raw ADC value to lux
return lux
# Function to send data to ThingSpeak using GET request
def send_data_to_thingspeak(lux):
# Prepare the URL with the lux value
url = f"{THINGSPEAK_URL}?api_key={THINGSPEAK_API_KEY}&field1={lux:.2f}"
# Send the GET request
try:
response = urequests.get(url)
print("ThingSpeak Response:", response.text) # Print the response for debugging
response.close()
except Exception as e:
print("Failed to send data to ThingSpeak:", e)
# 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():
print("Connecting to Wi-Fi...")
time.sleep(1)
print("Connected to Wi-Fi:", wifi.ifconfig())
# Main loop
if __name__ == "__main__":
try:
while True:
lux = read_ldr() # Read the light intensity in lux
print(f"Light Intensity (Lux): {lux:.2f}")
send_data_to_thingspeak(lux) # Send the lux value to ThingSpeak
print("Data sent to ThingSpeak")
time.sleep(5) # Send data every 5 seconds
except KeyboardInterrupt:
print("Program stopped.")