import time
import dht
from machine import Pin, ADC, time_pulse_us
# --- Sensor Setup ---
# DHT22 Sensor
dht_sensor = dht.DHT22(Pin(15))
# Ultrasonic Sensor
TRIG = Pin(5, Pin.OUT)
ECHO = Pin(18, Pin.IN)
# LDR Sensor (Photoresistor)
ldr = ADC(Pin(34)) # Analog pin
ldr.atten(ADC.ATTN_11DB) # full range 0-3.3V
# Potentiometer
pot = ADC(Pin(35))
pot.atten(ADC.ATTN_11DB)
# --- Helper Functions ---
def get_distance():
TRIG.value(0)
time.sleep_us(2)
TRIG.value(1)
time.sleep_us(10)
TRIG.value(0)
duration = time_pulse_us(ECHO, 1, 30000) # wait for HIGH
distance = (duration / 2) * 0.0343 # cm
return distance
# --- Create CSV File with Header ---
with open("MultiSensor_Data.csv", "w") as f:
f.write("S.NO,Temperature,Humidity,Distance,Light,Potentiometer\n")
print("✅ CSV file created with header")
# --- Data Logging Loop ---
s_no = 1
while True:
try:
# Read DHT22
dht_sensor.measure()
temp = dht_sensor.temperature()
hum = dht_sensor.humidity()
# Read Ultrasonic
dist = get_distance()
# Read LDR (scaled 0–1023)
light_val = ldr.read() // 4
# Read Potentiometer (scaled 0–1023)
pot_val = pot.read() // 4
# Append to CSV
with open("MultiSensor_Data.csv", "a") as f:
f.write("{},{:.1f},{:.1f},{:.1f},{},{}\n".format(
s_no, temp, hum, dist, light_val, pot_val))
print(f"📤 Row {s_no} -> Temp={temp}°C, Hum={hum}%, Dist={dist:.1f}cm, Light={light_val}, Pot={pot_val}")
s_no += 1
if s_no > 10: # stop after 10 rows (you can remove this limit)
print("✅ Finished writing 10 rows")
break
time.sleep(2) # delay between readings
except Exception as e:
print("⚠️ Sensor Error:", e)
time.sleep(2)