# Rui Santos & Sara Santos - Random Nerd Tutorials
# Complete project details at https://RandomNerdTutorials.com/raspberry-pi-pico-ds3231-rtc-micropython/
# 1.4 take out debug statements
import time
import urtc
from machine import I2C, Pin, ADC
days_of_week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
# Initialize RTC (connected to I2C channel 0)
# definition for Waveshare configuration
i2c = I2C(0, scl=Pin(21), sda=Pin(20))
rtc = urtc.DS3231(i2c)
# Initialize temperature and humidity probe (connected to I2C channel 1)
TH_i2c = I2C(1, scl=Pin(7), sda=Pin(6), freq=100000)
# Initialize soil moisture probe input
sensor_AO = ADC(26)
#---------------------------------------------------------------------------------
#Temperature and humidity probe
#------------------------------------------------------------------------------
I2C_ADDRESS = 0x44
MEASURE_CMD = b'\x2C\x10'
# end temperature and humidity probe setup
#---------------------------------------------------------------------------------
#definition for temperature/humidity probe
#library not needed for time and humdity probe. Reads registers directly and converts to correct units.
def read_temperature_humidity():
try:
TH_i2c.writeto(I2C_ADDRESS, MEASURE_CMD)
time.sleep_ms(100)#allow probe to stabilize for reading
data = TH_i2c.readfrom(I2C_ADDRESS, 6)
if len(data) == 6:
temp_raw = data[0] << 8 | data[1]
hum_raw = data[3] << 8 | data[4]
temperature = -45 + (175 * temp_raw / 65535)
humidity = 100 * hum_raw / 65535
return temperature, humidity
else:
raise Exception("Invalid response length")
except OSError as e:
return None, None
#-----------------------------------------------------------------------------------
# end temperature/humidity probe definition
#--------------------------------------------------------------------------------------------------
def get_current_time():
now = rtc.datetime()
formatted_time = f"{now.year}-{now.month:02}-{now.day:02}, {now.hour:02}:{now.minute:02}:{now.second:02}"
return formatted_time
#--------------------------------------------------------------------------------------
# body of program
#--------------------------------------------------------------------------------------
#get temp and humidity from probe
devices = TH_i2c.scan()#make sure probe is present
with open('record.txt','a') as f:
if I2C_ADDRESS in devices:
temp, hum = read_temperature_humidity()
moisture=sensor_AO.read_u16()
if temp is not None:
f.write(get_current_time() +", "+ str(temp)+", "+ str(hum)+", "+ str(moisture)+"\n")
else:
f.write("Failed to read data from sensor"+ "\n")
else:
f.write("Sensor not detected"+ "\n")
#------------------------------------------------------------------------------------
#RTC alread on timed interrupt. Only necessary to turn it off. Don't need to reset.
time.sleep_ms(10)# allow chip to stablize before turning off
rtc.alarm(False, 0)# turn off alarm, power lost here