print("Program: Sensor Detection")
print("Date: 14/11/2024")
print("by jd")
# Import Libraries
import dht # Library to interface with DHT22 sensor
import machine # Library for configuring GPIO pins
import time # Library to handle delays
# Pin Declaration
data_pin = 13 # DHT22 connected to GPIO pin 13
# Object Declaration
sensor = dht.DHT22(machine.Pin(data_pin)) # Create DHT22 object on the specified pin
# Save Data to File
def save_data_to_file(temp, humidity):
#Function to save sensor data to a text file
try:
# Save data to a text file on the ESP32's filesystem
with open('/data.txt', 'a') as f: # Open file in append mode
f.write('Temperature: {:.2f}°C, Humidity: {:.2f}%\n'.format(temp, humidity))
print('Data saved to file.')
except Exception as e:
print('Failed to save data to file:', e)
# Main Program
def main():
"""Main program loop"""
print('DHT22 Sensor Program Running...')
while True:
try:
# Measure temperature and humidity
sensor.measure()
temp = sensor.temperature() # Temperature in Celsius
humidity = sensor.humidity() # Humidity in percentage
# Print the readings to the console (REPL)
print('Temperature: {:.2f}°C'.format(temp))
print('Humidity: {:.2f}%'.format(humidity))
# Save data to the file if the readings are valid
save_data_to_file(temp, humidity)
except OSError as e:
# Handle errors
print('Failed to read sensor:', e)
# Wait for 2 seconds before taking the next reading
time.sleep(2)
# Run the main program
if __name__ == '__main__':
main()