Help with Sensors and timers

Hello to everyone, im working in a project with dht22, relays,acs712, and a multiplexor…

I set up a couple of timers, but everything is working slow, for example, if I put 1000L to my dht22 and 1000L to my acs712, everything works like hell, whe I want to use my relays I have a 4 seconds delay, whats wrong?

I need acs712 every 1 second, cause this tell me if my TV is on or off, same on multiplexor.

Im using Nodemcu 1.0.


#include <OneWire.h>                
#include <DallasTemperature.h>
#include <BlynkSimpleEsp8266.h>
#include <DHT.h>
#include <IRremoteESP8266.h>
#include "MUX74HC4067.h"



int RECV_PIN = D3; //PINO DIGITAL EM QUE O FOTORRECEPTOR ESTÁ CONECTADO - GPIO12 / PINO D6

const int RelePin = 2;
const int RelePin2 = 14;

const int sensorIn = A0;
int mVperAmp = 66; // Use 100 for 20A Module and 66 for 30A Module

double Voltage = 0;
double VRMS = 0;
double AmpsRMS = 0;


MUX74HC4067 mux(D0, D1);



//OneWire ourWire(D1);        //Se establece el D1  como bus OneWire

//DallasTemperature sensors(&ourWire); //Se declara una variable u objeto para nuestro sensor



#define DHTPIN 13         // Definimos el pin al que conectaremos el DHT22



WidgetLED led3(V3);



WidgetTerminal terminal(V21);




// definimos que tipo de DHT estaerror lectura temperaturamos usando
#define DHTTYPE DHT22   // DHT 22, AM2302, AM2321


DHT dht(DHTPIN, DHTTYPE);

//SimpleTimer timer;
BlynkTimer timer;


IRrecv irrecv(RECV_PIN); 

decode_results results; //Variable que alamacena resultados- b3ae4026b9f44f5eb6d28cb2cd385d0d


char auth[] = "xxxxx";
char ssid[] = "xxxx";
char pass[] = "xxxx";





    IRsend irsend(4); //LED emisor INFRA conectado en PIN 4
    
    int khz=38; 

    //Señal infrarroja de apagado AIRE
    unsigned int OFF[] = {9022, 4016, 603, 612, 601, 587, 603, 613, 600, 588, 601, 612, 603, 588, 599, 613, 601, 589, 598, 1616, 602, 589, 599, 613, 601, 1592, 598, 613, 601, 591, 625, 586, 600, 613, 602, 586, 601, 618, 594, 589, 603, 612, 599, 589, 602, 1615, 598, 1592, 601, 613, 598, 589, 601, 613, 600, 587, 602, 612, 602, 1589, 599, 614, 601, 1589, 601, 613, 601, 588, 599, 1616, 600, 589, 600, 20001, 599, 613, 601, 589, 621, 590, 599, 590, 625, 584, 601, 613, 572, 615, 600, 614, 597, 590, 600, 613, 599, 588, 600, 612, 602, 587, 600, 1615, 601, 586, 600, 613, 601, 589, 599, 613, 600, 588, 626, 585, 602, 591, 623, 585, 601, 612, 574, 614, 602, 612, 599, 589, 601, 612, 600, 589, 599, 1615, 599, 588, 601, 1614, 600, 587, 602};
   
    //Señal infrarroja de encendido AIRE
    unsigned int ON[] =  {9019, 4017, 601, 613, 601, 588, 600, 613, 601, 1591, 599, 613, 602, 588, 599, 614, 600, 590, 621, 1593, 600, 591, 596, 614, 602, 1591, 599, 613, 602, 591, 650, 560, 602, 612, 574, 614, 602, 614, 596, 590, 601, 612, 599, 589, 600, 1616, 599, 1591, 601, 613, 598, 589, 601, 614, 600, 588, 600, 614, 601, 1590, 601, 612, 601, 1590, 601, 613, 601, 589, 599, 1617, 600, 588, 601, 20014, 601, 613, 601, 589, 651, 561, 601, 613, 602, 587, 601, 613, 572, 615, 602, 614, 597, 590, 600, 614, 601, 588, 601, 612, 601, 589, 599, 1616, 600, 588, 600, 614, 601, 588, 599, 613, 601, 592, 623, 587, 600, 614, 601, 587, 601, 614, 599, 589, 601, 613, 599, 589, 601, 613, 601, 589, 600, 1616, 601, 587, 601, 1616, 601, 1590, 602};






    void setup()
    {
      irsend.begin();
      Serial.begin(9600);
      Blynk.begin(auth, ssid, pass);
      pinMode(RelePin, OUTPUT);
      pinMode(RelePin2, OUTPUT);
      dht.begin();
     // sensors.begin();   //Se inicia el sensor
      mux.signalPin(A0, INPUT, ANALOG);





  // Configuramos el timer para que se ejecute cada 2 segundos
timer.setInterval(60000L, sendSensor);
// timer.setInterval(50000L, TempExterior);
// timer.setInterval(70000L, SensorGas);

timer.setInterval(1000L, CurrentSensor);
timer.setInterval(1000L, Multiplexor);



  irrecv.enableIRIn();  //Inicia receptor INFRA

ESP.wdtDisable();
ESP.wdtEnable(WDTO_8S);



    
    }

    

    BLYNK_WRITE(V1){
      int onoff = param.asInt();
      if(onoff == 1){

        for (int i = 0; i < 3; i++) 
{
        
      irsend.sendNEC(0x20DF10EF, 32); // Prende TV Cuarto principal

}
      
      Serial.println("Transmitting");
      terminal.println("Prender TV Main") ;
        terminal.flush();
      
    }

    }
    BLYNK_WRITE(V2){
      int mode = param.asInt();
      if(mode == 1){
      terminal.println("Prender Aire Main") ;
    irsend.sendRaw(ON, sizeof(ON) / sizeof(ON[0]), khz);  //Prende Aire Cuarto Principal
     }
     else
      {
              terminal.println("Apagar Aire Main") ;

      irsend.sendRaw(OFF, sizeof(OFF) / sizeof(OFF[0]), khz); //Apaga Aire Cuarto Principal

      }
     
     }
      

  
     
    
