Example for sending TMP36 sensor data to Cayenne using an X-NUCLEO-IDW01M1 WiFi expansion board.

Dependencies:   LDR_sensor Cayenne-MQTT-mbed mbed X_NUCLEO_IDW01M1v2 NetworkSocketAPI moisture_sensor Pir_sensor TMP36 lib_dht22 millis

Revision:
6:b9c029e61e71
Parent:
5:294a8b1bca28
--- a/main.cpp	Fri Nov 11 18:31:11 2016 +0000
+++ b/main.cpp	Sun Apr 21 03:33:11 2019 +0000
@@ -2,32 +2,63 @@
 * Example app for using the Cayenne MQTT mbed library to send data from a TMP36 sensor. This example uses
 * the X-NUCLEO-IDW01M1 WiFi expansion board via the X_NUCLEO_IDW01M1v2 library.
 */
-
+#include "millis.h"
 #include "MQTTTimer.h"
 #include "CayenneMQTTClient.h"
 #include "MQTTNetworkIDW01M1.h"
 #include "SpwfInterface.h"
-#include "TMP36.h"
+
+#include "math.h"
+
+
 
+//#include "TMP36.h"
+//#include "DHT.h"
+#include "dht22.h"
+#include  "Pir_sensor.h"
+#include "moisture_sensor.h"
+#include "LDR_sensor.h"
+
+DHT22 dht22(D7);
+
+/*
+DHT sensor(D7,DHT22);
+void task_DHT();
+*/
+Serial  pc(USBTX, USBRX);
 // WiFi network info.
-char* ssid = "ssid";
-char* wifiPassword = "wifiPassword";
+char* ssid = "DIN1";
+char* wifiPassword = "sharif82";
 
 // Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
-char* username = "MQTT_USERNAME";
-char* password = "MQTT_PASSWORD";
-char* clientID = "CLIENT_ID";
+char* username = "59176890-3ee5-11e9-ad96-c15442ccb423";
+char* password = "2ba1e1d7467a27f966d41c53fef22f4ae3b986d3";
+char* clientID = "9c2293c0-4cc9-11e9-ba40-5d168a516101";
 
 SpwfSAInterface interface(D8, D2); // TX, RX
 MQTTNetwork<SpwfSAInterface> network(interface);
 CayenneMQTT::MQTTClient<MQTTNetwork<SpwfSAInterface>, MQTTTimer> mqttClient(network, username, password, clientID);
 
-DigitalOut led1(LED1);
-
+DigitalOut led2(PB_6);
+DigitalOut led1(PA_6);
+//DigitalIn Sensor1(PA_7);
+//InterruptIn button(PA_7);
 /**
 * Print the message info.
 * @param[in] message The message received from the Cayenne server.
 */
