import network
import time
import urequests
# Wi-Fi Wokwi
SSID = "Wokwi-GUEST"
PASSWORD = ""
# ====== ThingSpeak ======
WRITE_API_KEY = "C4XCAS4RMT4Z5HMS"
URL = "https://api.thingspeak.com/update"
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
wlan.connect(SSID, PASSWORD)
print("Connexion Wi-Fi...")
t0 = time.ticks_ms()
while not wlan.isconnected():
if time.ticks_diff(time.ticks_ms(), t0) > 15000:
raise RuntimeError("Timeout Wi-Fi")
time.sleep(0.2)
print("Connecté :", wlan.ifconfig())
def send_to_thingspeak(temp, hum):
# ThingSpeak attend field1, field2, ...
body = "api_key={}&field1={}&field2={}".format(WRITE_API_KEY, temp, hum)
headers = {
"Content-Type": "application/x-www-form-urlencoded"
}
print("Body:", body)
r = urequests.post(URL, data=body, headers=headers)
print("Status:", r.status_code)
print("Réponse:", r.text) # normalement un numéro d'entrée (ex: "123")
r.close()
connect_wifi()
time.sleep(1)
while True:
try:
# Exemple valeurs (remplace par capteur réel si tu veux)
temperature = 25.4
humidity = 58
send_to_thingspeak(temperature, humidity)
except Exception as e:
print("Erreur:", e)
time.sleep(20) # ThingSpeak minimum 15 sec entre envois