import network
import urequests
from machine import Pin
from time import sleep
SSID = "Wokwi-GUEST"
PASSWORD = ""
THINGSPEAK_API_KEY = "1L79H45SWEDW6VJ9"
THINGSPEAK_URL = "https://api.thingspeak.com/update?api_key=1L79H45SWEDW6VJ9&field1=0"
def connect_to_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
print("Activation du module Wi-Fi...")
wlan.connect(SSID, PASSWORD)
attempt = 0
while not wlan.isconnected():
attempt += 1
print(f"Tentative de connexion ({attempt})...")
sleep(1)
if attempt > 10: # Arrêter après 10 tentatives
print("Impossible de se connecter au Wi-Fi.")
return False
print("Connecté au Wi-Fi!")
print("Adresse IP:", wlan.ifconfig()[0])
return True
def send_to_thingspeak(motion_status):
url = f'https://api.thingspeak.com/update?api_key={THINGSPEAK_API_KEY}&field1={pir}'
try:
response = urequests.get(url)
print("Réponse ThingSpeak:", response.text)
response.close()
except Exception as e:
print("Erreur lors de l'envoi à ThingSpeak:", e)
motion = False
def handle_interrupt(pin):
global motion
motion = True
global interrupt_pin
interrupt_pin = pin
pir = Pin(13, Pin.IN)
pir.irq(trigger=Pin.IRQ_RISING, handler=handle_interrupt)
# Fonction pour afficher un message sur l'OLED
def display_message(message):
oled.fill(0) # Effacer l'écran
oled.text(message, 0, 0) # Afficher le message à la ligne 0
oled.show()
if connect_to_wifi():
while True:
if motion:
print("Mouvement détecté! Interrupt déclenché par:", interrupt_pin)
send_to_thingspeak(1)
sleep(20)
print("Mouvement arrêté!")
send_to_thingspeak(0)
motion = False
else:
sleep(1) # Attente pour éviter une boucle inutile
else:
print("Programme arrêté : Wi-Fi non connecté.")