67 lines
1.5 KiB
Arduino
67 lines
1.5 KiB
Arduino
|
#include <ESP8266WiFi.h>
|
||
|
#include <PubSubClient.h>
|
||
|
|
||
|
// Configurations WiFi et MQTT
|
||
|
const char* ssid = "Redmi Note 13 Pro 5G";
|
||
|
const char* password = "1234567890";
|
||
|
const char* mqtt_server = "192.168.127.208";
|
||
|
const char* mqtt_topic = "bouton/etat";
|
||
|
|
||
|
// Déclaration des broches
|
||
|
#define BUTTON_PIN D8
|
||
|
|
||
|
WiFiClient espClient;
|
||
|
PubSubClient client(espClient);
|
||
|
|
||
|
void setup_wifi() {
|
||
|
delay(10);
|
||
|
Serial.println();
|
||
|
Serial.print("Connexion au WiFi...");
|
||
|
WiFi.begin(ssid, password);
|
||
|
|
||
|
while (WiFi.status() != WL_CONNECTED) {
|
||
|
delay(500);
|
||
|
Serial.print(".");
|
||
|
}
|
||
|
|
||
|
Serial.println("");
|
||
|
Serial.println("WiFi connecté");
|
||
|
Serial.print("Adresse IP: ");
|
||
|
Serial.println(WiFi.localIP());
|
||
|
}
|
||
|
|
||
|
void reconnect() {
|
||
|
while (!client.connected()) {
|
||
|
Serial.print("Connexion au broker MQTT...");
|
||
|
if (client.connect("ESP8266Client")) {
|
||
|
Serial.println("connecté");
|
||
|
} else {
|
||
|
Serial.print("échec, rc=");
|
||
|
Serial.print(client.state());
|
||
|
Serial.println("; nouvelle tentative dans 5 secondes");
|
||
|
delay(5000);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
void setup() {
|
||
|
Serial.begin(115200);
|
||
|
pinMode(BUTTON_PIN, INPUT_PULLUP);
|
||
|
|
||
|
setup_wifi();
|
||
|
client.setServer(mqtt_server, 1883);
|
||
|
}
|
||
|
|
||
|
void loop() {
|
||
|
if (!client.connected()) {
|
||
|
reconnect();
|
||
|
}
|
||
|
client.loop();
|
||
|
|
||
|
// Vérifier si le bouton est pressé
|
||
|
if (digitalRead(BUTTON_PIN) == HIGH) {
|
||
|
Serial.println("Bouton pressé, envoi du message...");
|
||
|
client.publish(mqtt_topic, "Bouton presse");
|
||
|
delay(200); // Anti-rebond pour éviter les publications multiples
|
||
|
}
|
||
|
}
|