Arduino via ethernet

Mon problème

Bonjour,

J’aimerais intégrer des arduino dans ha. J’aimerais également qu’ils communiquent via le lan. J’ai un shield ethernet.
J’ai regardé sur le github, ils disent que pour utiliser l’arduino, il faut utiliser firmata. Mais je ne comprends pas bien. J’ai lu que certains utilisent mqtt.
En fait, mon arduino n’aura (dans un premier temps ) que des capteurs dht22.

Quelqu’un saurait-il m’aiguiller sur une façon de pratiquer ? Ou un tuto valable ?

Merci

System Health

version core-2021.2.3
installation_type Home Assistant OS
dev false
hassio true
docker true
virtualenv false
python_version 3.8.7
os_name Linux
os_version 5.4.83-v7
arch armv7l
timezone Europe/Brussels
Home Assistant Community Store
GitHub API ok
Github API Calls Remaining 4975
Installed Version 1.11.3
Stage running
Available Repositories 749
Installed Repositories 2
Home Assistant Cloud
logged_in false
can_reach_cert_server ok
can_reach_cloud_auth ok
can_reach_cloud ok
Hass.io
host_os Home Assistant OS 5.11
update_channel stable
supervisor_version supervisor-2021.02.11
docker_version 19.03.13
disk_total 14.0 GB
disk_used 5.4 GB
healthy true
supported true
board rpi3
supervisor_api ok
version_api ok
installed_addons Samba share (9.3.0), File editor (5.2.0), Terminal & SSH (9.0.1), KNXD daemon (0.4.1), Node-RED (8.1.1), Samba Backup (4.4), InfluxDB (4.0.3), Alsa & PulseAudio Fix (3.4), Let’s Encrypt (4.11.0), Duck DNS (1.12.5), Mosquitto broker (5.1)
Lovelace
dashboards 1
resources 1
views 4
mode storage

Je te confirme la librairie mqtt est la plus simple des solutions pour intégrer tes Arduino existantes dans ha.

C’est super simple côté Arduino et encore plus côté ha. Il te faut juste comprendre le Matt si tu ne connais pas du tout et avoir un broker Matt sous la main (hassos peut facilement l’ajouter a priori)

Un exemple simple.

Sinon regarde aussi le WT32-ETH01
Ça fonctionne sous ESPHome et c’est ethernet

Bon c’est certainement perfectible, mais voici ce que fait l’une de mes arduinos avec plusieures sondes en 1-wire:

#include <SPI.h>
#include <OneWire.h>
#include <Ethernet.h>
#include <PubSubClient.h>

// Declare an array with pin numbers for individual OneWire buses
OneWire  ds[] = {9};
//OneWire ds(9);

byte No_of_1Wire_Buses = sizeof(ds) / sizeof(ds[0]);  // Number of pins declared for OneWire = number of Buses
byte this_1Wire_Bus = 0;  // OneWire Bus number that is currently processed
  
//Ethernet and pubsub setup BEGIN
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0x00, 0xeE8};
//byte ip[] = { 10, 0, 0, 160 }; //Comment out if you want DHCP also you need to modify Ethernet.begin(mac, ip)

void callback(char* topic, byte* payload, unsigned int length) {
  // handle message arrived
}

EthernetClient ethClient;
PubSubClient client("10.0.0.1", 1883, callback, ethClient);
//Ethernet and pubsub setup END

char hexChars[] = "0123456789ABCDEF";

void setup(void) {
  // power on the temperature sensor
  // pin 8 is power pin for temperature sensor
  pinMode(8, OUTPUT);
  digitalWrite(8, HIGH);
  Serial.begin(9600);
  
  if (Ethernet.begin(mac) == 0)
    {
      Serial.println("Failed to configure Ethernet using DHCP");
      return;
    }
    
  Serial.print("My IP address: ");
  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    // print the value of each byte of the IP address:
    Serial.print(Ethernet.localIP()[thisByte], DEC);
    Serial.print("."); 
  }
  Serial.println();
  delay(3000);
  Serial.print("Number of defined 1Wiew buses: ");
  Serial.println(No_of_1Wire_Buses);
}