+
+double status=0;
+void pressed()
+{
+    status = 1 ;// 
+}
+
+void released()
+{
+    status = 0; // 
+}
+
 void outputMessage(CayenneMQTT::MessageData& message)
 {
     switch (message.topic)  {
@@ -62,23 +93,132 @@
     printf("\n");
 }
 
+//int previousState = -1;
+
+/*
+void checkSensor()
+{
+          int status = 0;
+           button.fall(&pressed);
+           button.rise(&released);
+       
+         printf("Publish sensor detection, status: %d\n",status);
+              
+}           
+
+*/
+int previousState = -1;
+int currentState = -1;
+unsigned long previousMillis = 0;
+
+/*
+void checkSensor()
+{
+  
+  unsigned long currentMillis = millis();
+  // Check sensor data every 250 milliseconds
+ while (currentMillis - previousMillis >= 1000) 
+ {
+  
+    pc.printf("millissensor = %d\r\n", millis());
+    // Check the sensor state and send data when it changes.
+  // currentState = Sensor1;
+    wait (0.5);
+    int error = 0;
+    if (Sensor1==1) 
+    { 
+     if ((error = mqttClient.publishData(DATA_TOPIC, 6, TYPE_TEMPERATURE, UNIT_CELSIUS, 1)) != CAYENNE_SUCCESS) 
+           {
+             printf("Publish temperature failed, error: %d\n", error);
+           }
+           led2 = 1;
+           wait (0.1);
+           
+    }
+        if ((error = mqttClient.publishData(DATA_TOPIC, 6, TYPE_TEMPERATURE, UNIT_CELSIUS , 0)) != CAYENNE_SUCCESS) 
+           {
+             printf("Publish temperature failed, error: %d\n", error);
+           }
+           led2 = 0;
+           previousMillis=currentMillis;
+  
+ 
+  
+}
+}
+*/
+
 /**
 * Handle messages received from the Cayenne server.
 * @param[in] message The message received from the Cayenne server.
 */
+/*
+void task_DHT()
+{
+    int error = 0;
+    int h, c,f;
+    float dp = 0.0f;
+ 
+        wait(2.0f);
+        error = sensor.readData();
+        if (0 == error) 
+        {
+            c   = sensor.ReadTemperature(CELCIUS);
+            f   = sensor.ReadTemperature(FARENHEIT);
+            h   = sensor.ReadHumidity();
+            dp  = sensor.CalcdewPoint(c, h);
+    
+            printf("Temperature in Celcius: %d, Farenheit %d\r\n", c, f);
+            printf("Humidity is %d, Dewpoint: %4.2f\r\n\n", h, dp);
+        } else {
+            printf("Error: %d\r\n", error);
+        }
+}
+
+*/
+
+void Read_DHT()
+
+{
+    DHT22_data_t dht22_data;
+    dht22.read(&dht22_data);
+    
+    float temperature = dht22_data.temp / 10.0f;
+    float humidity = dht22_data.humidity / 10.0f;
+        
+    pc.printf("Temperature: %2.2f    Humidity: %2.2f%%\r\n", temperature, humidity);
+    wait_ms(200);
+    return;
+}
+
+
+
 void messageArrived(CayenneMQTT::MessageData& message)
 {
     int error = 0;
     // Add code to process the message. Here we just ouput the message data.
     outputMessage(message);
 
-    if (message.topic == COMMAND_TOPIC) {
-        switch(message.channel) {
-        case 0:
+    if (message.topic == COMMAND_TOPIC) 
+    {
+        switch(message.channel) 
+        {
+        case 1:
             // Set the onboard LED state
             led1 = atoi(message.getValue());
             // Publish the updated LED state
-            if ((error = mqttClient.publishData(DATA_TOPIC, message.channel, NULL, NULL, message.getValue())) != CAYENNE_SUCCESS) {
+            if ((error = mqttClient.publishData(DATA_TOPIC, message.channel, NULL, NULL, message.getValue())) != CAYENNE_SUCCESS) 
+            {
+                printf("Publish LED state failure, error: %d\n", error);
+            }
+            break;
+        
+        case 2:
+            // Set the onboard LED state
+            led2 = atoi(message.getValue());
+            // Publish the updated LED state
+            if ((error = mqttClient.publishData(DATA_TOPIC, message.channel, NULL, NULL, message.getValue())) != CAYENNE_SUCCESS) 
+            {
                 printf("Publish LED state failure, error: %d\n", error);
             }
             break;
@@ -103,7 +243,7 @@
     printf("Connecting to %s:%d\n", CAYENNE_DOMAIN, CAYENNE_PORT);
     while ((error = network.connect(CAYENNE_DOMAIN, CAYENNE_PORT)) != 0) {
         printf("TCP connect failed, error: %d\n", error);
-        wait(2);
+        wait(10);
     }
 
     if ((error = mqttClient.connect()) != MQTT::SUCCESS) {
@@ -134,55 +274,187 @@
 */
 void loop(void)
 {
+
+   
     // Start the countdown timer for publishing data every 5 seconds. Change the timeout parameter to publish at a different interval.
-    MQTTTimer timer(5000);
-    TMP36 tmpSensor(A5);
+    MQTTTimer timer(1000);
+    double pow(unsigned int, unsigned int);
+   
     
-    while (true) {
+    Pir_sensor tmpSensor1(PA_7);
+    moisture_sensor tmpSensor2(PA_0);    //use A0 analog pin to received output from soil sensor
+    LDR_sensor tmpSensor3(PA_1);    //use A1 analog pin to received output from soil sensor
+ //   pc.printf("Reading Pir Sensor!! %d\r\n");
+    if (tmpSensor1.read() ==1)
+      
+    {  
+    wait (0.1);
+    }
+     led2 =0;
+     
+    wait (0.1);
+    
+    
+   
+    while (true) 
+    {
         // Yield to allow MQTT message processing.
-        mqttClient.yield(1000);
+        mqttClient.yield(10000);
 
         // Check that we are still connected, if not, reconnect.
-        if (!network.connected() || !mqttClient.connected()) {
-            network.disconnect();
+        if (!network.connected() || !mqttClient.connected()) 
+        {
+           // network.disconnect();
             mqttClient.disconnect();
             printf("Reconnecting\n");
-            while (connectClient() != CAYENNE_SUCCESS) {
+            while (connectClient() != CAYENNE_SUCCESS) 
+            {
                 wait(2);
                 printf("Reconnect failed, retrying\n");
             }
         }
+    
+ 
+    pc.printf("Reading ALL Sensor!! %d\r\n");
+   
+    
+//    Read_DHT();
+   DHT22_data_t dht22_data;
+   dht22.read(&dht22_data);
+    
+   float temperature = dht22_data.temp / 10.0f;
+   float humidity = dht22_data.humidity / 10.0f;
+   pc.printf("Temperature: %2.2f    Humidity: %2.2f%%\r\n", temperature, humidity);
+   wait_ms(10);
+   
+   //start to read soil sensor//
+    float meas_r=tmpSensor2.read();
+    float meas_v=meas_r * 3300;
+    float water_level=100*((3300-meas_v)/3300);
+    
+  
+    pc.printf("measure = %f = %.0f mV\r\n", meas_r, meas_v);
+    pc.printf("Water level ratio = %.0f %\r\n", water_level);
+   //end read soil sensor//
+
+   
+    //start to LDR sensor//
+    float meas_r1;
+    float meas_v1;
+    double   Rest;
+    float LDRvolt;
+    float ldrLux;
+    meas_r1=tmpSensor3.read();
+   
+    meas_v1=meas_r1 * 3300;
+    
+    LDRvolt=3300-meas_v1;
+    Rest=(LDRvolt/1000)/(3.3/10000);
+   //ldrLux = pow(Rest,4.47687);
+ 
+    pc.printf("LDR Voltage: %2.2f\r\n",LDRvolt);
+    pc.printf("LDR Resistance : %2.2f\r\n",Rest);
+   //end read LDR sensor//  
+   
+
+   
+   
+   
+    if (tmpSensor1.read() ==1)
+      
+    { led2 =1; 
+    wait (0.1);
+    }
+     led2 =0;
+     
+   // wait (0.5);
+    
+
 
         // Publish some example data every few seconds. This should be changed to send your actual data to Cayenne.
-        if (timer.expired()) {
+        if (timer.expired()) 
+        {
             int error = 0;
-            if ((error = mqttClient.publishData(DATA_TOPIC, 5, TYPE_TEMPERATURE, UNIT_CELSIUS, tmpSensor.read())) != CAYENNE_SUCCESS) {
+            /*if ((error = mqttClient.publishData(DATA_TOPIC, 5, TYPE_TEMPERATURE, UNIT_CELSIUS, tmpSensor.read())) != CAYENNE_SUCCESS) 
+            {
                 printf("Publish temperature failed, error: %d\n", error);
             }
-            // Restart the countdown timer for publishing data every 5 seconds. Change the timeout parameter to publish at a different interval.
+             */
+             
+             if ((error = mqttClient.publishData(DATA_TOPIC, 7, TYPE_VOLTAGE, UNIT_MILLIVOLTS, LDRvolt)) != CAYENNE_SUCCESS) 
+            {
+              printf("Publish temperature failed, error: %d\n", error);
+            } 
+             
+             if ((error = mqttClient.publishData(DATA_TOPIC, 6, TYPE_TEMPERATURE, UNIT_DIGITAL, tmpSensor1.read())) != CAYENNE_SUCCESS) 
+            {
+              printf("Publish temperature failed, error: %d\n", error);
+            }
+       
+            
+             if ((error = mqttClient.publishData(DATA_TOPIC, 5, TYPE_TEMPERATURE, UNIT_CELSIUS, temperature)) != CAYENNE_SUCCESS) 
+            {
+                printf("Publish temperature failed, error: %d\n", error);
+            }
+              if ((error = mqttClient.publishData(DATA_TOPIC, 4, TYPE_VOLTAGE, UNIT_PERCENT, humidity)) != CAYENNE_SUCCESS) 
+            {
+                printf("Publish temperature failed, error: %d\n", error);
+            }
+            
+             if ((error = mqttClient.publishData(DATA_TOPIC, 3, TYPE_VOLTAGE, UNIT_PERCENT, water_level)) != CAYENNE_SUCCESS) 
+            {
+                printf("Publish temperature failed, error: %d\n", error);
+            }
+            
             timer.countdown_ms(5000);
+            //led2=0;
         }
+        
+       
     }
 }
 
 /**
 * Main function.
 */
+
+
 int main()
-{   
+{   millisStart();        
+ 
+
+    //led2 = 1;
     // Initialize the network interface.
     printf("Initializing interface\n");
     interface.connect(ssid, wifiPassword, NSAPI_SECURITY_WPA2);
 
+
+   
     // Set the default function that receives Cayenne messages.
     mqttClient.setDefaultMessageHandler(messageArrived);
 
     // Connect to Cayenne.
-    if (connectClient() == CAYENNE_SUCCESS) {
+    if (connectClient() == CAYENNE_SUCCESS) 
+    {
+        
+    //while(1)
+    //{
         // Run main loop.
+        
+     //       button.fall(&pressed);
+      //      button.rise(&released);
+       //  led2 = 1;
+      //  checkSensor();
+      //  led2 = 0;
         loop();
-    }
-    else {
+    //  checkSensor();
+   //   pc.printf("millis = %d\r\n", millis());
+   // }
+    // Assign functions to button
+     }
+    
+    else 
+    {
         printf("Connection failed, exiting\n");
     }