# Use the Machine library from MicroPython to access pins on the Pico.
from machine import Pin
# utime is a verion of Python's "time" library
# that's been optimized for MicroPython
import utime
from dht import DHT11 # if the sensor is DHT11, import DHT11 instead of DHT22
# Create a variable that tells Python which Pin the LED is attached to.
led = machine.Pin(25, machine.Pin.OUT)
# Change DHT22 to DHT11 if DHT11 is used
dht = DHT11(Pin(15))
# Create a Real Time Clock (RTC) variable
rtc=machine.RTC()
# Open up a CSV file to store our data
file = open("temps.csv", "w")
# Write headers to the CSV file
file.write("date_time,temp,humidity\n")
# Create a loop that takes readings every 2 seconds.
while True:
# Toggle the LED to serve as a status light
led.toggle()
# Get the sensor readings
dht.measure()
temp = (1.8 * dht.temperature()) +32
hum = dht.humidity()
# Get the current time and format it
timestamp = rtc.datetime()
timestring = "%04d-%02d-%02d %02d:%02d:%02d"%(timestamp[0:3] + timestamp[4:7])
# Display the values to the console
print(f"Time: {timestring} Temperature: {temp}°F Humidity: {hum}% ")
# Write the values to the CSV
file.write(timestring + "," + str(temp) + "," + str(hum) + "\n")
# Flush the buffer
# Pause the code for at least 2 secs because DHT11/DHT22 takes a reading once every 2 secs
utime.sleep(2)