void loop(void) {
//Connect to MQTT
  if (!client.connected())
  {
    Serial.println("Connecting to MQTT server");
    client.connect("arduino_entree");
    client.publish("/arduino_entree/status","ONLINE");
    Serial.println("Connected to MQTT server");
  }
  client.loop();
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float celsius, fahrenheit;
 
  if ( !ds[this_1Wire_Bus].search(addr)) {
    Serial.print("No more addresses for array element number: ");
    Serial.println(this_1Wire_Bus);
    if (this_1Wire_Bus >= (No_of_1Wire_Buses - 1)) {
      this_1Wire_Bus = 0;
    } else {
      this_1Wire_Bus++;
    }
    ds[this_1Wire_Bus].reset_search();
       Serial.println("Pausing between search's");
    delay(30000); //delay between finding all the sensors
    return;
  }
  
  Serial.print("ROM =");
  unsigned long *lval = (unsigned long *)addr;
  Serial.println(*lval);
  for( i = 0; i < 8; i++) {
    Serial.write(' ');
    Serial.print(addr[i], HEX);
    
  }

  if (OneWire::crc8(addr, 7) != addr[7]) {
      Serial.println("CRC is not valid!");
      return;
  }
  Serial.println();
 
  // the first ROM byte indicates which chip
  switch (addr[0]) {
    case 0x10:
      Serial.println("  Chip = DS18S20");  // or old DS1820
      type_s = 1;
      break;
    case 0x28:
      Serial.println("  Chip = DS18B20");
      type_s = 0;
      break;
    case 0x22:
      Serial.println("  Chip = DS1822");
      type_s = 0;
      break;
    default:
      Serial.println("Device is not a DS18x20 family device.");
      return;
  } 

  ds[this_1Wire_Bus].reset();
  ds[this_1Wire_Bus].select(addr);
  ds[this_1Wire_Bus].write(0x44, 1);        // start conversion, with parasite power on at the end
 
  
  delay(1000);     // maybe 750ms is enough, maybe not
  // we might do a ds.depower() here, but the reset will take care of it.
  
  present = ds[this_1Wire_Bus].reset();
  ds[this_1Wire_Bus].select(addr);    
  ds[this_1Wire_Bus].write(0xBE);         // Read Scratchpad

  Serial.print("  Data = ");
  Serial.print(present, HEX);
  Serial.print(" ");
  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds[this_1Wire_Bus].read();
    //data[i] = ds.read();
    Serial.print(data[i], HEX);
    Serial.print(" ");
  }
  Serial.print(" CRC=");
  Serial.print(OneWire::crc8(data, 8), HEX);
  Serial.println();

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
      // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
  } else {
    byte cfg = (data[4] & 0x60);
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
  }
  celsius = (float)raw / 16.0;
  fahrenheit = celsius * 1.8 + 32.0;
  Serial.print("  Temperature = ");
  Serial.print(celsius);
  Serial.print(" Celsius, ");
  Serial.print(fahrenheit);
  Serial.println(" Fahrenheit");
//publish the temp now
  char charTopic[] = "/arduino_entree/XXXXXXXXXXXXXXXX/temperature/current";
  for (i = 0; i < 8; i++) {
    charTopic[16+i*2] = HEX_MSB(addr[i]); //33 is where the backlash before XXX starts
    charTopic[17+i*2] = HEX_LSB(addr[i]); //34 is plus one on the above
  }
  char charMsg[10];
  memset(charMsg,'\0',10);
  dtostrf(celsius, 4, 2, charMsg);
  client.publish(charTopic,charMsg);
  delay(1000); // just adding a small delay between publishing just incase
}

Ensuite dans HA chaque sondes est identifié comme un sensor:


- platform: mqtt
  state_topic: "/arduino_entree/2823F42B03000048/temperature/current"
  name: chaudiere_aller_temperature
  device_class: temperature
  unit_of_measurement: '°C'

- platform: mqtt
  state_topic: "/arduino_entree/2828338B0300006A/temperature/current"
  name: chaudiere_retour_temperature
  device_class: temperature
  unit_of_measurement: '°C'

- platform: mqtt
  state_topic: "/arduino_entree/28104095050000F9/temperature/current"
  name: plancher_retour_temperature
  device_class: temperature
  unit_of_measurement: '°C'

- platform: mqtt
  state_topic: "/arduino_entree/28E1FC95050000D2/temperature/current"
  name: plancher_aller_temperature
  device_class: temperature
  unit_of_measurement: '°C'

Bonjour,
Merci à vous tous pour vos réponses.
Bon, je suis arrivé à un truc mais sans le comprendre (et ca m’embête).
J’ai su mettre en place mon broker. à première vue, mon arduino communique.
Seulement, je ne vois rien sur HA.
@tikismoke . sais-tu m’expliquer comment s’écrit le croquis arduino? Pas que je ne le comprend pas le croquis arduino (encore que…) mais en fait, je m’étonne de ne pas pouvoir écrire un croquis simple. Tous ceux que je trouve sont terriblement compliqués je trouve.
Deuxième chose, comment sais-tu ce que tu dois mettre dans le fichier config? Par exemple, où trouves-tu ton state_topic:?
Je pense que c’est au minimum la non déclaration dans le fichier config qui fait que je ne le vois pas. Mais problème, je ne sais pas quoi y mettre.
Petite précision, pour qu’il y ai une communication valide dans le log de mosquitto, j’ai dû mettre « anonimous » sur « true ». Est-ce normal?
Je vous mets les log de mosquitto voir si vous avez une idée de comment faire…

[23:20:03] INFO: Setup mosquitto configuration
[23:20:03] INFO: Found local users inside config
[23:20:03] INFO: Initialize Hass.io Add-on services
[23:20:04] INFO: Initialize Home Assistant discovery
[23:20:04] INFO: Start Mosquitto daemon
1613859604: mosquitto version 1.6.3 starting
1613859604: Config loaded from /etc/mosquitto.conf.
1613859604: Loading plugin: /usr/share/mosquitto/auth-plug.so
1613859604: |-- *** auth-plug: startup
1613859604:  ├── Username/password checking enabled.
1613859604:  ├── TLS-PSK checking enabled.
1613859604:  └── Extended authentication not enabled.
1613859604: Opening ipv4 listen socket on port 1883.
1613859604: Opening ipv6 listen socket on port 1883.
1613859604: Opening websockets listen socket on port 1884.
1613859604: Opening ipv4 listen socket on port 8883.
1613859604: Opening ipv6 listen socket on port 8883.
1613859604: Opening websockets listen socket on port 8884.
1613859604: Warning: Mosquitto should not be run as root/administrator.
1613859606: New connection from 192.168.1.50 on port 1883.
1613859606: New client connected from 192.168.1.50 as Arduino_1 (p2, c1, k15).
1613859607: New connection from 172.30.32.1 on port 1883.
[INFO] found homeassistant on local database
1613859608: New client connected from 172.30.32.1 as 2gvVDPt2Dry5Yvw0h3SBRl (p2, c1, k60, u'homeassistant').
1613861091: Socket error on client 2gvVDPt2Dry5Yvw0h3SBRl, disconnecting.
1613861123: New connection from 172.30.32.1 on port 1883.
[INFO] found homeassistant on local database
1613861126: New client connected from 172.30.32.1 as 5OsSdMmJ6rSjJiyXUApxoz (p2, c1, k60, u'homeassistant').
1613861404: Saving in-memory database to /data/mosquitto.db.

