import machine
import sdcard
import os
import time
# Define pin connections
ldr_pin = machine.ADC(26) # LDR sensor connected to Pin GP26 (ADC0)
spi = machine.SPI(0, baudrate=1000000, sck=machine.Pin(18), mosi=machine.Pin(19), miso=machine.Pin(16))
cs_pin = machine.Pin(17) # CS pin for SD card
# Initialize microSD card
sd = sdcard.SDCard(spi, cs_pin)
# Function to read LDR sensor data
def read_ldr():
ldr_value = ldr_pin.read_u16()
return ldr_value
# Function to log data to SD card
def log_data(ldr_value):
with open('/sd/ldr_log.txt', 'a') as file:
file.write("{},{}\n".format(time.time(), ldr_value))
# Mount the SD card
os.mount(sd, '/sd')
# Main loop
try:
while True:
# Read LDR sensor data
ldr_value = read_ldr()
# Log data to SD card
log_data(ldr_value)
# Print data (optional)
print("LDR Value:", ldr_value)
# Delay before next reading
time.sleep(1) # Adjust delay as needed
except KeyboardInterrupt:
# Unmount the SD card and clean up
os.umount('/sd')