import time
import network
import urequests
from machine import Pin, ADC, I2C
import dht
from ssd1306 import SSD1306_I2C
# --- Paramètres ThingSpeak ---
WRITE_API_KEY = "CR4LWERLVQIH0NW4"
THINGSPEAK_URL = "https://api.thingspeak.com/update"
# --- Initialisation des capteurs ---
dht_sensor = dht.DHT22(Pin(15))
ldr_pin = ADC(Pin(34))
ldr_pin.atten(ADC.ATTN_11DB)
# --- Paramètres du panneau solaire ---
P_STC = 300
beta = -0.004
T_STC = 25
G_STC = 1000
# --- Informations Wi-Fi ---
SSID = "Wokwi-GUEST"
PASSWORD = ""
# --- Initialisation OLED ---
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled = SSD1306_I2C(128, 64, i2c)
# --- Connexion Wi-Fi ---
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if wlan.isconnected():
print("Déjà connecté!")
return True
print("Connexion au Wi-Fi...")
wlan.connect(SSID, PASSWORD)
attempt = 0
while not wlan.isconnected():
attempt += 1
print(f"Tentative de connexion... (Wi-Fi {attempt})")
if attempt >= 10:
print("Échec de la connexion Wi-Fi.")
return False
time.sleep(1)
print("Connecté au Wi-Fi! Adresse IP:", wlan.ifconfig()[0])
return True
# --- Lecture des capteurs ---
def read_temperature():
try:
dht_sensor.measure()
return dht_sensor.temperature()
except Exception as e:
print("Erreur de lecture du capteur DHT22:", e)
return None
def read_irradiation():
raw_value = ldr_pin.read()
G = (raw_value / 4095) * G_STC
return G
def calculate_power(T, G):
if T is None or G is None:
return 0
P_pv = P_STC * (1 + beta * (T - T_STC)) * (G / G_STC)
return max(P_pv, 0)
# --- Affichage OLED ---
def display_on_oled(temperature, irradiation, power):
oled.fill(0) # Effacer l'écran
oled.text("System Status:", 0, 0)
oled.text(f"Temp: {temperature:.1f}C", 0, 15)
oled.text(f"Irrad: {irradiation:.1f}W/m2", 0, 30)
oled.text(f"Power: {power:.1f}W", 0, 45)
oled.show()
# --- Envoi à ThingSpeak ---
def send_to_thingspeak(power, temperature, irradiation):
url = f"{THINGSPEAK_URL}?api_key={WRITE_API_KEY}&field1={power}&field2={temperature}&field3={irradiation}"
try:
response = urequests.get(url)
print("Réponse de ThingSpeak:", response.text)
response.close()
except Exception as e:
print("Erreur d'envoi à ThingSpeak:", e)
# --- Fonction principale ---
def main():
if not connect_wifi():
return
while True:
temperature = read_temperature()
irradiation = read_irradiation()
power = calculate_power(temperature, irradiation)
print("Température (°C):", temperature)
print("Irradiation (W/m²):", irradiation)
print("Puissance (W):", power)
# Affichage OLED
display_on_oled(temperature, irradiation, power)
# Envoi à ThingSpeak
send_to_thingspeak(power, temperature, irradiation)
time.sleep(60)
# --- Lancer le programme ---
main()