from machine import ADC
import time
# --- Sensor setup ---
ldr = ADC(26) # LDR connected to GP26 (ADC0)
# --- List to store readings ---
ldr_values = [] # start with empty list
TOTAL_SAMPLES = 10 # how many readings to take
INTERVAL_SEC = 2 # time gap between readings (seconds)
print("Taking", TOTAL_SAMPLES, "LDR readings...")
# --- Collect readings into the list ---
for i in range(TOTAL_SAMPLES):
value = ldr.read_u16() # read sensor value
ldr_values.append(value) # store in the list
print("Reading", i+1, "=", value)
time.sleep(INTERVAL_SEC)
print("\nAll readings:", ldr_values)
# --- Analyse the readings using list functions ---
highest = max(ldr_values)
lowest = min(ldr_values)
total = sum(ldr_values)
average = total / len(ldr_values)
print("\nAnalysis of LDR readings:")
print("Maximum value :", highest)
print("Minimum value :", lowest)
print("Average value :", average)
# -------------------------------------------------
# File Handling: save readings into CSV file
# -------------------------------------------------
FILENAME = "ldr_log.csv"
# 1) Open file in WRITE mode ("w")
f = open(FILENAME, "w")
# 2) Write header row (for Excel)
f.write("Sample,LDR_ADC\n")
# 3) Write each reading from the list as one row
for i in range(len(ldr_values)):
sample_no = i + 1
value = ldr_values[i]
line = str(sample_no) + "," + str(value) + "\n"
f.write(line)
# write analysis results at the end
f.write("\nMaximum," + str(highest) + "\n")
f.write("Minimum," + str(lowest) + "\n")
f.write("Average," + str(average) + "\n")
# 4) Close the file
f.close()
print("\nData saved to file:", FILENAME)