from machine import Pin
import time
import sdcard
import dht
import uos
# Assign chip select (CS) pin (and start it high)
cs = machine.Pin(1, machine.Pin.OUT)
# Intialize SPI peripheral (start with 1 MHz)
spi = machine.SPI(0,
baudrate=1000000,
polarity=0,
phase=0,
bits=8,
firstbit=machine.SPI.MSB,
sck=machine.Pin(2),
mosi=machine.Pin(3),
miso=machine.Pin(4))
# Initialize SD card
sd = sdcard.SDCard(spi, cs)
# Mount filesystem
vfs = uos.VfsFat(sd)
uos.mount(vfs, "/sd")
# Defining sensor pins
light_sensor_pin = Pin(17)
dht_sensor = dht.DHT22(Pin(14))
adc = ADC(28)
# Defining filter window size [number of samples to average]
filter_window_size = 5
# Initialize variables to store past sensor readings
past_temp_readings = [0] * filter_window_size
past_light_readings = [0] * filter_window_size
current_filter_index = 0
# Function to read temperature and humidity
def read_temperature():
try:
dht_sensor.measure()
return dht_sensor.temperature()
except Exception as e:
print("Failed to read from DHT sensor:", e)
return None
# Function to read light sensor
def read_light():
d = adc.read_u16()
volt=3.3*(d/65535)
resistance = 2000 * volt / (1 - volt / 5)
lux = pow(50 * 1e3 * pow(10, 0.7) / resistance, (1 / 0.7))
return lux
# Function to apply moving average filter
def apply_moving_average(data_list, new_value):
# Add new value to the list and remove the oldest value
data_list[current_filter_index] = new_value
current_filter_index = (current_filter_index + 1) % filter_window_size
# Calculate the average of the data points in the list
return sum(data_list) / len(data_list)
while True:
# Read sensor data
raw_temperature = read_temperature()
raw_light_level = read_light()
# Apply moving average filter to sensor data
filtered_temperature = apply_moving_average(past_temp_readings, raw_temperature)
filtered_light_level = apply_moving_average(past_light_readings, raw_light_level)
# Get current timestamp
timestamp = time.time()
# Format data for storage
data_string = f"{timestamp},{filtered_temperature},{filtered_light_level}\n"
# Open file for data appending
with open("/sd/data.txt", "a") as f:
f.write(data_string)
# Adjust sleep time based on desired data collection frequency
time.sleep(5) # Collect data every 5 seconds
# Unmount SD card when finished (optional)
sd.umount(vfs)