D’avance je vous remercie de votre patience car je suis vraiment nul dans ce domaine.

Le state topic dans mon cas je le fabrique ici dans le code de l’arduino (mais il est variable est dépend de l’adresse de ma sonde):

  char charTopic[] = "/arduino_entree/XXXXXXXXXXXXXXXX/temperature/current";

Poste ton code arduino, on va jeter un oeil.
Ensuite pour t’aider dans HA il y a un outil d’ecoute mqtt, tu vas dans configuration/intégrations/mqtt/configuration et là tu peux écouter les paquet.
Dans ton cas mais le caractère # est clic sur LISTEN tu verras toutes les trames MQTT de ton broker.

Tu verras le nom (chemin) du topic qui t’intéresses défiler

Bonjour,
Un bref commentaire car il se fait tard…
L’outil d’écoute, je l’ai utilisé avec le # mais rien n’apparaît. Je dois donc avoir un problème quelque part mais je ne sais pas où.

Merci de ta réponse

Bonjour, voici mon code Arduino (c’est un que j’ai trouvé sur le net):

//  Arduino Mqtt et des capteurs DHT22 (temp/humidite )
//
//  Exemple de reconnexion MQTT - non bloquant
//  une recopie-modif du wiki FHEM : https://wiki.fhem.de/wiki/MQTT_Einführung_Teil_3
//
//  base par: Rince du forum Fhem (adaptation 4 capteurs par JeeLet)
//  croquis : Arduino1_mqtt_dht22_eth_v01.ino
//  Biblio: PubSubClient.h (NickOLeary) et dht?? et pour dhtnew pas trouvé
//  date/version: 2020 / v01 (4 capteurs DHT22 en pseudo on-wire )
//
// Ce croquis montre comment garder le client connecté en utilisant
// une fonction de reconnexion non bloquante, Si le client perd sa connexion,
// il tente de se reconnecter toutes les 5 secondes sans bloquer la boucle principale.
//
//
// -------------- debut ---------------

 #include <DHT.h>
 #include <SPI.h>
 #include <Ethernet.h>
 #include <PubSubClient.h>
 
 #define DHTPIN 6    
  
 #define DHTTYPE DHT22
 
 DHT dht (DHTPIN, DHTTYPE);
 

 byte mac[]    = { 0x90, 0xA2, 0xDA, 0x0D, 0x85, 0xFF }; // adresses mac
 IPAddress ip{ 192, 168, 1, 50};     //ip du client
 IPAddress server{ 192, 168, 1, 2}; //ip du serveur MQTT (le Broker)

        // ------------- mqtt ---------------//

   void callback(char* topic, byte* payload, unsigned int length)
   {
   // gérer le message est arrivé
   }

  EthernetClient ethClient;
  PubSubClient client(ethClient);

  long lastReconnectAttempt = 0;

  boolean reconnect()
 {
    if (client.connect("Arduino_1", "home/Arduino_1", 0, true, "offline"))
    {
     // Once connected, publish an announcement...
     client.publish("home/Arduino_1","online", true);
     // ... and resubscribe
     client.subscribe("inTopic");
    }
   return client.connected();
 }


 // Réservez la zone de stockage pour sauver la clôture //
 
  // capteur0
  static char humidity[15];
  static char temperature[15];
  float h = 0.0;
  float h_alt = 0.0;
  float t = 0.0;
  float t_alt = 0.0;

  // capteur1
  static char char_h1[15];
  static char char_t1[15];
  float h1 = 0.0;
  float h1_alt = 0.0;
  float t1 = 0.0;
  float t1_alt = 0.0;

  // capteur2
  static char char_h2[15];
  static char char_t2[15];
  float h2 = 0.0;
  float h2_alt = 0.0;
  float t2 = 0.0;
  float t2_alt = 0.0;


// remise a zero du compteur "millisecondes"  depuis le dernier appel.
    unsigned long previousMillis = 0;  
        
// valeur intervalle de fréquence d'utilisation du capteur, en millisecondes (60000=1mn)
    const long interval = 12000;



         //***************** Setup **********************//

 void setup()
 {
   client.setServer(server, 1883);
   client.setCallback(callback);

   Ethernet.begin(mac, ip);
   delay(1500);
   lastReconnectAttempt = 0;
  
   Serial.begin(9600);
   Serial.println("DHT22 - Test!");
 
   dht.begin();
  
 }

//***************** Loop **********************

 void loop()
 {
   if (!client.connected())
   {
     long now = millis();
     if (now - lastReconnectAttempt > 5000) // calcul temps pour reconnection client
       {
        lastReconnectAttempt = now;
    
     // Tentative de reconnexion
       if (reconnect())
          {
          lastReconnectAttempt = 0;
          }
       }
   }

   else
     {
      client.loop(); // Client connected
     }

   unsigned long currentMillis = millis();

    if (currentMillis - previousMillis >= interval) // calcul temps ecouler du capteur
    {
      previousMillis = currentMillis;

     // ----- lecture des capteurs ------    
    
      h = dht.readHumidity();       //humidite 0
      t = dht.readTemperature();    //Temperature 0

     }
    
   // Vérifiez si un numéro valide est retourné.
   //  Si "NaN" "Not a Number" (pas un nombre) est renvoyé, affiche erreurs capteur.

     if (isnan(t) || isnan(h) || isnan(t1) || isnan(h1) || isnan(t2) || isnan(h2) )
      {
       Serial.println(" un DHT22 n'a pas pu être lu");
       client.publish("home/Arduino_1","Erreur capteur",true);
    
     // "true" envoie le message conservé, c'est-à-dire que le message reste sur le courtier
     //jusqu'à ce que quelque chose de nouveau arrive.
      }
       else if (h == h_alt && t == t_alt && h1 == h1_alt && t1 == t1_alt && h2 == h2_alt && t2 == t2_alt  )
         {
          //ne fais rien
         }
       else
        {
         client.publish("home/Arduino_1","en Ligne", true);
    
         dtostrf(h,6, 1, humidity);
         dtostrf(t,6, 1, temperature);
      
         dtostrf(h1,6, 1, char_h1);
         dtostrf(t1,6, 1, char_t1);

         dtostrf(h2,6, 1, char_h2);
         dtostrf(t2,6, 1, char_t2);

    
         client.publish("home/Arduino_1/cuisine/humidite",humidity, true);
         client.publish("home/Arduino_1/cuisine/Temperature",temperature, true);

         client.publish("home/Arduino_1/bureau/humidite",char_h1, true);
         client.publish("home/Arduino_1/bureau/Temperature",char_t1, true);

         client.publish("home/Arduino_1/chambre/humidite",char_h2, true);
         client.publish("home/Arduino_1/chambre/Temperature",char_t2, true);
    
       h_alt = h;       // annuler l'ancienne lecture ..
       t_alt = t;       // ... pour ne réagir qu'aux changements


// ------------ Visu sur terminal ------------------

        Serial.print("humidite: ");
        Serial.print(h);
        Serial.print(" %\t");
        Serial.print("Temperature: ");
        Serial.print(t);
        Serial.println(" C");
   
    }
 }
//-------- Fin Pgm --------------

En te remerciant

Pour être sur et t’aider quelques pistes:
-As tu vérifier que ton arduino obtient bien un ip à la fin du void setup en rajoutant ceci par exemple :

Serial.print(« My IP address: « );
for (byte thisByte = 0; thisByte < 4; thisByte++) {
Serial.print(Ethernet.localIP()[thisByte], DEC);
Serial.print( ». »);
}
-Ensuite, je ne sais pas pourquoi mais la ligne de déclaration du client Mqtt est plus longue chez moi:
PubSubClient client("10.0.0.1", 1883, callback, ethClient);
Et du coup je n’ai pas de ligne client.setServer dans mon setup.

Ce ne sont que des pistes.

Déjà si en mettant # dans le listener tu ne vois rien passer ces bien que personnes ne publie de message sur ton broker.

Bonjour,
Je n’en sort pas.
Penses-tu qu’il est possible d’adapter ton code avec des dht22? Si oui, comment?
J’ai essayé ton code dans le logiciel arduino et en le vérifiant, il m’indique des erreursau niveau du:

charTopic[16+i*2] = HEX_MSB(addr[i]); //33 is where the backlash before XXX starts
    charTopic[17+i*2] = HEX_LSB(addr[i]); //34 is plus one on the above
  }
  char charMsg[10];
  memset(charMsg,'\0',10);
  dtostrf(celsius, 4, 2, charMsg);
  client.publish(charTopic,charMsg);
  delay(1000); // just adding a small delay between publishing just incase
}

Merci

Je peux me rendre dispo sur discord d’ici 45min pour un peu moins d’une heure

Heuuu oui mais je ne sais pas trop comment ca marche

Ca y est, je suis sur discord. Par contre, faut que tu m’expliques comment on s’y retrouve

salut,
Juste pour te dire que sans rien changer au croquis ni a rien du tout, aujourd’hui, je vois les msg passer dans mqtt.
bizarre
Merci à toi

Bonne nouvelle.

Tu peux mettre le code Arduino ici des fois que ça serve à d’autres.

As tout hasard tu n’auras pas redémarrer la pi? Des fois que quelque-chose ai nécessité un redémarrage. (pour ceux qui relisent nous n’avons modifier que le code Arduino de Jérôme pour voir ce qui pouvait bloquer).

Bon amusement avec HA

Ok, je le posterai demain mais pour précision, oui j’ai redémarré, j’ai réinstallé mosquitto et l’intégration mqtt. Mais tout ça hier et ça ne fonctionnait pas. Aujourd’hui, je le rebranche et miracle. Et pour dire aussi que j’ai repris le 1er code que tu m’avais envoyé.
Il y a eu quelques ratées au début puis de mieux en mieux comme pour un diesel qui lui faut le temps de chauffer lol.
J’aurai quand même encore besoin de toi pour l’une ou l’autre petites questions.
Au fait, tu sais me dire si toutes les entrées du croquis sont nécessaires ? Avec un simple code de dht22 et les librairies ethernet et mqtt, ça ne marcherait pas ?parce que le code simple, je le comprends mais celui sur lequel tu t’es penché hier, je suis coulé et j’aurais besoin d’adapter pour des relais, sonde pression et sonde de proximité…
En te remerciant

Alors pour rajouter des relais ou autre c’est pas un souci à mon avis.
En revanche il va falloir que tu te documentes plus sur le code Arduino. Il va falloir rajouter une gestion de l’écoute Mqtt pour savoir quand agir.
Il faut vraiment que tu arrives à comprendre chaque ligne de ce que tu as fait pour pouvoir avancer et en faire encore plus.

