Esp32 y Dht11 pasar variables

Me podrian ayudar a pasar las variables de tempC y humedad al voip() realmente no tengo un nivel que llegue a comprender en este codigo que pongo a continuacion, como hacer que funcione eso que necesito. Gracias.

#include <WiFi.h>
#include <HTTPClient.h>

#include "DHTesp.h" // Click here to get the library: http://librarymanager/All#DHTesp
#include <Ticker.h>

#ifndef ESP32
#pragma message(THIS EXAMPLE IS FOR ESP32 ONLY!)
#error Select ESP32 board.
#endif

// base de datos

// Replace with your network credentials
const char* ssid     = "TP-Link_20022";
const char* password = "12345678";

// REPLACE with your Domain name and URL path or IP address with path
const char* serverName = "http://mipagina-web/postsolardata.php";

// Keep this API Key value to be compatible with the PHP code provided in the project page. 
// If you change the apiKeyValue value, the PHP file /post-esp-data.php also needs to have the same key 
String apiKeyValue = "123123213213";

String sensorName = "Solar1";
String sensorLocation = "estacion";




//definicion sensores

#define LIGHT_SENSOR_PIN 36 // ESP32 pin GIOP36 (ADC0)
//#include <DHT.h>
//#define DHT_SENSOR_PIN 3
//#define DHT_SENSOR_TYPE DHT11
//DHT dht_sensor(DHT_SENSOR_PIN, DHT_SENSOR_TYPE);
DHTesp dht;

void tempTask(void *pvParameters);
bool getTemperature();
void triggerGetTemp();

/** Task handle for the light value read task */
TaskHandle_t tempTaskHandle = NULL;
/** Ticker for temperature reading */
Ticker tempTicker;
/** Comfort profile */
ComfortState cf;
/** Flag if task should run */
bool tasksEnabled = false;
/** Pin number for DHT11 data pin */
int dhtPin = 3;

/**
 * initTemp
 * Setup DHT library
 * Setup task and timer for repeated measurement
 * @return bool
 *    true if task and timer are started
 *    false if task or timer couldn't be started
 */
bool initTemp() {
  byte resultValue = 0;
  // Initialize temperature sensor
  dht.setup(dhtPin, DHTesp::DHT11);
  Serial.println("DHT initiated");

  // Start task to get temperature
  xTaskCreatePinnedToCore(
      tempTask,                       /* Function to implement the task */
      "tempTask ",                    /* Name of the task */
      4000,                           /* Stack size in words */
      NULL,                           /* Task input parameter */
      5,                              /* Priority of the task */
      &tempTaskHandle,                /* Task handle. */
      1);                             /* Core where the task should run */

  if (tempTaskHandle == NULL) {
    Serial.println("Failed to start task for temperature update");
    return false;
  } else {
    // Start update of environment data every 20 seconds
    tempTicker.attach(20, triggerGetTemp);
  }
  return true;
}

/**
 * triggerGetTemp
 * Sets flag dhtUpdated to true for handling in loop()
 * called by Ticker getTempTimer
 */
void triggerGetTemp() {
  if (tempTaskHandle != NULL) {
     xTaskResumeFromISR(tempTaskHandle);
  }
}

/**
 * Task to reads temperature from DHT11 sensor
 * @param pvParameters
 *    pointer to task parameters
 */
void tempTask(void *pvParameters) {
  Serial.println("tempTask loop started");
  while (1) // tempTask loop
  {
    if (tasksEnabled) {
      // Get temperature values
      getTemperature();
    }
    // Got sleep again
    vTaskSuspend(NULL);
  }
}

