Okay merci pour les explications, voici le code un peu nettoyé.
Donc je rappelle ma question : est-il possible, en Wifi de déclencher les mcu en cascade avec une précision de qq 10aines ou au maximum 100aine de ms ?
Si oui y a -t-il un problème avec ceci :
#define DATA_PIN 2
byte BRIGHTNESS = 60;
byte fadeAmount = 5;
byte gHue = 124; // hue pour HSV
byte prev_gHue = gHue;
byte gSat = 255;// saturation pour HSV
byte gBpm = 10; // beat per minutes, 40 max !
byte prev_gBpm = 2;//autre bpm pour un glissement progressif des valeurs
byte fadeval = 20;
byte gCol = 0; //color index #1
byte gCol2 = 1; //color index #2
int gDel = 50;//variable pour delay()
int gDel2 = 2000;
int prev_gDel = 2000;
int pas = 100;
WiFiClient ESP01client;
PubSubClient client(ESP01client);
//Variables pour recevoir patterns
byte ledPattern = 0; // pattern # : 255 patterns maximum
unsigned int startTime;
String clientID = WiFi.hostname();
String topicName = clientID + "/#";
bool global_enabled = false;
//diagnostique Wifi, sans perturber la loop() et il existe des fonctions asynchrones pour cela :
//les fonctions "Generic" de l'ESP8266
//https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/generic-examples.html
WiFiEventHandler gotIpEventHandler, disconnectedEventHandler;
long lastReconnectAttempt = 0;//variable lié à la fonction de reconnexion mqtt non bloquante, voir l'exemple mqtt_reconnect_nonblocking.ino
boolean connect_mqtt() {
Serial.println("");
if (client.connect(clientID.c_str())) {
client.publish("welcomeled", clientID.c_str());
client.subscribe("led");//led pattern
Serial.println("connexion OK !!");
Serial.printf("welcome : %s\n", clientID.c_str());
}
return client.connected();
}
//=================================================================================
int payloadToInt(byte* payload, int length) {
String payloadFromMQTT = "";
for (int i = 0; i < length; i++) { //itérer dans toute la longueur message, length est fourni dans le callback
if (isDigit(payload[i]))// tester si le payload est bien un chiffre décimal
payloadFromMQTT += (char)payload[i];//caster en type char et ajouter/placer dans la variable
}
return payloadFromMQTT.toInt();
}
//-------------FONCTION CALLBACK------------
void callback(char* topic, byte* payload, unsigned int length)
{
String debugMessage = "";
global_enabled = true; // open flag : PLAY !
debugMessage = clientID + " - Topic entrant : [" + topic + "] ";
//--------------- nom du mc ----------------
if ( (strcmp(topic, (clientID + "/helloled").c_str()) == 0)
|| (strcmp(topic, "helloled") == 0)) {
client.publish("welcomeled", clientID.c_str());
}
}
typedef void (*voidfunc)();
voidfunc func[] = {p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19};
int nFunc = sizeof(func) / sizeof(func[0]); // sizeof returns the total number of bytes.
void setPattern() {
if ((ledPattern >= 0) && (ledPattern <= nFunc))
{
func[ledPattern]();
}
}
void setup() {
delay(3000); // 3 second delay for recovery
WiFi.softAPdisconnect (true);//encore mieux avec?
WiFi.mode(WIFI_STA);//s'assurer que l'on est mode STAtion et pas autre chose
Serial.begin(74880);// initialize menu Tools > serial monitor
delay(100);
//Par défaut le diagnostique Wifi est désactivé, pour l'activer
//Serial.setDebugOutput(true);
/*
//////////// ESP01 settings //////////
//********************* CHANGE ESP01 PIN FUNCTION **************************************
pinMode(3, FUNCTION_0); //(RX) pin (nommé également pin3 dans la doc) devient GPIO 3
//**************************************************************************************
*/
FastLED.addLeds<WS2812, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);// set master brightness control.
FastLED.setBrightness(BRIGHTNESS);// (255) = puissance maximale -----> ATTENTION POWER !
//------------- wifi-------------
/*A activer pour un téléversement pour une connexion sur un nouveau réseau
https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/scan-examples.html#disconnect
WiFi.mode(WIFI_STA);
WiFi.disconnect();
*/
// setup_wifi();//connexion effective au réseau wifi
//-------------event handlers asynchrone: ne perturbent pas la loop()------
//cet event handler, surveille en permanence, en tâche de fond si une adresse IP est attribuée au module
gotIpEventHandler = WiFi.onStationModeGotIP([](const WiFiEventStationModeGotIP & event)
{
Serial.print("Station connected, IP: ");
Serial.println(WiFi.localIP());
});
//cet event handler, surveille en permanence, en tâche de fond si le module est déconnecté
disconnectedEventHandler = WiFi.onStationModeDisconnected([](const WiFiEventStationModeDisconnected & event)
{
Serial.println("Station disconnected");
});
Serial.printf("Connecting to %s ...\n", ssid);
delay(1000);
//------------- mqtt-------------
//IP et port
client.setServer(mon_broker, 1883);
client.setCallback(callback);
WiFi.begin(ssid, password);//begin établi la connexion en tant que tel
delay(1500);// Allow the hardware to sort itself out
lastReconnectAttempt = 0;
//indique dans le moniteur le nombre de fonctions à disposition
Serial.print("le nombre de fonctions diponibles est :");
Serial.println(nFunc);
Serial.println();
}
void loop() {
// erreur 1 : ce-dessous, inutile ! car l'ESP tente lui-même de se reconnecter lorsqu'il est déconnecté du Wifi
/* https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/station-class.html#start-here
if (WiFi.status() != WL_CONNECTED)
setup_wifi();
*/
//monitorer le status de la connexion en continue
//Serial.printf("Status de la Connection: %d\n", WiFi.status());//retourne un entier
/*
WiFi.status() retourne un code qui décrit la situation :
0 : WL_IDLE_STATUS when Wi-Fi is in process of changing between statuses
1 : WL_NO_SSID_AVAILin case configured SSID cannot be reached
3 : WL_CONNECTED after successful connection is established
4 : WL_CONNECT_FAILED if password is incorrect
6 : WL_DISCONNECTED if module is not configured in station mode
*/
//------------ non blocking mqtt connexion ----------
if (!client.connecte()) {
long now = millis();
if (now - lastReconnectAttempt > 5000) {
lastReconnectAttempt = now;
// Attempt to reconnect
if (connect_mqtt()) {
lastReconnectAttempt = 0;
}
}
} else {
// Client connected
client.loop();
}
if (!global_enabled) //Global "display enable" flag
return;
setPattern();
// insert a delay to keep the framerate modest
FastLED.delay(1000 / FRAMES_PER_SECOND);
}