from machine import Pin, RTC
import time
import dht

# Set up the onboard LED to blink to show activity

# NOTE: Using the onbaord LED is different for the Pi Pico vs Pi Pico W!

# Use this line for Pi Pico:
led = Pin(25, Pin.OUT)

# Use this line for Pi Pico W:
#led = machine.Pin('LED', machine.Pin.OUT)

# Create a Real Time Clock object.
# Note, the date and time will be set by Thonny if connected to a computer.
# When the Pi Pico is run disconnected from Thonny, the date at time will start at 01/01/2021 12:00AM.
rtc = RTC()

# Create a DHT objected and set the pin it's attached to.
# Be sure to use dht.DHT11 or dht.DHT22 depending on which sensor you are using!
sensor = dht.DHT22(Pin(28))


# Open/create a log.csv file to add data to.
logFile = open("log.csv", "a")

# Write the a CSV header line
logFile.write("Date time, Temperature, Humidity" + "\n")

#Close the file to avoid corruption.
logFile.close()

while True:
    # Tell our DHT11 sensor object to take measurement.
    sensor.measure()
    
    # Store the latest measurements in variables.
    temp = sensor.temperature()
    hum = sensor.humidity()
    
    # Get the current Date and Time from the Real Time Clock object.
    timestamp=rtc.datetime()
    
    # Format the Date and Time into an easy to read string.
    timestring="%04d-%02d-%02d %02d:%02d:%02d"%(timestamp[0:3] + timestamp[4:7])
    
    # Create a string that contains our Date and Time, Temperature and Humidity, each separated by a comma.
    csvLine = timestring + "," + str(temp) + "," + str(hum)
    
    # For testing when connected to Thonny, print out the csvLine to the shell.
    # This line can be removed/commented out when running live unconnected to a computer.
    print(csvLine)
    
    # Open/create a log.csv file to add data to.
    logFile = open("log.csv", "a")
    
    # Write the data to the file including adding "\n" to the end to end the line.
    logFile.write(csvLine + "\n")
    
    #Close the file to avoid corruption.
    logFile.close()
    
    # Blink LED so we know its still running when not connected to Thonny.
    led.on()
    time.sleep(.2)
    led.off()
    time.sleep(.2)

    # Sleep until we want to take another reading.
    time.sleep(3)

BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT