import network
import urequests
import time
from machine import Pin, reset
from dht import DHT22
# Define the DHT sensor
dht_sensor = DHT22(Pin(15))
# WiFi credentials
SSID = 'Wokwi-GUEST'
PASSWORD = ''
# Google Apps Script details
GAS_ID = "AKfycbwTyCB9MF1fbra_8wNr0Ao7MMmwc5_PMcSRmK7gk4bKzeyDxJJLBFswgKhHxhCy8yw9" # Replace with your new deployment ID
# Constants
MAX_RETRIES = 3
RETRY_DELAY = 5
MEASUREMENT_INTERVAL = 10
def connect_wifi():
"""Connect to WiFi"""
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('Connecting to WiFi...', end='')
wlan.connect(SSID, PASSWORD)
retry = 0
while not wlan.isconnected() and retry < 20: # 10 second timeout
print('.', end='')
time.sleep(0.5)
retry += 1
print('')
if wlan.isconnected():
print('WiFi Connected, IP:', wlan.ifconfig()[0])
return True
else:
print('WiFi Connection failed')
return False
def read_sensor():
"""Read DHT sensor data"""
try:
dht_sensor.measure()
temp = round(dht_sensor.temperature(), 1)
hum = round(dht_sensor.humidity(), 1)
if -40 <= temp <= 80 and 0 <= hum <= 100: # Basic validation
return temp, hum
print('Invalid sensor readings: Temp={}, Hum={}'.format(temp, hum))
return None, None
except Exception as e:
print('Sensor reading failed:', e)
return None, None
def send_to_sheet(temp, hum):
"""Send data to Google Sheet"""
url = "https://script.google.com/macros/s/{}/exec?temperature={}&humidity={}".format(
GAS_ID, temp, hum
)
print('\nSending data to:', url)
for attempt in range(MAX_RETRIES):
try:
response = urequests.get(url)
print('Response status:', response.status_code)
try:
print('Response content:', response.text)
except:
print('Could not read response content')
response.close()
if response.status_code == 200:
return True
except Exception as e:
print('Attempt {}/{} failed: {}'.format(attempt + 1, MAX_RETRIES, e))
if attempt < MAX_RETRIES - 1:
print('Retrying in {} seconds...'.format(RETRY_DELAY))
time.sleep(RETRY_DELAY)
return False
def main():
"""Main function"""
print('\nStarting DHT Logger')
print('Server URL: https://script.google.com/macros/s/{}/exec'.format(GAS_ID))
while True:
try:
# Ensure WiFi is connected
if not connect_wifi():
print('Will retry WiFi in {} seconds...'.format(MEASUREMENT_INTERVAL))
time.sleep(MEASUREMENT_INTERVAL)
continue
# Read sensor
temperature, humidity = read_sensor()
if temperature is not None:
print('\nTemperature: {}°C'.format(temperature))
print('Humidity: {}%'.format(humidity))
# Send to Google Sheet
if send_to_sheet(temperature, humidity):
print('Data sent successfully')
else:
print('Failed to send data')
except Exception as e:
print('Main loop error:', e)
print('\nWaiting {} seconds...'.format(MEASUREMENT_INTERVAL))
time.sleep(MEASUREMENT_INTERVAL)
if __name__ == '__main__':
try:
main()
except Exception as e:
print('Fatal error:', e)
time.sleep(5)
reset()