2024-10-07 18:38:43 +02:00
|
|
|
#include <ESP8266WiFi.h>
|
|
|
|
#include <PubSubClient.h>
|
|
|
|
|
|
|
|
// Configurations WiFi et MQTT
|
2024-11-04 18:14:46 +01:00
|
|
|
const char* ssid = "fablab";
|
|
|
|
const char* password = "geek make code do";
|
|
|
|
const char* mqtt_server = "192.168.73.20";
|
2024-11-01 22:13:05 +01:00
|
|
|
const char* mqtt_topic = "brainblast/buzzer/pressed/1";
|
|
|
|
const char* mqtt_message = "{\"buzzer_id\": 1, \"color\": \"#FF7518\"}";
|
2024-11-04 18:14:46 +01:00
|
|
|
//hostname wifi et client id mqtt
|
|
|
|
const char* esp_name = "BUZZER-1";
|
2024-10-07 18:38:43 +02:00
|
|
|
|
|
|
|
// 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...");
|
2024-11-04 18:14:46 +01:00
|
|
|
WiFi.hostname(esp_name);
|
2024-10-07 18:38:43 +02:00
|
|
|
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...");
|
2024-11-04 18:14:46 +01:00
|
|
|
if (client.connect(esp_name)) {
|
2024-10-07 18:38:43 +02:00
|
|
|
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...");
|
2024-11-01 22:13:05 +01:00
|
|
|
client.publish(mqtt_topic, mqtt_message);
|
2024-10-07 18:38:43 +02:00
|
|
|
delay(200); // Anti-rebond pour éviter les publications multiples
|
|
|
|
}
|
2024-11-01 22:13:05 +01:00
|
|
|
}
|