Courage et persévérance, tu vas y arriver j’en suis sur.

Comme promis, voici mon code:

//  Arduino Mqtt et des capteurs DHT22 (temp/humidite )
//
//  Exemple de reconnexion MQTT - non bloquant
//  une recopie-modif du wiki FHEM : https://wiki.fhem.de/wiki/MQTT_Einführung_Teil_3
//
//  base par: Rince du forum Fhem (adaptation 4 capteurs par JeeLet)
//  croquis : Arduino1_mqtt_dht22_eth_v01.ino
//  Biblio: PubSubClient.h (NickOLeary) et dht?? et pour dhtnew pas trouvé
//  date/version: 2020 / v01 (4 capteurs DHT22 en pseudo on-wire )
//
// Ce croquis montre comment garder le client connecté en utilisant
// une fonction de reconnexion non bloquante, Si le client perd sa connexion,
// il tente de se reconnecter toutes les 5 secondes sans bloquer la boucle principale.
//
//
// -------------- debut ---------------

 #include <DHT.h>
 #include <SPI.h>
 #include <Ethernet.h>
 #include <PubSubClient.h>
 
 #define DHTPIN 6    
  
 #define DHTTYPE DHT22
 
 DHT dht (DHTPIN, DHTTYPE);
 

 byte mac[]    = { 0x90, 0xA2, 0xDA, 0x0D, 0x85, 0xFF }; // adresses mac
 IPAddress ip{ 192, 168, 1, 50};     //ip du client
 IPAddress server{ 192, 168, 1, 2}; //ip du serveur MQTT (le Broker)

        // ------------- mqtt ---------------//

   void callback(char* topic, byte* payload, unsigned int length)
   {
   // gérer le message est arrivé
   }

  EthernetClient ethClient;
  PubSubClient client(ethClient);

  long lastReconnectAttempt = 0;

  boolean reconnect()
 {
    if (client.connect("Arduino_1", "home/Arduino_1", 0, true, "offline"))
    {
     // Once connected, publish an announcement...
     client.publish("home/Arduino_1","online", true);
     // ... and resubscribe
     client.subscribe("inTopic");
    }
   return client.connected();
 }


 // Réservez la zone de stockage pour sauver la clôture //
 
  // capteur0
  static char humidity[15];
  static char temperature[15];
  float h = 0.0;
  float h_alt = 0.0;
  float t = 0.0;
  float t_alt = 0.0;

  // capteur1
  static char char_h1[15];
  static char char_t1[15];
  float h1 = 0.0;
  float h1_alt = 0.0;
  float t1 = 0.0;
  float t1_alt = 0.0;

  // capteur2
  static char char_h2[15];
  static char char_t2[15];
  float h2 = 0.0;
  float h2_alt = 0.0;
  float t2 = 0.0;
  float t2_alt = 0.0;


// remise a zero du compteur "millisecondes"  depuis le dernier appel.
    unsigned long previousMillis = 0;  
        
// valeur intervalle de fréquence d'utilisation du capteur, en millisecondes (60000=1mn)
    const long interval = 12000;



         //***************** Setup **********************//

 void setup()
 {
   client.setServer(server, 1883);
   client.setCallback(callback);

   Ethernet.begin(mac, ip);
   delay(1500);
   lastReconnectAttempt = 0;
  
   Serial.begin(9600);
   Serial.println("DHT22 - Test!");
   
  if (Ethernet.begin(mac) == 0)
    {
      Serial.println("Failed to configure Ethernet using DHCP");
      return;
    }
    
  Serial.print("My IP address: ");
  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    // print the value of each byte of the IP address:
    Serial.print(Ethernet.localIP()[thisByte], DEC);
    Serial.print("."); 
  }
  Serial.println();

   dht.begin();
  
 }

//***************** Loop **********************

 void loop()
 {
   if (!client.connected())
   {
     long now = millis();
     if (now - lastReconnectAttempt > 5000) // calcul temps pour reconnection client
       {
        lastReconnectAttempt = now;
    
     // Tentative de reconnexion
       if (reconnect())
          {
          lastReconnectAttempt = 0;
          }
       }
   }

   else
     {
      client.loop(); // Client connected
     }

   unsigned long currentMillis = millis();

    if (currentMillis - previousMillis >= interval) // calcul temps ecouler du capteur
    {
      previousMillis = currentMillis;

     // ----- lecture des capteurs ------    
    
      h = dht.readHumidity();       //humidite 0
      t = dht.readTemperature();    //Temperature 0

     }
    
   // Vérifiez si un numéro valide est retourné.
   //  Si "NaN" "Not a Number" (pas un nombre) est renvoyé, affiche erreurs capteur.

     if (isnan(t) || isnan(h) || isnan(t1) || isnan(h1) || isnan(t2) || isnan(h2) )
      {
       Serial.println(" un DHT22 n'a pas pu être lu");
       client.publish("home/Arduino_1","Erreur capteur",true);
    
     // "true" envoie le message conservé, c'est-à-dire que le message reste sur le courtier
     //jusqu'à ce que quelque chose de nouveau arrive.
      }
       else if (h == h_alt && t == t_alt && h1 == h1_alt && t1 == t1_alt && h2 == h2_alt && t2 == t2_alt  )
         {
          //ne fais rien
         }
       else
        {
         client.publish("home/Arduino_1","en Ligne", true);
    
         dtostrf(h,6, 1, humidity);
         dtostrf(t,6, 1, temperature);
      
         dtostrf(h1,6, 1, char_h1);
         dtostrf(t1,6, 1, char_t1);

         dtostrf(h2,6, 1, char_h2);
         dtostrf(t2,6, 1, char_t2);

    
         client.publish("home/Arduino_1/cuisine/humidite",humidity, true);
         client.publish("home/Arduino_1/cuisine/Temperature",temperature, true);

         client.publish("home/Arduino_1/bureau/humidite",char_h1, true);
         client.publish("home/Arduino_1/bureau/Temperature",char_t1, true);

         client.publish("home/Arduino_1/chambre/humidite",char_h2, true);
         client.publish("home/Arduino_1/chambre/Temperature",char_t2, true);
    
       h_alt = h;       // annuler l'ancienne lecture ..
       t_alt = t;       // ... pour ne réagir qu'aux changements


// ------------ Visu sur terminal ------------------

        Serial.print("humidite: ");
        Serial.print(h);
        Serial.print(" %\t");
        Serial.print("Temperature: ");
        Serial.print(t);
        Serial.println(" C");
   
    }
 }
