from machine import Pin, ADC
from time import sleep
import network
import urequests
# ================== WIFI (REAL PICO WH) ==================
SSID = "iPhone" # Replace with your hotspot SSID
PASSWORD = "faris123" # Replace with your hotspot password
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)
print("Connecting to WiFi...")
while not wlan.isconnected():
sleep(1)
print("WiFi Connected:", wlan.ifconfig())
# ================== THINGSPEAK ==================
WRITE_API_KEY = "MNX6JFE1DJ7IGRT8"
THINGSPEAK_URL = "https://api.thingspeak.com/update"
# ================== HARDWARE ==================
led_pins = [2,3,4,5,6,7,8,9,10,11]
leds = [Pin(p, Pin.OUT) for p in led_pins]
ldr = ADC(26) # GPIO26 / ADC0
# ================== MAP LDR VALUE TO LED COUNT ==================
def map_ldr_to_leds(value):
"""
Convert ADC value (0-65535) to LED count (0-10)
Darker -> more LEDs ON
"""
inverted = 65535 - value
# smoother mapping, avoid rounding problems
led_count = int((inverted / 65535) * 11)
return max(0, min(11, led_count))
# ================== SEND DATA TO THINGSPEAK ==================
def send_to_thingspeak(ldr_value, led_count):
url = f"{THINGSPEAK_URL}?api_key={WRITE_API_KEY}&field1={ldr_value}&field2={led_count}"
try:
r = urequests.get(url)
r.close()
except:
print("Failed to send data to ThingSpeak")
# ================== MAIN LOOP ==================
while True:
# Read LDR
ldr_value = ldr.read_u16()
led_count = map_ldr_to_leds(ldr_value)
# Update LEDs immediately
for i in range(10):
leds[i].value(i < led_count)
# Debug print
print("Raw LDR:", ldr_value, "LEDs ON:", led_count)
# Send to ThingSpeak every 15s
send_to_thingspeak(ldr_value, led_count)
sleep(5)