/**
 * getTemperature
 * Reads temperature from DHT11 sensor
 * @return bool
 *    true if temperature could be aquired
 *    false if aquisition failed
*/
bool getTemperature() {
  // Reading temperature for humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (it's a very slow sensor)
  TempAndHumidity newValues = dht.getTempAndHumidity();
  // Check if any reads failed and exit early (to try again).
  if (dht.getStatus() != 0) {
    Serial.println("DHT11 error status: " + String(dht.getStatusString()));
    return false;
  }

  float heatIndex = dht.computeHeatIndex(newValues.temperature, newValues.humidity);
  float dewPoint = dht.computeDewPoint(newValues.temperature, newValues.humidity);
  float cr = dht.getComfortRatio(cf, newValues.temperature, newValues.humidity);

  String comfortStatus;
  switch(cf) {
    case Comfort_OK:
      comfortStatus = "Comfort_OK";
      break;
    case Comfort_TooHot:
      comfortStatus = "Comfort_TooHot";
      break;
    case Comfort_TooCold:
      comfortStatus = "Comfort_TooCold";
      break;
    case Comfort_TooDry:
      comfortStatus = "Comfort_TooDry";
      break;
    case Comfort_TooHumid:
      comfortStatus = "Comfort_TooHumid";
      break;
    case Comfort_HotAndHumid:
      comfortStatus = "Comfort_HotAndHumid";
      break;
    case Comfort_HotAndDry:
      comfortStatus = "Comfort_HotAndDry";
      break;
    case Comfort_ColdAndHumid:
      comfortStatus = "Comfort_ColdAndHumid";
      break;
    case Comfort_ColdAndDry:
      comfortStatus = "Comfort_ColdAndDry";
      break;
    default:
      comfortStatus = "Unknown:";
      break;
  };

  float tempC = String(newValues.temperature).toFloat();
  float humedad = String(newValues.humidity).toFloat();
  //Serial.println(" Temp:" + String(newValues.temperature) + " Humedad:" + String(newValues.humidity) + " Index:" + String(heatIndex) + " medio:" + String(dewPoint) + " " + comfortStatus);
  Serial.println(tempC);  // este valor que esta aqui quiero mandar a VOIP()
  Serial.println(humedad); // tambien este valor ....
  
  return true;
}



// medidor de corriente sensibilidad ( ajustar con matematica de medicion)

// Sensibilidad del sensor en V/A
float SENSIBILITY = 0.185;   // Modelo 5A
//float SENSIBILITY = 0.100; // Modelo 20A
//float SENSIBILITY = 0.066; // Modelo 30A
int SAMPLESNUMBER = 100;



void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(115200);
  //dht_sensor.begin();
  //iniciamos wifi

WiFi.begin(ssid, password);
  Serial.println("Conectando a wifi AP");
  while(WiFi.status() != WL_CONNECTED) { 
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("conexion exitosa, la IP ES: ");
  Serial.println(WiFi.localIP());

  
// sensore temp  
initTemp();
  // Signal end of setup() to tasks
  tasksEnabled = true;  
  
  
}

//******************* void para imprimir voltajes y armperajes

void printMeasure(String prefix, float value, String postfix)
{
   Serial.print(prefix);
   Serial.print(value, 3);
   Serial.println(postfix);
   
}



// iniciamos el LOOp // *******************************************************************************************


void loop() {

 
 

  delay(1500);
  
  // reads the input on analog pin (value between 0 and 4095)
  int analogValue = analogRead(LIGHT_SENSOR_PIN);

  Serial.print("Analog Value = ");
  Serial.print(analogValue);   // the raw analog reading

  // We'll have a few threshholds, qualitatively determined
  if (analogValue < 40) {
    Serial.println(" => Ausencia de Luz");
  } else if (analogValue < 800) {
    Serial.println(" => Muy poca luz");
  } else if (analogValue < 2000) {
    Serial.println(" => Luz ambiente");
  } else if (analogValue < 3200) {
    Serial.println(" => Luz normal");
  } else {
    Serial.println(" => Incidencia de luz directa o sensor danado!");
  }

  delay(500);
  
if (!tasksEnabled) {
    // Wait 2 seconds to let system settle down
    delay(2000);
    // Enable task that will read values from the DHT sensor
    tasksEnabled = true;
    if (tempTaskHandle != NULL) {
      vTaskResume(tempTaskHandle);
    }
  }
  
  //amperaje
   float current = getCorriente(SAMPLESNUMBER);
   float currentRMS = 0.707 * current;
   float power = 230.0 * currentRMS;
   printMeasure("Intensidad: ", current, "A ,");
   printMeasure("Irms: ", currentRMS, "A ,");
   printMeasure("Potencia: ", power, "W");

   

   
// mandamos los datos por internet //


//Check WiFi connection status
  if(WiFi.status()== WL_CONNECTED){
    WiFiClient client;
    HTTPClient http;
    
    // Your Domain name with URL path or IP address with path
    http.begin(client, serverName);
    
    // Specify content-type header
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
    
    // Prepare your HTTP POST request data


// por que es AQUI DONDE QUIERO QUE LOS TOME de esa funcion getTemperature()
    
    String httpRequestData = "api_key=" + apiKeyValue + "&sensor=" + sensorName
                          + "&location=" + sensorLocation + "&value1=" + analogValue
                          + "&value2=" + humedad + "&value3=" + tempC + "&value4=" + current + "&value5=" + currentRMS + "";
     
                          
    Serial.print("httpRequestData: ");
    Serial.println(httpRequestData);
    
    // You can comment the httpRequestData variable above
    // then, use the httpRequestData variable below (for testing purposes without the BME280 sensor)
    //String httpRequestData = "api_key=tPmAT5Ab3j7F9&sensor=BME280&location=Office&value1=24.75&value2=49.54&value3=1005.14";

    // Send HTTP POST request
    int httpResponseCode = http.POST(httpRequestData);
     
    // If you need an HTTP request with a content type: text/plain
    //http.addHeader("Content-Type", "text/plain");
    //int httpResponseCode = http.POST("Hello, World!");
    
    // If you need an HTTP request with a content type: application/json, use the following:
    //http.addHeader("Content-Type", "application/json");
    //int httpResponseCode = http.POST("{\"value1\":\"19\",\"value2\":\"67\",\"value3\":\"78\"}");
        
    if (httpResponseCode>0) {
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
    }
    else {
      Serial.print("Error code: ");
      Serial.println(httpResponseCode);
    }
    // Free resources
    http.end();
  }
  else {
    Serial.println("WiFi Disconnected");
  }
  //Send an HTTP POST request every 30 seconds
  delay(120000);  



}

