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()
# Configurações Wi-Fi
WIFI_SSID = "Wifi_1"
WIFI_PASSWORD = "12345678"
while True:
def monitor():
sensor.measure()
temp = sensor.temperature()
humidity = sensor.humidity()
randUmid = random.uniform(0, 100)
randTemp = 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(randTemp), 0, 32)
oled.text("Umid Rand: {}%".format(randUmid), 0, 48)
oled.show()
def connect_wifi(ssid, password):
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('Conectando à rede Wi-Fi...')
wlan.connect(ssid, password)
while not wlan.isconnected():
pass
print('Conectado à rede Wi-Fi:', ssid)
print('Endereço IP:', wlan.ifconfig()[0])
def send_data_to_thingspeak():
api_key = "4YV866HAT2GTJ5E8"
temp = sensor.temperature()
humidity = sensor.humidity()
randTemp = random.uniform(-10, 40)
randUmid = random.uniform(0, 100)
def main():
# Conectar-se à rede Wi-Fi
connect_wifi(WIFI_SSID, WIFI_PASSWORD)
# Enviar dados para ThingSpeak
send_data_to_thingspeak()
api_key = "4YV866HAT2GTJ5E8"
# Enviar dados para ThingSpeak
url1 = f"https://api.thingspeak.com/update?api_key={api_key}&field1={temp}"
url2 = f"https://api.thingspeak.com/update?api_key={api_key}&field2={humidity}"
url3 = f"https://api.thingspeak.com/update?api_key={api_key}&field3={randTemp}"
url4 = f"https://api.thingspeak.com/update?api_key={api_key}&field4={randUmid}"
response1 = urequests.post(url1)
response2 = urequests.get(url2)
response3 = urequests.get(url3)
response4 = urequests.get(url4)
# Verificar se as solicitações foram bem-sucedidas
if response1.status_code == 200:
print('Dados enviados para ThingSpeak - Temp Real:', temp)
else:
print('Erro ao enviar dados para ThingSpeak - Temp Real:', response1.status_code)
if response2.status_code == 200:
print('Dados enviados para ThingSpeak - Umid Real:', humidity)
else:
print('Erro ao enviar dados para ThingSpeak - Umid Real:', response2.status_code)
if response3.status_code == 200:
print('Dados enviados para ThingSpeak - Temp Rand:', randTemp)
else:
print('Erro ao enviar dados para ThingSpeak - Temp Rand:', response3.status_code)
if response4.status_code == 200:
print('Dados enviados para ThingSpeak - Umid Rand:', randUmid)
else:
print('Erro ao enviar dados para ThingSpeak - Umid Rand:', response4.status_code)
# Fechar conexões
response1.close()
response2.close()
response3.close()
response4.close()
if __name__ == "__main__":
main()