# ============================================================
# 🧪 Experiment 2: Room Monitoring System (CSV Logging Version)
# Raspberry Pi Pico W + LDR (Lux) + DHT22 (Temp & Humidity)
# Uploads to ThingSpeak Fields 3, 4, and 5
# Records all data into readings.csv
# ============================================================
import machine, time, math, network, urequests, ujson, dht
# ---------- ThingSpeak ----------
THINGSPEAK_API_KEY = "FTPW74F3RMWELQH8"
THINGSPEAK_URL = "http://api.thingspeak.com/update"
# ---------- Wi-Fi ----------
WIFI_SSID = "UniMAP-WiFi"
WIFI_PASSWORD = "2210600121"
# ---------- LDR (Analog) ----------
ldr = machine.ADC(1) # GPIO27 = ADC1
VCC = 3.3
R_FIXED = 10000.0 # 10 kΩ resistor
GAMMA = 0.7
RL10 = 50.0 # kΩ at 10 Lux
# ---------- DHT22 (Digital) ----------
dht_sensor = dht.DHT22(machine.Pin(4)) # DATA pin on GPIO4
# ---------- Wi-Fi connection ----------
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
print("Connecting to Wi-Fi...", end="")
while not wlan.isconnected():
print(".", end="")
time.sleep(1)
print("\n✅ Connected:", wlan.ifconfig())
# ---------- Helper Functions ----------
def read_lux():
adc_val = ldr.read_u16()
voltage = adc_val / 65535.0 * VCC
if voltage <= 0.01 or voltage >= VCC - 0.01:
return 0.0
r_ldr = R_FIXED * voltage / (VCC - voltage)
lux = math.pow(RL10 * 1e3 * math.pow(10, GAMMA) / r_ldr, 1.0 / GAMMA)
return round(lux, 2)
def read_dht():
try:
dht_sensor.measure()
temp = dht_sensor.temperature()
hum = dht_sensor.humidity()
return round(temp, 2), round(hum, 2)
except OSError:
return None, None
def send_to_thingspeak(lux, temp, hum):
data = {
"api_key": THINGSPEAK_API_KEY,
"field3": lux,
"field4": temp,
"field5": hum
}
try:
r = urequests.post(
THINGSPEAK_URL,
data=ujson.dumps(data),
headers={"Content-Type": "application/json"}
)
print(f"✅ Data sent → Lux: {lux}, Temp: {temp}, Hum: {hum}")
r.close()
except Exception as e:
print("⚠️ ThingSpeak error:", e)
# ---------- Prepare CSV file ----------
file_name = "readings.csv"
with open(file_name, "w") as f:
f.write("time,lux,temp,hum,measured_delay\n") # header line
# ---------- Main Loop ----------
DELAY = 10 # 🔸 Change to 10,15,20,30,60 for Q5
previous_time = None
previous_ticks = None
while True:
start_ticks = time.ticks_ms()
# --- Sensor readings ---
lux = read_lux()
temp, hum = read_dht()
timestamp = time.localtime()
current_time = f"{timestamp[3]:02d}:{timestamp[4]:02d}:{timestamp[5]:02d}"
# --- Calculate measured delay ---
if previous_ticks is not None:
delay_ms = time.ticks_diff(start_ticks, previous_ticks)
delay_s = delay_ms / 1000.0
print(f"\n⏱ Current: {current_time} | Previous: {previous_time} | Measured Delay = {delay_s:.2f} s")
else:
delay_s = 0.0
print(f"\n⏱ Current: {current_time} | Previous: --- (first reading)")
# --- Display readings ---
print(f"Lux={lux} lx | Temp={temp} °C | Hum={hum}%")
# --- Send to ThingSpeak ---
if temp is not None and hum is not None:
send_to_thingspeak(lux, temp, hum)
else:
print("⚠️ DHT22 read failed, skipping upload")
# --- Save to CSV file ---
try:
with open(file_name, "a") as f:
f.write(f"{current_time},{lux},{temp},{hum},{delay_s:.2f}\n")
except Exception as e:
print("⚠️ CSV write error:", e)
# --- Adjust sleep to maintain total delay ---
elapsed_ms = time.ticks_diff(time.ticks_ms(), start_ticks)
elapsed_s = elapsed_ms / 1000.0
sleep_time = max(0, DELAY - elapsed_s)
print(f"⏳ Adjusted sleep = {sleep_time:.2f} s (Target delay = {DELAY}s)\n")
previous_time = current_time
previous_ticks = start_ticks
time.sleep(sleep_time)