//=============mate mates de amperaje echo por mi mismo en laboratorio con esp32 heltech lora wan y acs7 calibrando de apocooo con 490mA y 12v a 2,45 v promedio de 2,5v del sensor y envez de 3.3 de referencia del esp32 madificamos a una sensibilodad de 100****//
float getCorriente(int samplesNumber)
{
   float voltage;
   float corrienteSum = 0;
   for (int i = 0; i < samplesNumber; i++)
   {
      voltage = analogRead(39) * 3.5 / 4096.0;
      Serial.print("voltaje del sensor : ");
      Serial.println(voltage);
      corrienteSum += -1 * (voltage - 2.55) / SENSIBILITY;
   }
   return(corrienteSum / samplesNumber);
}

Que es enviar algo al voip? Da un ejemplo, link o lo que ayude a entender.
Voip para mi es voz por Internet.

Tienes razon perdon por el ERROR DE TIPEO.

Me refiero para pasar el valor de una variable por ejemplo el de este codigo quiero el valor que esta en

bool getTemperature() {
tempC y humedad

para pasar al

voip loop ()

Es que

voip loop ()

No significa nada y dara un error de compilacion. ¿Que es una nueva funcion para trabajar con la temperatura y Humedad?, si es asi deberia declararla por ejemplo:

void tem_hum (float tem, float hum) {
  // realizo lo que quiera con tem y hum
}

y donde las calcula anteriormente

 float tempC = String(newValues.temperature).toFloat();
  float humedad = String(newValues.humidity).toFloat();
  //Serial.println(" Temp:" + String(newValues.temperature) + " Humedad:" + String(newValues.humidity) + " Index:" + String(heatIndex) + " medio:" + String(dewPoint) + " " + comfortStatus);
  Serial.println(tempC);  // este valor que esta aqui quiero mandar a VOIP()
  Serial.println(humedad); // tambien este valor ....
   
  return true;
}

Haces una llamada a la nueva funcion

 float tempC = String(newValues.temperature).toFloat();
  float humedad = String(newValues.humidity).toFloat();
  //Serial.println(" Temp:" + String(newValues.temperature) + " Humedad:" + String(newValues.humidity) + " Index:" + String(heatIndex) + " medio:" + String(dewPoint) + " " + comfortStatus);
  Serial.println(tempC);  // este valor que esta aqui quiero mandar a VOIP()
  Serial.println(humedad); // tambien este valor ....
  tem_hum (tempC, humedad) ;
  return true;
}

Otra forma seria declarar esas variables como globales, antes del " setup ":

float tempC, humedad;

Y cambiar el codigo donde las calcula al siguiente:


  tempC = String(newValues.temperature).toFloat();
  humedad = String(newValues.humidity).toFloat();
  //Serial.println(" Temp:" + String(newValues.temperature) + " Humedad:" + String(newValues.humidity) + " Index:" + String(heatIndex) + " medio:" + String(dewPoint) + " " + comfortStatus);
  Serial.println(tempC);  // este valor que esta aqui quiero mandar a VOIP()
  Serial.println(humedad); // tambien este valor ....
  
  return true;
}

De esta forma tendras acceso a esas variables en cualquier parte del codigo en las que quieras usarlas.

1 Like

excelente, muchas gracias por la aclaracion.

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