Help make Openhab2 MQ2 AirQuality work



  • Dear All!

    I would like to configure my ethernet gateway + NODE 1 (DHT+MQ2) sensor node with openhab2

    Some friends from here helped to me , so i could create the node's sketch. The temperature+humidity works, but i cant make the mq2 sensor work. I use the airquality sketch for it mixed it with the temperaturehumidity sketch.
    The openhab get the value from the mq2 (based on the logs) but i cant display it on the website.
    I have just seen that based on this table Controller table the airquality is not supported in the openhab 2 + mysensors . Is it true?

    Node's sketch:

    /**
     * The MySensors Arduino library handles the wireless radio link and protocol
     * between your home built sensors/actuators and HA controller of choice.
     * The sensors forms a self healing radio network with optional repeaters. Each
     * repeater and gateway builds a routing tables in EEPROM which keeps track of the
     * network topology allowing messages to be routed to nodes.
     *
     * Created by Henrik Ekblad <henrik.ekblad@mysensors.org>
     * Copyright (C) 2013-2015 Sensnology AB
     * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
     *
     * Documentation: http://www.mysensors.org
     * Support Forum: http://forum.mysensors.org
     *
     * This program is free software; you can redistribute it and/or
     * modify it under the terms of the GNU General Public License
     * version 2 as published by the Free Software Foundation.
     *
     *******************************
     *
     * REVISION HISTORY
     * Version 1.0: Henrik EKblad
     * Version 1.1 - 2016-07-20: Converted to MySensors v2.0 and added various improvements - Torben Woltjen (mozzbozz)
     * 
     * DESCRIPTION
     * This sketch provides an example of how to implement a humidity/temperature
     * sensor using a DHT11/DHT-22.
     *  
     * For more information, please visit:
     * http://www.mysensors.org/build/humidity
     * 
     */
    #define MY_NODE_ID 1
    // Enable debug prints
    #define MY_DEBUG
    
    // Enable and select radio type attached 
    #define MY_RADIO_NRF24
    //#define MY_RADIO_RFM69
    //#define MY_RS485
    /* TemperatureAndHumidity */
    #include <SPI.h>
    #include <MySensors.h>  
    #include <DHT.h>
    
    // Set this to the pin you connected the DHT's data pin to
    #define DHT_DATA_PIN 3
    
    // Set this offset if the sensor has a permanent small offset to the real temperatures
    #define SENSOR_TEMP_OFFSET 0
    
    // Sleep time between sensor updates (in milliseconds)
    // Must be >1000ms for DHT22 and >2000ms for DHT11
    static const uint64_t UPDATE_INTERVAL = 5000;
    
    // Force sending an update of the temperature after n sensor reads, so a controller showing the
    // timestamp of the last update doesn't show something like 3 hours in the unlikely case, that
    // the value didn't change since;
    // i.e. the sensor would force sending an update every UPDATE_INTERVAL*FORCE_UPDATE_N_READS [ms]
    static const uint8_t FORCE_UPDATE_N_READS = 10;
    
    #define CHILD_ID_HUM 0
    #define CHILD_ID_TEMP 1
    
    float lastTemp;
    float lastHum;
    uint8_t nNoUpdatesTemp;
    uint8_t nNoUpdatesHum;
    bool metric = true;
    
    /*---------------------------------MQ2---------------------------------------------------------*/
    
    #define   CHILD_ID_MQ                   2
    /************************Hardware Related Macros************************************/
    #define   MQ_SENSOR_ANALOG_PIN         (0)  //define which analog input channel you are going to use
    #define         RL_VALUE                     (5)     //define the load resistance on the board, in kilo ohms
    #define         RO_CLEAN_AIR_FACTOR          (9.83)  //RO_CLEAR_AIR_FACTOR=(Sensor resistance in clean air)/RO,
    //which is derived from the chart in datasheet
    /***********************Software Related Macros************************************/
    #define         CALIBARAION_SAMPLE_TIMES     (50)    //define how many samples you are going to take in the calibration phase
    #define         CALIBRATION_SAMPLE_INTERVAL  (500)   //define the time interal(in milisecond) between each samples in the
    //cablibration phase
    #define         READ_SAMPLE_INTERVAL         (50)    //define how many samples you are going to take in normal operation
    #define         READ_SAMPLE_TIMES            (5)     //define the time interal(in milisecond) between each samples in
    //normal operation
    /**********************Application Related Macros**********************************/
    #define         GAS_LPG                      (0)
    #define         GAS_CO                       (1)
    #define         GAS_SMOKE                    (2)
    /*****************************Globals***********************************************/
    //unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds)
    unsigned long SLEEP_TIME = 5000; // Sleep time between reads (in milliseconds)
    //VARIABLES
    float Ro = 10000.0;    // this has to be tuned 10K Ohm
    int val = 0;           // variable to store the value coming from the sensor
    float valMQ =0.0;
    float lastMQ =0.0;
    float           LPGCurve[3]  =  {2.3,0.21,-0.47};   //two points are taken from the curve.
    //with these two points, a line is formed which is "approximately equivalent"
    //to the original curve.
    //data format:{ x, y, slope}; point1: (lg200, 0.21), point2: (lg10000, -0.59)
    float           COCurve[3]  =  {2.3,0.72,-0.34};    //two points are taken from the curve.
    //with these two points, a line is formed which is "approximately equivalent"
    //to the original curve.
    //data format:{ x, y, slope}; point1: (lg200, 0.72), point2: (lg10000,  0.15)
    float           SmokeCurve[3] = {2.3,0.53,-0.44};   //two points are taken from the curve.
    //with these two points, a line is formed which is "approximately equivalent"
    //to the original curve.
    //data format:{ x, y, slope}; point1: (lg200, 0.53), point2:(lg10000,-0.22)
    /*--------------------MQ2 end---------------------------------*/
    MyMessage msgHum(CHILD_ID_HUM, V_HUM);
    MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP);
    DHT dht;
    MyMessage msg(CHILD_ID_MQ, V_LEVEL);       
    
    void presentation()  
    { 
      // Send the sketch version information to the gateway
      // sendSketchInfo("TemperatureAndHumidity", "1.1");
      sendSketchInfo("Temperature, Humidity and Gas", "1.1"); /*MQ2*/
      
      // Register all sensors to gw (they will be created as child devices)
      present(CHILD_ID_HUM, S_HUM);
      present(CHILD_ID_TEMP, S_TEMP);
      present(CHILD_ID_MQ, S_AIR_QUALITY); /*MQ2*/
      // present(CHILD_ID_MQ, S_SMOKE); /*MQ2*/
      metric = getControllerConfig().isMetric;
    
        
    }
    
    
    void setup()
    {
      dht.setup(DHT_DATA_PIN); // set data pin of DHT sensor
      if (UPDATE_INTERVAL <= dht.getMinimumSamplingPeriod()) {
        Serial.println("Warning: UPDATE_INTERVAL is smaller than supported by the sensor!");
      }
      // Sleep for the time of the minimum sampling period to give the sensor time to power up
      // (otherwise, timeout errors might occure for the first reading)
      sleep(dht.getMinimumSamplingPeriod());
      /*---MQ2---------------------------------------------------------*/
      Ro = MQCalibration(MQ_SENSOR_ANALOG_PIN);  //Calibrating the sensor. Please make sure the sensor is in clean air                                       
    }
    
    void loop()      
    {  
      // Force reading sensor, so it works also after sleep()
      dht.readSensor(true);
      
      // Get temperature from DHT library
      float temperature = dht.getTemperature();
      if (isnan(temperature)) {
        Serial.println("Failed reading temperature from DHT!");
      } else if (temperature != lastTemp || nNoUpdatesTemp == FORCE_UPDATE_N_READS) {
        // Only send temperature if it changed since the last measurement or if we didn't send an update for n times
        lastTemp = temperature;
        if (!metric) {
          temperature = dht.toFahrenheit(temperature);
        }
        // Reset no updates counter
        nNoUpdatesTemp = 0;
        temperature += SENSOR_TEMP_OFFSET;
        send(msgTemp.set(temperature, 1));
    
        #ifdef MY_DEBUG
        Serial.print("T: ");
        Serial.println(temperature);
        #endif
      } else {
        // Increase no update counter if the temperature stayed the same
        nNoUpdatesTemp++;
      }
    
      // Get humidity from DHT library
      float humidity = dht.getHumidity();
      if (isnan(humidity)) {
        Serial.println("Failed reading humidity from DHT");
      } else if (humidity != lastHum || nNoUpdatesHum == FORCE_UPDATE_N_READS) {
        // Only send humidity if it changed since the last measurement or if we didn't send an update for n times
        lastHum = humidity;
        // Reset no updates counter
        nNoUpdatesHum = 0;
        send(msgHum.set(humidity, 1));
        
        #ifdef MY_DEBUG
        Serial.print("H: ");
        Serial.println(humidity);
        #endif
      } else {
        // Increase no update counter if the humidity stayed the same
        nNoUpdatesHum++;
      }
    
    /*----MQ2----*/
    uint16_t valMQ = MQGetGasPercentage(MQRead(MQ_SENSOR_ANALOG_PIN)/Ro,GAS_CO);
      Serial.println(val);
    
      Serial.print("LPG:");
      Serial.print(MQGetGasPercentage(MQRead(MQ_SENSOR_ANALOG_PIN)/Ro,GAS_LPG) );
      Serial.print( "ppm" );
      Serial.print("    ");
      Serial.print("CO:");
      Serial.print(MQGetGasPercentage(MQRead(MQ_SENSOR_ANALOG_PIN)/Ro,GAS_CO) );
      Serial.print( "ppm" );
      Serial.print("    ");
      Serial.print("SMOKE:");
      Serial.print(MQGetGasPercentage(MQRead(MQ_SENSOR_ANALOG_PIN)/Ro,GAS_SMOKE) );
      Serial.print( "ppm" );
      Serial.print("\n");
    
      if (valMQ != lastMQ) {
        send(msg.set((int16_t)ceil(valMQ)));
        lastMQ = ceil(valMQ);
      }
     
      // Sleep for a while to save energy
      sleep(UPDATE_INTERVAL); 
      
      
      
    }
    
    /*----MQ2----*/
    /****************** MQResistanceCalculation ****************************************
    Input:   raw_adc - raw value read from adc, which represents the voltage
    Output:  the calculated sensor resistance
    Remarks: The sensor and the load resistor forms a voltage divider. Given the voltage
             across the load resistor and its resistance, the resistance of the sensor
             could be derived.
    ************************************************************************************/
    float MQResistanceCalculation(int raw_adc)
    {
      return ( ((float)RL_VALUE*(1023-raw_adc)/raw_adc));
    }
    
    /***************************** MQCalibration ****************************************
    Input:   mq_pin - analog channel
    Output:  Ro of the sensor
    Remarks: This function assumes that the sensor is in clean air. It use
             MQResistanceCalculation to calculates the sensor resistance in clean air
             and then divides it with RO_CLEAN_AIR_FACTOR. RO_CLEAN_AIR_FACTOR is about
             10, which differs slightly between different sensors.
    ************************************************************************************/
    float MQCalibration(int mq_pin)
    {
      int i;
      float val=0;
    
      for (i=0; i<CALIBARAION_SAMPLE_TIMES; i++) {          //take multiple samples
        val += MQResistanceCalculation(analogRead(mq_pin));
        delay(CALIBRATION_SAMPLE_INTERVAL);
      }
      val = val/CALIBARAION_SAMPLE_TIMES;                   //calculate the average value
    
      val = val/RO_CLEAN_AIR_FACTOR;                        //divided by RO_CLEAN_AIR_FACTOR yields the Ro
      //according to the chart in the datasheet
    
      return val;
    }
    /*****************************  MQRead *********************************************
    Input:   mq_pin - analog channel
    Output:  Rs of the sensor
    Remarks: This function use MQResistanceCalculation to caculate the sensor resistenc (Rs).
             The Rs changes as the sensor is in the different consentration of the target
             gas. The sample times and the time interval between samples could be configured
             by changing the definition of the macros.
    ************************************************************************************/
    float MQRead(int mq_pin)
    {
      int i;
      float rs=0;
    
      for (i=0; i<READ_SAMPLE_TIMES; i++) {
        rs += MQResistanceCalculation(analogRead(mq_pin));
        delay(READ_SAMPLE_INTERVAL);
      }
    
      rs = rs/READ_SAMPLE_TIMES;
      return rs;   
    }
                                      
               
       
    
    /*****************************  MQGetGasPercentage **********************************
    Input:   rs_ro_ratio - Rs divided by Ro
             gas_id      - target gas type
    Output:  ppm of the target gas
    Remarks: This function passes different curves to the MQGetPercentage function which
             calculates the ppm (parts per million) of the target gas.
    ************************************************************************************/
    int MQGetGasPercentage(float rs_ro_ratio, int gas_id)
    {
      if ( gas_id == GAS_LPG ) {
        return MQGetPercentage(rs_ro_ratio,LPGCurve);
      } else if ( gas_id == GAS_CO ) {
        return MQGetPercentage(rs_ro_ratio,COCurve);
      } else if ( gas_id == GAS_SMOKE ) {
        return MQGetPercentage(rs_ro_ratio,SmokeCurve);
            
      }
    
      return 0;
                  
    }
    
    /*****************************  MQGetPercentage **********************************
    Input:   rs_ro_ratio - Rs divided by Ro
             pcurve      - pointer to the curve of the target gas
    Output:  ppm of the target gas
    Remarks: By using the slope and a point of the line. The x(logarithmic value of ppm)
             of the line could be derived if y(rs_ro_ratio) is provided. As it is a
             logarithmic coordinate, power of 10 is used to convert the result to non-logarithmic
             value.
    ************************************************************************************/
    int  MQGetPercentage(float rs_ro_ratio, float *pcurve)
    {
      return (pow(10,( ((log(rs_ro_ratio)-pcurve[1])/pcurve[2]) + pcurve[0])));
    }
    /*----MQ2----*/```
    

    Openhab2 logs:

    2017-07-25 21:17:29.818 [DEBUG] [ensors.handler.MySensorsThingHandler] - Updating channel: temp(V_TEMP) value to: 27.0
    2017-07-25 21:17:29.821 [DEBUG] [ensors.handler.MySensorsThingHandler] - Setting last update for node/child 1/1 to 2017-07-25T21:17:29.000+0200
    2017-07-25 21:17:29.821 [DEBUG] [rsAbstractConnection$MySensorsReader] - Message from gateway received: 1;0;1;0;1;36.0
    2017-07-25 21:17:29.822 [DEBUG] [rs.internal.gateway.MySensorsGateway] - Node 1 found in gateway
    2017-07-25 21:17:29.822 [DEBUG] [rs.internal.gateway.MySensorsGateway] - Child 0 found in node 1
    2017-07-25 21:17:29.822 [DEBUG] [ensors.handler.MySensorsThingHandler] - Updating channel: hum(V_HUM) value to: 36.0
    2017-07-25 21:17:29.823 [DEBUG] [ensors.handler.MySensorsThingHandler] - Setting last update for node/child 1/0 to 2017-07-25T21:17:29.000+0200
    2017-07-25 21:17:30.838 [DEBUG] [rsAbstractConnection$MySensorsReader] - Message from gateway received: 1;2;1;0;37;32111
    2017-07-25 21:17:30.839 [DEBUG] [rs.internal.gateway.MySensorsGateway] - Node 1 found in gateway
    2017-07-25 21:17:30.839 [DEBUG] [rs.internal.gateway.MySensorsGateway] - Child 2 not present in node 1

    Openhab codes:

    Bridge mysensors:bridge-eth:gateway [ ipAddress="100.100.6.41", tcpPort=5003, sendDelay=200, startupCheckEnabled=false,networkSanCheckEnabled=false ] {
    /** define things connected to that bridge here */
    humidity hum01 [ nodeId=1, childId=0 ]
    temperature temp01 [ nodeId=1, childId=1 ]
    airquality airq01 [ nodeId=1, childId=2 ]
    }

    items

    Number hum01 "Humidity" { channel="mysensors:humidity:gateway:hum01:hum" }
    Number temp01 "Temperature" { channel="mysensors:temperature:gateway:temp01:temp" }
    Number airq01 "AirQuality" { channel="mysensors:airquality:gateway:airq01:level" }

    Thanking you in advance for the helping..



  • Dear All!

    I dont know exactly what i did to make it work, but it is almost OK now.
    Almost, because on the PaperUI the Control tab shows the right value of the Air Quality Meter, but on the BasicUI sitemap and in the OPENHAB ios APP shows only the Text (Air Quality ...) without the value

    I attach the new sketch and code, if somebody could help me:

    Sketch

    /**
     * The MySensors Arduino library handles the wireless radio link and protocol
     * between your home built sensors/actuators and HA controller of choice.
     * The sensors forms a self healing radio network with optional repeaters. Each
     * repeater and gateway builds a routing tables in EEPROM which keeps track of the
     * network topology allowing messages to be routed to nodes.
     *
     * Created by Henrik Ekblad <henrik.ekblad@mysensors.org>
     * Copyright (C) 2013-2015 Sensnology AB
     * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
     *
     * Documentation: http://www.mysensors.org
     * Support Forum: http://forum.mysensors.org
     *
     * This program is free software; you can redistribute it and/or
     * modify it under the terms of the GNU General Public License
     * version 2 as published by the Free Software Foundation.
     *
     *******************************
     *
     * REVISION HISTORY
     * Version 1.0: Henrik EKblad
     * Version 1.1 - 2016-07-20: Converted to MySensors v2.0 and added various improvements - Torben Woltjen (mozzbozz)
     * 
     * DESCRIPTION
     * This sketch provides an example of how to implement a humidity/temperature
     * sensor using a DHT11/DHT-22.
     *  
     * For more information, please visit:
     * http://www.mysensors.org/build/humidity
     * 
     */
    #define MY_NODE_ID 1
    // Enable debug prints
    #define MY_DEBUG
    
    // Enable and select radio type attached 
    #define MY_RADIO_NRF24
    //#define MY_RADIO_RFM69
    //#define MY_RS485
    /* TemperatureAndHumidity */
    #include <SPI.h>
    #include <MySensors.h>  
    #include <DHT.h>
    
    // Set this to the pin you connected the DHT's data pin to
    #define DHT_DATA_PIN 3
    
    // Set this offset if the sensor has a permanent small offset to the real temperatures
    #define SENSOR_TEMP_OFFSET 0
    
    // Sleep time between sensor updates (in milliseconds)
    // Must be >1000ms for DHT22 and >2000ms for DHT11
    static const uint64_t UPDATE_INTERVAL = 5000;
    
    // Force sending an update of the temperature after n sensor reads, so a controller showing the
    // timestamp of the last update doesn't show something like 3 hours in the unlikely case, that
    // the value didn't change since;
    // i.e. the sensor would force sending an update every UPDATE_INTERVAL*FORCE_UPDATE_N_READS [ms]
    static const uint8_t FORCE_UPDATE_N_READS = 10;
    
    #define CHILD_ID_HUM 0
    #define CHILD_ID_TEMP 1
    #define CHILD_ID_MQ 2 /*MQ2*/
    float lastTemp;
    float lastHum;
    uint8_t nNoUpdatesTemp;
    uint8_t nNoUpdatesHum;
    bool metric = true;
    
    /*---------------------------------MQ2---------------------------------------------------------*/
    
    
    /************************Hardware Related Macros************************************/
    #define   MQ_SENSOR_ANALOG_PIN         (0)  //define which analog input channel you are going to use
    #define         RL_VALUE                     (5)     //define the load resistance on the board, in kilo ohms
    #define         RO_CLEAN_AIR_FACTOR          (9.83)  //RO_CLEAR_AIR_FACTOR=(Sensor resistance in clean air)/RO,
    //which is derived from the chart in datasheet
    /***********************Software Related Macros************************************/
    #define         CALIBARAION_SAMPLE_TIMES     (50)    //define how many samples you are going to take in the calibration phase
    #define         CALIBRATION_SAMPLE_INTERVAL  (500)   //define the time interal(in milisecond) between each samples in the
    //cablibration phase
    #define         READ_SAMPLE_INTERVAL         (50)    //define how many samples you are going to take in normal operation
    #define         READ_SAMPLE_TIMES            (5)     //define the time interal(in milisecond) between each samples in
    //normal operation
    /**********************Application Related Macros**********************************/
    #define         GAS_LPG                      (0)
    #define         GAS_CO                       (1)
    #define         GAS_SMOKE                    (2)
    /*****************************Globals***********************************************/
    //unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds)
    unsigned long SLEEP_TIME = 5000; // Sleep time between reads (in milliseconds)
    //VARIABLES
    float Ro = 10000.0;    // this has to be tuned 10K Ohm
    int val = 0;           // variable to store the value coming from the sensor
    float valMQ =0.0;
    float lastMQ =0.0;
    float           LPGCurve[3]  =  {2.3,0.21,-0.47};   //two points are taken from the curve.
    //with these two points, a line is formed which is "approximately equivalent"
    //to the original curve.
    //data format:{ x, y, slope}; point1: (lg200, 0.21), point2: (lg10000, -0.59)
    float           COCurve[3]  =  {2.3,0.72,-0.34};    //two points are taken from the curve.
    //with these two points, a line is formed which is "approximately equivalent"
    //to the original curve.
    //data format:{ x, y, slope}; point1: (lg200, 0.72), point2: (lg10000,  0.15)
    float           SmokeCurve[3] = {2.3,0.53,-0.44};   //two points are taken from the curve.
    //with these two points, a line is formed which is "approximately equivalent"
    //to the original curve.
    //data format:{ x, y, slope}; point1: (lg200, 0.53), point2:(lg10000,-0.22)
    /*--------------------MQ2 end---------------------------------*/
    MyMessage msgHum(CHILD_ID_HUM, V_HUM);
    MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP);
    DHT dht;
    MyMessage msg(CHILD_ID_MQ, V_LEVEL);       
    
    void presentation()  
    { 
      // Send the sketch version information to the gateway
      // sendSketchInfo("TemperatureAndHumidity", "1.1");
      sendSketchInfo("Temperature, Humidity and Gas", "1.1"); /*MQ2*/
      
      // Register all sensors to gw (they will be created as child devices)
      present(CHILD_ID_HUM, S_HUM);
      present(CHILD_ID_TEMP, S_TEMP);
      present(CHILD_ID_MQ, S_AIR_QUALITY); /*MQ2*/
      // present(CHILD_ID_MQ, S_SMOKE); /*MQ2*/
      metric = getControllerConfig().isMetric;
    
        
    }
    
    
    void setup()
    {
      dht.setup(DHT_DATA_PIN); // set data pin of DHT sensor
      if (UPDATE_INTERVAL <= dht.getMinimumSamplingPeriod()) {
        Serial.println("Warning: UPDATE_INTERVAL is smaller than supported by the sensor!");
      }
      // Sleep for the time of the minimum sampling period to give the sensor time to power up
      // (otherwise, timeout errors might occure for the first reading)
      sleep(dht.getMinimumSamplingPeriod());
      /*---MQ2---------------------------------------------------------*/
      Ro = MQCalibration(MQ_SENSOR_ANALOG_PIN);  //Calibrating the sensor. Please make sure the sensor is in clean air                                       
    }
    
    void loop()      
    {  
      // Force reading sensor, so it works also after sleep()
      dht.readSensor(true);
      
      // Get temperature from DHT library
      float temperature = dht.getTemperature();
      if (isnan(temperature)) {
        Serial.println("Failed reading temperature from DHT!");
      } else if (temperature != lastTemp || nNoUpdatesTemp == FORCE_UPDATE_N_READS) {
        // Only send temperature if it changed since the last measurement or if we didn't send an update for n times
        lastTemp = temperature;
        if (!metric) {
          temperature = dht.toFahrenheit(temperature);
        }
        // Reset no updates counter
        nNoUpdatesTemp = 0;
        temperature += SENSOR_TEMP_OFFSET;
        send(msgTemp.set(temperature, 1));
    
        #ifdef MY_DEBUG
        Serial.print("T: ");
        Serial.println(temperature);
        #endif
      } else {
        // Increase no update counter if the temperature stayed the same
        nNoUpdatesTemp++;
      }
    
      // Get humidity from DHT library
      float humidity = dht.getHumidity();
      if (isnan(humidity)) {
        Serial.println("Failed reading humidity from DHT");
      } else if (humidity != lastHum || nNoUpdatesHum == FORCE_UPDATE_N_READS) {
        // Only send humidity if it changed since the last measurement or if we didn't send an update for n times
        lastHum = humidity;
        // Reset no updates counter
        nNoUpdatesHum = 0;
        send(msgHum.set(humidity, 1));
        
        #ifdef MY_DEBUG
        Serial.print("H: ");
        Serial.println(humidity);
        #endif
      } else {
        // Increase no update counter if the humidity stayed the same
        nNoUpdatesHum++;
      }
    
    /*----MQ2----*/
    uint16_t valMQ = MQGetGasPercentage(MQRead(MQ_SENSOR_ANALOG_PIN)/Ro,GAS_CO);
      Serial.println(val);
    
      Serial.print("LPG:");
      Serial.print(MQGetGasPercentage(MQRead(MQ_SENSOR_ANALOG_PIN)/Ro,GAS_LPG) );
      Serial.print( "ppm" );
      Serial.print("    ");
      Serial.print("CO:");
      Serial.print(MQGetGasPercentage(MQRead(MQ_SENSOR_ANALOG_PIN)/Ro,GAS_CO) );
      Serial.print( "ppm" );
      Serial.print("    ");
      Serial.print("SMOKE:");
      Serial.print(MQGetGasPercentage(MQRead(MQ_SENSOR_ANALOG_PIN)/Ro,GAS_SMOKE) );
      Serial.print( "ppm" );
      Serial.print("\n");
    
      if (valMQ != lastMQ) {
        send(msg.set((int16_t)ceil(valMQ)));
        lastMQ = ceil(valMQ);
      }
     
      // Sleep for a while to save energy
      sleep(UPDATE_INTERVAL); 
      
      
      
    }
    
    /*----MQ2----*/
    /****************** MQResistanceCalculation ****************************************
    Input:   raw_adc - raw value read from adc, which represents the voltage
    Output:  the calculated sensor resistance
    Remarks: The sensor and the load resistor forms a voltage divider. Given the voltage
             across the load resistor and its resistance, the resistance of the sensor
             could be derived.
    ************************************************************************************/
    float MQResistanceCalculation(int raw_adc)
    {
      return ( ((float)RL_VALUE*(1023-raw_adc)/raw_adc));
    }
    
    /***************************** MQCalibration ****************************************
    Input:   mq_pin - analog channel
    Output:  Ro of the sensor
    Remarks: This function assumes that the sensor is in clean air. It use
             MQResistanceCalculation to calculates the sensor resistance in clean air
             and then divides it with RO_CLEAN_AIR_FACTOR. RO_CLEAN_AIR_FACTOR is about
             10, which differs slightly between different sensors.
    ************************************************************************************/
    float MQCalibration(int mq_pin)
    {
      int i;
      float val=0;
    
      for (i=0; i<CALIBARAION_SAMPLE_TIMES; i++) {          //take multiple samples
        val += MQResistanceCalculation(analogRead(mq_pin));
        delay(CALIBRATION_SAMPLE_INTERVAL);
      }
      val = val/CALIBARAION_SAMPLE_TIMES;                   //calculate the average value
    
      val = val/RO_CLEAN_AIR_FACTOR;                        //divided by RO_CLEAN_AIR_FACTOR yields the Ro
      //according to the chart in the datasheet
    
      return val;
    }
    /*****************************  MQRead *********************************************
    Input:   mq_pin - analog channel
    Output:  Rs of the sensor
    Remarks: This function use MQResistanceCalculation to caculate the sensor resistenc (Rs).
             The Rs changes as the sensor is in the different consentration of the target
             gas. The sample times and the time interval between samples could be configured
             by changing the definition of the macros.
    ************************************************************************************/
    float MQRead(int mq_pin)
    {
      int i;
      float rs=0;
    
      for (i=0; i<READ_SAMPLE_TIMES; i++) {
        rs += MQResistanceCalculation(analogRead(mq_pin));
        delay(READ_SAMPLE_INTERVAL);
      }
    
      rs = rs/READ_SAMPLE_TIMES;
      return rs;   
    }
                                      
               
       
    
    /*****************************  MQGetGasPercentage **********************************
    Input:   rs_ro_ratio - Rs divided by Ro
             gas_id      - target gas type
    Output:  ppm of the target gas
    Remarks: This function passes different curves to the MQGetPercentage function which
             calculates the ppm (parts per million) of the target gas.
    ************************************************************************************/
    int MQGetGasPercentage(float rs_ro_ratio, int gas_id)
    {
      if ( gas_id == GAS_LPG ) {
        return MQGetPercentage(rs_ro_ratio,LPGCurve);
      } else if ( gas_id == GAS_CO ) {
        return MQGetPercentage(rs_ro_ratio,COCurve);
      } else if ( gas_id == GAS_SMOKE ) {
        return MQGetPercentage(rs_ro_ratio,SmokeCurve);
            
      }
    
      return 0;
                  
    }
    
    /*****************************  MQGetPercentage **********************************
    Input:   rs_ro_ratio - Rs divided by Ro
             pcurve      - pointer to the curve of the target gas
    Output:  ppm of the target gas
    Remarks: By using the slope and a point of the line. The x(logarithmic value of ppm)
             of the line could be derived if y(rs_ro_ratio) is provided. As it is a
             logarithmic coordinate, power of 10 is used to convert the result to non-logarithmic
             value.
    ************************************************************************************/
    int  MQGetPercentage(float rs_ro_ratio, float *pcurve)
    {
      return (pow(10,( ((log(rs_ro_ratio)-pcurve[1])/pcurve[2]) + pcurve[0])));
    }
    /*----MQ2----*/
    

    Openhab codes:

    /etc/openhab2/sitemaps# cat /etc/openhab2/things/demo.things
    Bridge mysensors:bridge-eth:gateway [ ipAddress="100.100.6.41", tcpPort=5003, sendDelay=200, startupCheckEnabled=false,networkSanCheckEnabled=false ] {
    /** define things connected to that bridge here */
    humidity hum01 [ nodeId=1, childId=0 ]
    temperature temp01 [ nodeId=1, childId=1 ]
    airQuality airq01 [ nodeId=1, childId=2 ]
    }

    /etc/openhab2/sitemaps# cat /etc/openhab2/items/demo.items
    Number hum01 "Humidity" { channel="mysensors:humidity:gateway:hum01:hum" }
    Number temp01 "Temperature" { channel="mysensors:temperature:gateway:temp01:temp" }
    Number airq01 "AirQuality" { channel="mysensors:airquality:gateway:airq01:level" }

    :/etc/openhab2/sitemaps# cat /etc/openhab2/sitemaps/demo.sitemap
    sitemap demo label="Main Menu" {
    Frame {
    Text item=hum01
    Text item=temp01
    Default item=airq01

        }
    

    }

    Thank you in advance!

    Best regards,
    T


  • Hero Member

    Hey @Tommas !

    Add a placeholder [] to the text in items file.

    Number hum01 "Humidity [%.1f %%]" { channel="mysensors:humidity:gateway:hum01:hum" }
    Number temp01 "Temperature [%.1f °C]" { channel="mysensors:temperature:gateway:temp01:temp" }
    Number airq01 "AirQuality [%d]" { channel="mysensors:airquality:gateway:airq01:level" }
    


  • Dear @TimO

    Unfortunately it isnt enough. A - sign appeares but the value missing :(

    Best regrards
    T



  • Hey @Tommas
    What happens if you in the sitemap change "Defult item=airq01" to "Text item=airq01"



  • @MagnusF

    Unfortunately nothing changed:(
    I paste the openhab log, when the mq2 sense something:

    2017-07-27 18:42:12.899 [DEBUG] [rs.internal.gateway.MySensorsGateway] - Node 1 found in gateway
    2017-07-27 18:42:12.899 [DEBUG] [rs.internal.gateway.MySensorsGateway] - Child 2 found in node 1
    2017-07-27 18:42:12.900 [DEBUG] [ensors.handler.MySensorsThingHandler] - Updating channel: level(V_LEVEL) value to: 4
    2017-07-27 18:42:12.902 [DEBUG] [ensors.handler.MySensorsThingHandler] - Setting last update for node/child 1/2 to 2017-07-27T18:42:12.000+0200
    2017-07-27 18:42:19.369 [DEBUG] [rsAbstractConnection$MySensorsReader] - Message from gateway received: 1;2;1;0;37;0
    2017-07-27 18:42:19.370 [DEBUG] [rs.internal.gateway.MySensorsGateway] - Node 1 found in gateway
    2017-07-27 18:42:19.370 [DEBUG] [rs.internal.gateway.MySensorsGateway] - Child 2 found in node 1
    2017-07-27 18:42:19.371 [DEBUG] [ensors.handler.MySensorsThingHandler] - Updating channel: level(V_LEVEL) value to: 0
    2017-07-27 18:42:19.373 [DEBUG] [ensors.handler.MySensorsThingHandler] - Setting last update for node/child 1/2 to 2017-07-27T18:42:19.000+0200
    


  • @Tommas

    Dear all!

    Has someone any idea, why i cant display the mq2 value on the sitemap?
    Only a "-" appear. I would like to see the value. On the control tab on the paperui i see the changes.
    Another solution would be good as well, for example an alert if the mq2 value greater than X.

    Thank you in advance!
    T.



  • Hi @Tommas
    A new try. In your definition of the item airq01 you have in the channel="mysensors:airquality..." written "q" in lowercase letter.
    When I look in MySensors Binding in Paper UI it is written with a capital "Q", "airQuality". I don't know if it matters.



  • @MagnusF

    YESS! It was the problem :+1:

    Thank you very much!!


Log in to reply
 

Looks like your connection to MySensors Forum was lost, please wait while we try to reconnect.