Trabajar 2 Sensores DHT21 en Arduino Nano Esp32

el concepto de lo que se quiere hacer es muy simple y veo casos similares con el DHT11 y DHT22, no asi con el DHT21, requiero sensar temperatura y humedad con 2 sensores del mismo tipo, eh seguido los casos de exito que hay en el foro para los de mas sensores DHT, pero no me funcionan, solo funciona el primer sensor que leo (t1 y h1) y el otro no arroja nada(t2 y h2), no importando si cambio los sensores de posicion o el orden en el codigo, siempre sensa solamente el primer sensor que mando a leer. Agradecere mucho su ayuda y puntos de vista, adjunto el codigo que estoy utilizando:

/* 
  Sketch generated by the Arduino IoT Cloud Thing "Untitled"
  https://create.arduino.cc/cloud/things/c32af580-ec89-4a98-9e19-5d0d333f51e5 

  Arduino IoT Cloud Variables description

  The following variables are automatically generated and updated when changes are made to the Thing

  float t1;
  float t2;
  int h1;
  int h2;

  Variables which are marked as READ/WRITE in the Cloud Thing will also have functions
  which are called when their values are changed from the Dashboard.
  These functions are generated with the Thing and added at the end of this sketch.
*/

#include "thingProperties.h"
#include "DHT.h"
#define HT1 2     // pin 7 arduino  entrada de sensor 1
#define HT2 4  // pin 8 arduino  entrada de sensor 2
#define DHTTYPE DHT21
DHT dht1 (HT1, DHTTYPE);
DHT dht2 (HT2, DHTTYPE);

void setup() {
  // Initialize serial and wait for port to open:
  Serial.begin(9600);
  // This delay gives the chance to wait for a Serial Monitor without blocking if none is found
  delay(1500); 

  // Defined in thingProperties.h
  initProperties();

  // Connect to Arduino IoT Cloud
  ArduinoCloud.begin(ArduinoIoTPreferredConnection);
  
  /*
     The following function allows you to obtain more information
     related to the state of network and IoT Cloud connection and errors
     the higher number the more granular information you’ll get.
     The default is 0 (only errors).
     Maximum is 4
 */
  setDebugMessageLevel(2);
  ArduinoCloud.printDebugInfo();
  dht1.begin();
  dht2.begin();
}

void loop() {
  ArduinoCloud.update();
  delay(2000);
  h1 = dht1.readHumidity(); 
  t1 = dht1.readTemperature(); 

  h2 = dht2.readHumidity(); 
  t2 = dht2.readTemperature(); 
}

He trasladado su tema de una categoría de idioma inglés del foro a la categoría International > Español @giovani_ml.

En adelante por favor usar la categoría apropiada a la lengua en que queráis publicar. Esto es importante para el uso responsable del foro, y esta explicado aquí la guía "How to get the best out of this forum".
Este guía contiene mucha información útil. Por favor leer.

De antemano, muchas gracias por cooperar.

1 Like

Hola, lo único que veo raro en tu código es que no cargas la librería " adafruit unified sensor " necesaria para que funcione la librería " DHT.h ". Léete el siguiente TUTORIAL para mas información.

Hi,
Me parece que debes de declarar las variables h1 y t1 y h2 y t2 como floating point antes del setup. o las puedes declarar cuando las lees pero solamente las puede leer en loop.

Pero el comentario en el código aclara que las declara automáticamente Thing, de hecho si no estuviesen declaradas daría error al compilar.

Hi,
Hi,
Si yo me di cuenta de eso pero si corres el ejemplo que viene en la libreria #include "DHT.H" estan definidas. Adjunto sketch.
Encontre un sensor dht22 y corri el sketch que el esta usando y me da el sigiente error:
Compilation error: 'h1' was not declared in this scope
No se como a el no le da el error arriba mencionado.

// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain

// REQUIRES the following Arduino libraries:
// - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library
// - Adafruit Unified Sensor Lib: https://github.com/adafruit/Adafruit_Sensor

#include "DHT.h"

#define DHTPIN 2     // Digital pin connected to the DHT sensor
// Feather HUZZAH ESP8266 note: use pins 3, 4, 5, 12, 13 or 14 --
// Pin 15 can work but DHT must be disconnected during program upload.

// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 3 (on the right) of the sensor to GROUND (if your sensor has 3 pins)
// Connect pin 4 (on the right) of the sensor to GROUND and leave the pin 3 EMPTY (if your sensor has 4 pins)
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors.  This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println(F("DHTxx test!"));

  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print(F("Humidity: "));
  Serial.print(h);
  Serial.print(F("%  Temperature: "));
  Serial.print(t);
  Serial.print(F("°C "));
  Serial.print(f);
  Serial.print(F("°F  Heat index: "));
  Serial.print(hic);
  Serial.print(F("°C "));
  Serial.print(hif);
  Serial.println(F("°F"));
}

Porque es un proyecto de IoT Cloud. :wink:

Hola tauro0221, gracias por su tiempo, eh cargado la configuracion como comentas pero el error persiste, solo detecta un sensor, sigo realizando pruebas.

Hola MaximoEsfuerzo, correcto, es un codigo elaborado en IOT cloud, las variables estan declaradas en el Thing, me di cuenta de ello porque al declararlo en el sketch marcaba error de redeclaracion de variables, aun sigo buscando solucion, voy a intentar cargar la libreria de adafruit, gracias por su tiempo

Hola gonpezzi, eh cargado la libreria y seguido los pasos segun la guia, sin embardo, el problema persiste, muchas gracias por tu aportacion

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.