//-------- Fin Pgm --------------

Bonjour,

Finalement, le code ne va pas. Il a été puis ne va plus. Enfin, quand je dis qu’il ne va plus, c’est la majorité du temps. Il y a 2min, il a marché et maintenant plus…
Quand j’écoute avec l’intégration mqtt avec # , je ne vois rien qui se passe.
J’essaye de faire communiquer 10 dht22. J’ai également du passer de l,uno au mega car pas assez de memoire
si je me connecte à mon broker avec mqttlens, je vois les messages passer.
Lorsque j’utilise mqtt explorer, je ne vois pas mon arduino, mais lorsque j’envoie des messages avec mqttlens, ils apparaissent.
Je ne sais pas pourquoi mais je me demande si ca n’a pas à voir avec le clientid, le nom d’utilisateur ou le mot de passe (ils ne sont pas indiqué dans le code et je me demande si ce n’est pas ca qui bloque).
J’essaie d’intégrer des bouts de code de gens pour qui ca marche mais le logiciel fini toujours par me dire qu’il y a des erreurs.
Est-ce que quelqu’un a une idée? Ou alors un code fonctionnel avec le moyen de remplacer ses sensors avec des dht22?
J’ai modifié mon code pour intégrer mes 10 dht22. Si vous n’en comptez que 8, c’est normal. J’ai du en retirer 2 du code qui n’étaient pas raccordées.
Voici mon code:

//  Arduino Mqtt et des capteurs DHT22 (temp/humidite )
//
//  Exemple de reconnexion MQTT - non bloquant
//  une recopie-modif du wiki FHEM : https://wiki.fhem.de/wiki/MQTT_Einführung_Teil_3
//
// Ce croquis montre comment garder le client connecté en utilisant
// une fonction de reconnexion non bloquante, Si le client perd sa connexion,
// il tente de se reconnecter toutes les 5 secondes sans bloquer la boucle principale.
//
//
// -------------- debut ---------------

 #include <DHT.h>
 #include <SPI.h>
 #include <Ethernet.h>
 #include <PubSubClient.h>
 

 #define DHTPIN1 24 
 #define DHTPIN2 26  
 #define DHTPIN3 28
 #define DHTPIN4 30  

 #define DHTPIN6 34 
 #define DHTPIN7 36
 #define DHTPIN8 38  
 #define DHTPIN9 40 
  

 #define DHTTYPE1 DHT22
 #define DHTTYPE2 DHT22
 #define DHTTYPE3 DHT22
 #define DHTTYPE4 DHT22

 #define DHTTYPE6 DHT22
 #define DHTTYPE7 DHT22
 #define DHTTYPE8 DHT22
 #define DHTTYPE9 DHT22
 

 DHT dht1 (DHTPIN1, DHTTYPE1);
 DHT dht2 (DHTPIN2, DHTTYPE1);
 DHT dht3 (DHTPIN3, DHTTYPE1);
 DHT dht4 (DHTPIN4, DHTTYPE1);

 DHT dht6 (DHTPIN6, DHTTYPE1);
 DHT dht7 (DHTPIN7, DHTTYPE1);
 DHT dht8 (DHTPIN8, DHTTYPE1);
 DHT dht9 (DHTPIN9, DHTTYPE1);
 

 byte mac[]    = {  0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED }; // adresses mac
