from machine import Pin, I2C
import network
import urequests
import time
import sys
from dht import DHT22
from ssd1306 import SSD1306_I2C
# OLED display dimensions
WIDTH = 128
HEIGHT = 64
# Initialize I2C and OLED display
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled = SSD1306_I2C(WIDTH, HEIGHT, i2c)
# Initialize the DHT22 sensor on Pin 12
dht22 = DHT22(Pin(12))
# WiFi credentials
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# Thingspeak HTTP API Protocol
HTTP_HEADERS = {'Content-Type': 'application/json'}
THINGSPEAK_WRITE_API_KEY = 'RF15DXDSCKTW9SV9' # Replace with your actual API key
# Function to connect to WiFi
def connect_wifi():
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.disconnect()
wifi.connect(WIFI_SSID, WIFI_PASSWORD)
if not wifi.isconnected():
print('Connecting...')
timeout = 0
while not wifi.isconnected() and timeout < 10:
print(f"Retrying in {10 - timeout} seconds")
timeout += 1
time.sleep(1)
if wifi.isconnected():
print('Connected to WiFi')
else:
print('Failed to connect to WiFi')
sys.exit()
print('Network config:', wifi.ifconfig())
# Function to read temperature and humidity from the DHT22 sensor
def read_dht():
try:
dht22.measure()
return dht22.temperature(), dht22.humidity()
except OSError as e:
print(f"Failed to read DHT22 sensor: {e}")
return None, None
# Function to display data on OLED
def display_on_oled(temp, hum):
oled.fill(0) # Clear the display
oled.text(f"Temp: {temp:.1f} C", 0, 0)
oled.text(f"Hum: {hum:.1f} %", 0, 20)
oled.show()
# Connect to WiFi
connect_wifi()
while True:
# Read temperature and humidity
temp, hum = read_dht()
if temp is not None and hum is not None:
print(f"Temperature: {temp}°C")
print(f"Humidity: {hum}%")
# Display the data on the OLED
display_on_oled(temp, hum)
# Prepare data for ThingSpeak
dht_readings = {'field1': temp, 'field2': hum}
# Send data to ThingSpeak
try:
request = urequests.post(f'http://api.thingspeak.com/update?api_key={THINGSPEAK_WRITE_API_KEY}', json=dht_readings, headers=HTTP_HEADERS)
request.close()
print("Message sent to ThingSpeak channel successfully...")
except Exception as e:
print(f"Failed to send data to ThingSpeak: {e}")
print("********************************************")
time.sleep(15) # Wait for 15 seconds before sending the next reading