import time
import network
import urequests
from machine import Pin, I2C
from ssd1306 import SSD1306_I2C
from dht import DHT22
# Constants
THINGSPEAK_WRITE_API = "SV85Z386SSZYXJFR" # Replace with your ThingSpeak API key
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASS = ""
# I2C and OLED Setup
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=100000) # Pins for Wokwi simulation
oled = SSD1306_I2C(128, 64, i2c)
# DHT22 Sensor
dht = DHT22(Pin(15)) # Connect the DHT22 sensor to pin 15
# Simulated BMP280 Pressure
def read_pressure():
return 1013.25 # Simulate normal atmospheric pressure in hPa
# Connect to Wi-Fi
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASS)
timeout = 15 # 15 seconds timeout
while not wlan.isconnected() and timeout > 0:
print("Connecting to Wi-Fi...")
time.sleep(1)
timeout -= 1
if wlan.isconnected():
print("Connected to Wi-Fi")
print("IP Address:", wlan.ifconfig()[0])
else:
print("Failed to connect to Wi-Fi.")
raise Exception("Wi-Fi connection failed")
connect_wifi()
# Main loop
while True:
try:
# Read DHT22 data
dht.measure()
temperature = dht.temperature()
humidity = dht.humidity()
# Read BMP280 data (simulated)
pressure = read_pressure()
# Display data on OLED
oled.fill(0)
oled.text(f"Temp: {temperature:.1f}C", 0, 0)
oled.text(f"Hum: {humidity:.1f}%", 0, 10)
oled.text(f"Press: {pressure:.1f}hPa", 0, 20)
oled.show()
# Send data to ThingSpeak
url = f"https://api.thingspeak.com/update?api_key={THINGSPEAK_WRITE_API}&field1={temperature}&field2={humidity}&field3={pressure}"
response = urequests.get(url)
print("ThingSpeak Response:", response.text)
response.close()
time.sleep(30) # Update every 30 seconds
except Exception as e:
print("Error:", e)
time.sleep(10) # Retry after 10 seconds