const char* mqtt_server = "192.168.1.2";
const char* client_name = "speakerswitch";


        // ------------- mqtt ---------------//

   void callback(char* topic, byte* payload, unsigned int length)
   {
   // gérer le message est arrivé
   }

  EthernetClient ethClient;
  PubSubClient client(ethClient);

  long lastReconnectAttempt = 0;

  boolean reconnect()
 {
    if (client.connect("Arduino_rez", "home/Arduino_rez", 0, true, "offline"))
    {
     // Once connected, publish an announcement...
     client.publish("home/Arduino_rez","online", true);
     // ... and resubscribe
     client.subscribe("inTopic");
    }
   return client.connected();
 }


 // Réservez la zone de stockage pour sauver la clôture //
 
  // capteur0
  static char humidity[15];
  static char temperature[15];
  float h = 0.0;
  float h_alt = 0.0;
  float t = 0.0;
  float t_alt = 0.0;

  // capteur1
  static char char_h1[15];
  static char char_t1[15];
  float h1 = 0.0;
  float h1_alt = 0.0;
  float t1 = 0.0;
  float t1_alt = 0.0;

    // capteur2
  static char char_h2[15];
  static char char_t2[15];
  float h2 = 0.0;
  float h2_alt = 0.0;
  float t2 = 0.0;
  float t2_alt = 0.0;

    // capteur3
  static char char_h3[15];
  static char char_t3[15];
  float h3 = 0.0;
  float h3_alt = 0.0;
  float t3 = 0.0;
  float t3_alt = 0.0;

    // capteur4
  static char char_h4[15];
  static char char_t4[15];
  float h4 = 0.0;
  float h4_alt = 0.0;
  float t4 = 0.0;
  float t4_alt = 0.0;

    // capteur5
  static char char_h5[15];
  static char char_t5[15];
  float h5 = 0.0;
  float h5_alt = 0.0;
  float t5 = 0.0;
  float t5_alt = 0.0;

    // capteur6
  static char char_h6[15];
  static char char_t6[15];
  float h6 = 0.0;
  float h6_alt = 0.0;
  float t6 = 0.0;
  float t6_alt = 0.0;

    // capteur7
  static char char_h7[15];
  static char char_t7[15];
  float h7 = 0.0;
  float h7_alt = 0.0;
  float t7 = 0.0;
  float t7_alt = 0.0;

    // capteur8
  static char char_h8[15];
  static char char_t8[15];
  float h8 = 0.0;
  float h8_alt = 0.0;
  float t8 = 0.0;
  float t8_alt = 0.0;

    // capteur9
  static char char_h9[15];
  static char char_t9[15];
  float h9 = 0.0;
  float h9_alt = 0.0;
  float t9 = 0.0;
  float t9_alt = 0.0;

// remise a zero du compteur "millisecondes"  depuis le dernier appel.
    unsigned long previousMillis = 0;  
        
// valeur intervalle de fréquence d'utilisation du capteur, en millisecondes (60000=1mn)
    const long interval = 6000;



         //***************** Setup **********************//

 void setup()
 {
   client.setServer(server, 1883);
   client.setCallback(callback);

   Ethernet.begin(mac, ip);
   delay(1500);
   lastReconnectAttempt = 0;
  
   Serial.begin(9600);
      
  if (Ethernet.begin(mac) == 0)
    {
      Serial.println("Failed to configure Ethernet using DHCP");
      return;
    }
    
  Serial.print("My IP address: ");
  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    // print the value of each byte of the IP address:
    Serial.print(Ethernet.localIP()[thisByte], DEC);
    Serial.print("."); 
  }
  Serial.println();


   dht1.begin();
   dht2.begin();
   dht3.begin();
   dht4.begin();

   dht6.begin();
   dht7.begin();
   dht8.begin();
   dht9.begin();
  
 }

