import time
import dht
import random
import urequests
from machine import Pin
from machine import I2C
from ssd1306 import SSD1306_I2C
import network
WIDTH = 128
HEIGHT = 64
sda_pin = Pin(0)
scl_pin = Pin(1)
sensor = dht.DHT22(Pin(28))
i2c = I2C(0, sda=sda_pin, scl=scl_pin, freq=400000)
oled = SSD1306_I2C(WIDTH, HEIGHT, i2c)
oled.fill(0) # Limpa o display
oled.show()
# conectar-se à rede Wi-Fi
print("Connecting to WiFi", end="")
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("Wokwi-GUEST", "")
while not wlan.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
print(wlan.ifconfig())
# Função para enviar dados para o ThingSpeak
def send_to_thingspeak(temp, humidity, rand_temp, rand_humidity):
api_key = "FQ5RJYQGUMKII6EA" # Substitua com sua API Key do ThingSpeak
url = "https://api.thingspeak.com/update?api_key={}&field1={}&field2={}&field3={}&field4={}".format(api_key, temp, humidity, rand_temp, rand_humidity)
response = urequests.get(url)
print("Dados enviados para ThingSpeak:", response.text)
response.close()
# Função principal para monitorar e enviar dados
def monitor_and_send():
while True:
sensor.measure()
temp = sensor.temperature()
humidity = sensor.humidity()
rand_umid = random.uniform(0, 100)
rand_temp = random.uniform(-10, 40)
# Limpar o display
oled.fill(0)
# Escrever temperatura e umidade no display
oled.text("Temp Real: {}C".format(temp), 0, 0)
oled.text("Umid Real: {}%".format(humidity), 0, 16)
oled.text("Temp Rand: {}C".format(rand_temp), 0, 32)
oled.text("Umid Rand: {}%".format(rand_umid), 0, 48)
oled.show()
# Enviar dados para o ThingSpeak
send_to_thingspeak(temp, humidity, rand_temp, rand_umid)
# Aguardar 15 segundos antes de ler novamente os sensores e enviar dados
time.sleep(15)
# Executar a função principal
monitor_and_send()