//Funcione lectura codigos INFRA

    void dump(decode_results *results) {
  int count = results->rawlen;
  if (results->decode_type == UNKNOWN) {
    Serial.print("Unknown encoding: ");
  }
  else if (results->decode_type == NEC) {
    Serial.print("Decoded NEC: ");
  }
  else if (results->decode_type == SONY) {
    Serial.print("Decoded SONY: ");
  }
  else if (results->decode_type == RC5) {
    Serial.print("Decoded RC5: ");
  }
  else if (results->decode_type == RC6) {
    Serial.print("Decoded RC6: ");
  }
  else if (results->decode_type == PANASONIC) {
    Serial.print("Decoded PANASONIC - Address: ");
    Serial.print(results->panasonicAddress, HEX);
    Serial.print(" Value: ");
  }
  else if (results->decode_type == LG) {
    Serial.print("Decoded LG: ");
  }
  else if (results->decode_type == JVC) {
    Serial.print("Decoded JVC: ");
  }
  else if (results->decode_type == AIWA_RC_T501) {
    Serial.print("Decoded AIWA RC T501: ");
  }
  else if (results->decode_type == WHYNTER) {
    Serial.print("Decoded Whynter: ");
  }
  Serial.print(results->value, HEX);
  Serial.print(" (");
  Serial.print(results->bits, DEC);
  Serial.println(" bits)");
  Serial.print("Raw (");
  Serial.print(count, DEC);
  Serial.print("): ");

  for (int i = 1; i < count; i++) {
    if (i & 1) {
      Serial.print(results->rawbuf[i]*USECPERTICK, DEC);
    }
    else {
      Serial.write('-');
      Serial.print((unsigned long) results->rawbuf[i]*USECPERTICK, DEC);
    }
    Serial.print(" ");
  }
  Serial.println();






}
    void loop() {
      Blynk.run();
      timer.run(); // Iniciamos SimpleTimer
  

      //Lectura codigos infrarrojos
      
      /*if (irrecv.decode(&results)) {
      Serial.println(results.value, HEX);
      dump(&results);
      irrecv.resume(); }
           
      //Lectura codigos infrarrojos*/

 }

           

    
      
    

    //Definimos funcion para el DHT22
    void sendSensor()
{
  float  h = dht.readHumidity();
  float  t = dht.readTemperature(); // o dht.readTemperature(true) para mostrar la Tº en Fahrenheit
  
  if (isnan(h) || isnan(t)) {
    Serial.println("Error al leer datos del sensor");
 //   Serial.println(DateTime.now());
    return;
  }
  // Puedes enviar cualquier datos en cualquier momento
  // pero no envíen más de 10 datos por segundo, sino su app no funcionará.
  Blynk.virtualWrite(V5, h);
  Blynk.virtualWrite(V6, t);
  Serial.println(t);
    Serial.println(h);

  
}


/*
void TempExterior()
{
   sensors.requestTemperatures();   //Se envía el comando para leer la temperatura
float temp= sensors.getTempCByIndex(0); //Se obtiene la temperatura en ºC


Blynk.virtualWrite(V7, temp);
Serial.print("Temperatura= ");
Serial.print(temp);
Serial.println(" C");
            
}
*/

/*
void relayStatus_1(){
  
int relayState = digitalRead(RelePin);
if (relayState == LOW)
{
  Serial.println("RELE1 LOW");
   led3.on();
} else {
  Serial.println("RELE1 HIGH");
   led3.off();
}


}
*/