//***************** Loop **********************

 void loop()
 {
   if (!client.connected())
   {
     long now = millis();
     if (now - lastReconnectAttempt > 5000) // calcul temps pour reconnection client
       {
        lastReconnectAttempt = now;
    
     // Tentative de reconnexion
       if (reconnect())
          {
          lastReconnectAttempt = 0;
          }
       }
   }

   else
     {
      client.loop(); // Client connected
     }

   unsigned long currentMillis = millis();

    if (currentMillis - previousMillis >= interval) // calcul temps ecouler du capteur
    {
      previousMillis = currentMillis;

     // ----- lecture des capteurs ------    
    

      
      h1 = dht1.readHumidity();     //humidite 1
      t1 = dht1.readTemperature();  //Temperature 1
      
      h2 = dht2.readHumidity();     //humidite 2
      t2 = dht2.readTemperature();  //Temperature 2

      h3 = dht3.readHumidity();     //humidite 3
      t3 = dht3.readTemperature();  //Temperature 3
      
      h4 = dht4.readHumidity();     //humidite 4
      t4 = dht4.readTemperature();  //Temperature 4


      
      h6 = dht6.readHumidity();     //humidite 6
      t6 = dht6.readTemperature();  //Temperature 6
     
      h7 = dht7.readHumidity();     //humidite 7
      t7 = dht7.readTemperature();  //Temperature 7
      
      h8 = dht8.readHumidity();     //humidite 8
      t8 = dht8.readTemperature();  //Temperature 8
     
      h9 = dht9.readHumidity();     //humidite 9
      t9 = dht9.readTemperature();  //Temperature 9     
     }
    
   // Vérifiez si un numéro valide est retourné.
   //  Si "NaN" "Not a Number" (pas un nombre) est renvoyé, affiche erreurs capteur.

     if (isnan(t) || isnan(h) || isnan(t1) || isnan(h1) || isnan(t2) || isnan(h2) || isnan(t3) || isnan(h3) || isnan(t4) || isnan(h4) || isnan(t5) || isnan(h5) || isnan(t6) || isnan(h6) || isnan(t7) || isnan(h7) || isnan(t8) || isnan(h8) || isnan(t9) || isnan(h9) )
      {
       Serial.println(" un DHT22 n'a pas pu être lu");
       client.publish("home/Arduino_rez","Erreur capteur",true);
    
     // "true" envoie le message conservé, c'est-à-dire que le message reste sur le courtier
     //jusqu'à ce que quelque chose de nouveau arrive.
      }
       else if (h == h_alt && t == t_alt && h1 == h1_alt && t1 == t1_alt && h2 == h2_alt && t2 == t2_alt && h3 == h3_alt && t3 == t3_alt && h4 == h4_alt && t4 == t4_alt && h5 == h5_alt && t5 == t5_alt && h6 == h6_alt && t6 == t6_alt && h7 == h7_alt && t7 == t7_alt && h8 == h8_alt && t8 == t8_alt && h9 == h9_alt && t9 == t9_alt  )
         {
          //ne fais rien
         }
       else
        {
         client.publish("home/Arduino_rez","en Ligne", true);
    
         dtostrf(h,6, 1, humidity);
         dtostrf(t,6, 1, temperature);
      
         dtostrf(h1,6, 1, char_h1);
         dtostrf(t1,6, 1, char_t1);

         dtostrf(h2,6, 1, char_h2);
         dtostrf(t2,6, 1, char_t2);

         dtostrf(h3,6, 1, char_h3);
         dtostrf(t3,6, 1, char_t3);

         dtostrf(h4,6, 1, char_h4);
         dtostrf(t4,6, 1, char_t4);

         dtostrf(h5,6, 1, char_h5);
         dtostrf(t5,6, 1, char_t5);

         dtostrf(h6,6, 1, char_h6);
         dtostrf(t6,6, 1, char_t6);

         dtostrf(h7,6, 1, char_h7);
         dtostrf(t7,6, 1, char_t7);

         dtostrf(h8,6, 1, char_h8);
         dtostrf(t8,6, 1, char_t8);

         dtostrf(h9,6, 1, char_h9);
         dtostrf(t9,6, 1, char_t9);

         client.publish("home/Arduino_rez/ch_heather/humidite",humidity, true);
         client.publish("home/Arduino_rez/ch_heather/Temperature",temperature, true);

         client.publish("home/Arduino_rez/cuisine/humidite",char_h1, true);
         client.publish("home/Arduino_rez/cuisine/Temperature",char_t1, true);

          client.publish("home/Arduino_rez/caves/humidite",char_h1, true);
         client.publish("home/Arduino_rez/caves/Temperature",char_t1, true);

          client.publish("home/Arduino_rez/salle_de_jeu/humidite",char_h1, true);
         client.publish("home/Arduino_rez/salle_de_jeu/Temperature",char_t1, true);

          client.publish("home/Arduino_rez/salle_de_bain/humidite",char_h1, true);
         client.publish("home/Arduino_rez/salle_de_bain/Temperature",char_t1, true);

          client.publish("home/Arduino_rez/ch_parents/humidite",char_h1, true);
         client.publish("home/Arduino_rez/ch_parents/Temperature",char_t1, true);

          client.publish("home/Arduino_rez/ch_pacey/humidite",char_h1, true);
         client.publish("home/Arduino_rez/ch_pacey/Temperature",char_t1, true);

          client.publish("home/Arduino_rez/bureau/humidite",char_h1, true);
         client.publish("home/Arduino_rez/bureau/Temperature",char_t1, true);

          client.publish("home/Arduino_rez/salon/humidite",char_h1, true);
         client.publish("home/Arduino_rez/salon/Temperature",char_t1, true);

          client.publish("home/Arduino_rez/ch_kirsten/humidite",char_h1, true);
         client.publish("home/Arduino_rez/ch_kirsten/Temperature",char_t1, true);

       h_alt = h;       // annuler l'ancienne lecture ..
       t_alt = t;       // ... pour ne réagir qu'aux changements
       
       h1_alt = h1;  
       t1_alt = t1;

       h2_alt = h2;  
       t2_alt = t2;

       h3_alt = h3;  
       t3_alt = t3;

       h4_alt = h4;  
       t4_alt = t4;

       h5_alt = h5;  
       t5_alt = t5;

       h6_alt = h6;  
       t6_alt = t6;

       h7_alt = h7;  
       t7_alt = t7;

       h8_alt = h8;  
       t8_alt = t8;

       h9_alt = h9;  
       t9_alt = t9;

// ------------ Visu sur terminal ------------------

        Serial.print("humidite ch.Heather: ");
        Serial.print(h);
        Serial.print(" %\t");
        Serial.print("Temperature ch.Heather: ");
        Serial.print(t);
        Serial.println(" C");

        Serial.print("humidite cuisine: ");
        Serial.print(h1);
        Serial.print(" %\t");
        Serial.print("Temperature cuisine: ");
        Serial.print(t1);
        Serial.println(" C");

        Serial.print("humidite caves: ");
        Serial.print(h2);
        Serial.print(" %\t");
        Serial.print("Temperature caves: ");
        Serial.print(t2);
        Serial.println(" C");

        Serial.print("humidite salle de jeu: ");
        Serial.print(h3);
        Serial.print(" %\t");
        Serial.print("Temperature salle de jeu: ");
        Serial.print(t3);
        Serial.println(" C");

        Serial.print("humidite salle de bain: ");
        Serial.print(h4);
        Serial.print(" %\t");
        Serial.print("Temperature salle de bain: ");
        Serial.print(t4);
        Serial.println(" C");

        Serial.print("humidite ch. parents: ");
        Serial.print(h5);
        Serial.print(" %\t");
        Serial.print("Temperature ch. parents: ");
        Serial.print(t5);
        Serial.println(" C");

        Serial.print("humidite ch. Pacey: ");
        Serial.print(h6);
        Serial.print(" %\t");
        Serial.print("Temperature ch. Pacey: ");
        Serial.print(t6);
        Serial.println(" C");

        Serial.print("humidite bureau: ");
        Serial.print(h7);
        Serial.print(" %\t");
        Serial.print("Temperature bureau: ");
        Serial.print(t7);
        Serial.println(" C");

        Serial.print("humidite salon: ");
        Serial.print(h8);
        Serial.print(" %\t");
        Serial.print("Temperature salon: ");
        Serial.print(t8);
        Serial.println(" C");

        Serial.print("humidite ch. kirsten: ");
        Serial.print(h9);
        Serial.print(" %\t");
        Serial.print("Temperature ch. kirsten: ");
        Serial.print(t9);
        Serial.println(" C");
   
    }
 }
//-------- Fin Pgm --------------

merci