import machine
import sdcard
import uos
import dht
import utime
# DHT11 data pin
dht_sensor = dht.DHT11(machine.Pin(5))
# Assign chip select (CS) pin (and start it high)
cs = machine.Pin(1, machine.Pin.OUT)
# Initialize 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")
# Run this in an infinite loop to continuously log sensor data
while True:
try:
dht_sensor.measure()
temp = dht_sensor.temperature # No parentheses here
humidity = dht_sensor.humidity # No parentheses here
# Create a file and write the sensor readings to it
with open("sensor_log.txt", "a") as file:
file.write("Temperature: {}C, Humidity: {}%\r\n".format(temp, humidity))
# Open the file we just created and read from it
with open("sensor_log.txt", "r") as file:
data = file.read()
print(data)
except Exception as e:
print('Failed to read sensor.', e)
# Sleep for 1 minute before next reading
utime.sleep(5)