/* FUNCION SENSOR GAS
void SensorGas()
{
  int mq2 = (analogRead(gasPin));

  if (mq2>400){
           
           gasDetected = "Se detectó gas butano";
           Serial.println(gasDetected);
      }
      else
      {
           
           gasDetected= "Aire limpio";
           Serial.println(gasDetected);


      }

Blynk.virtualWrite(V9, gasDetected);
      

}*/

float getVPP()
{
  float result;
  int readValue;             // value read from the sensor
  int maxValue = 0;          // store max value here
  int minValue = 1024;       // store min value here

   uint32_t start_time = millis();
   while((millis()-start_time) < 1000)  // sample for 1 Sec
   {
       readValue = analogRead(sensorIn);
       // see if you have a new maxValue
       if (readValue > maxValue) 
       {
            /*record the maximum sensor value*/
           maxValue = readValue;
       }
       if (readValue < minValue) 
       {
           /*record the minimum sensor value*/
           minValue = readValue;
       }
   }

   // Subtract min from max
   result = ((maxValue - minValue) * 5.0)/1024.0;

   return result;
 }

void CurrentSensor()
{
  Voltage = getVPP();
 VRMS = (Voltage/2.0) *0.707;  //root 2 is 0.707
 AmpsRMS = (VRMS * 1000)/mVperAmp;
 Serial.print(AmpsRMS);
 Serial.println(" Amps RMS");
 
 Blynk.virtualWrite(V9, AmpsRMS);

 if(AmpsRMS > 0.50){
    Blynk.virtualWrite(V1, HIGH);  
 }
 else
 {
    Blynk.virtualWrite(V1, LOW);  
 }



}




void Multiplexor()

{

  ESP.wdtFeed();

      int data;

  for (byte i = 0; i < 16; ++i)
  {
    // Reads from channel i. Returns a value from 0 to 1023
    data = mux.read(i);
    Serial.print("Potentiometer at channel ");
    Serial.print(i);
    Serial.print(" is at ");
    Serial.print((double)(data) * 100 / 1023);
    Serial.println("%%");
    }
      Serial.println();
  
   

}






/*  BLYNK_CONNECTED() {
    if (isFirstConnect) {
Blynk.syncAll();
isFirstConnect = false;}
          terminal.println("Blynk se ha conectado") ;

}*/


why do you need to check temperature every second? this is some project for a nuclear reactor? :slight_smile:

per the datasheet, for dht22 the max sampling rate is 2 seconds, so, you should use at least 2500 millis between 2 reads. but even that is overkill… for room temperature monitoring it would be more reasonable once evey 10 seconds or once every minute.

the same here… you switch your tv on / off several times a minute? or what is the reason for that?

for just simple on / off monitoring, you can check if a logic level voltage is present or not, or, put a ldr to the led on the tv.

in the getvpp function you sample for 1000 millis, that is a bit too much for blynk. this can cause heartbeat timeout or render the system unresponsive. try to sample less than 500 millis.

The TV interval is 60 seconds, about acs712 you are right, but what about if you really need to use 2 sensors in realtime interval? Is it possible? Or its a nodemcu hardware limit or blynk limit? Thanks in advance.

it is possible of course. but also the sensors should be up to the task, and the code should be optimised.

if you still have the 4 seconds delay, try to check the

  • quality of your wifi / internet connection (ping)
  • reduce “blocking” delays in code
  • put a serial println millis at the beginning if each function, to monitor which function how long it takes to execute. this can help to find the cause.

normally, the action in blynk app (press of a button) should be close to real time on hardware, even on cloud server.

esit: for hardware serial learn to use 115200 baud, that is a generally decent speed for atmel and esp too. 9600 is obsolete and really slow.

How can I put a serial println to monitor functions? Thanks (115200 baud changed!)

well, simple as that :slight_smile:

just put this at the beginning of each function:

Serial.print("entering function x: ");
Serial.println(millis());

thus you can see how much it takes for each function to execute. if there are hangs somewhere, that would be obvious to see.

Thank you, i’ ve changed some timers and now its working ok, but I have a question how can my code could be optimized? I Need some tips to make it work better.

well, if i look at the content of your code, it seems that was written by someone who knows what he is doing…

but if i look at the general aspect and indentation, formatting, it is quite unorganised and ugly.

so, i assume that you are a novice, who copy pasted together several existing code fragments until the desired outcome was achieved :slight_smile:

if you want to optimise the code, first, try to work on the general aspect (prettiness). or, at least, use the right click > auto format in arduino ide. it is useful :wink:

https://www.quora.com/What-is-an-example-of-beautiful-coding

https://blog.codinghorror.com/pretty-code-ugly-code/

Thank you for all your tips!

please mark topic as solved if you feel so!

The topic is solved, is there any button to close the thread?

yeah, you can edit at the topic title, change the category

1 Like

Done!

1 Like