Saturday, 2 May 2020

IoT weather station program description

Summary:-

The previous blog discussed about the planned circuit and how the individual sensors work. Now let's see how the IoT feature operates. 

First step was, testing individual sensor with arduino pro mini. One by one I tested all the sensors starting with DHT 11 (for temp and humidity), wind speed circuit, MQ7 (for CO level), then finally wind direction circuit. All the individual sensors worked perfectly with the arduino. 

Now the next step was to combine all the individual sensor circuits into one circuit and replace arduino with ESP 32 . The same thing needed to be done with the individual codes that worked for the individual sensors. 

Even though the ESP 32 is compatible with the arduino IDE. The program that runs on arduino pro mini needs to be modified, in order to work with ESP 32. The baud rate must be changed from 9600 to 115200. Also the pin no's has to be changed according to the ESP 32 pin diagram. If we are using the on board Wi-Fi then it will disable the some of the ADC pins, we can only use pin 32 to 39 for ADC.

Some components that didn't worked as expected were removed from the circuit. Below given is the Modified circuit diagram for the project:- 

         

About IoT platform :-

This project uses IBM watson IoT platform. It uses MQTT protocol to send the data from client to  server. It works on publish - subscribe model. The users need to subscribe to the topic. The messages published on that topic can be accessed by the user. 

For making the ESP 32 to communicate with the IBM watson IoT platform and send temperature and humidity data , click on the link below and follow the steps given in the link. 

https://iotdesignpro.com/projects/how-to-connect-esp32-with-ibm-watson-cloud-platform

Once the account is created on the IoT platform. We can sign in and create our own data visuals by adding  graph,  pi chart, bar graph , gauge, etc.

Project images:-

Practical setup on breadboard

IBM watson IoT platform showing temp, humidity, wind speed and co level on guage and line graph.
Changed layout shows wind direction in left , 315 is north-west.

Project code and description:-

The code given the above mentioned link is only for temperature and humidity. Therefore it contains only 2 topics and 2 payload. To add more parameters like carbon monoxide level, wind speed and wind direction we need to combine their individual sensor codes by calling functions . Also we need to add more topics  and payloads. These payloads are string payloads that contain the device ID , device name and the value of parameter. This information is very important for the data to reach the right location.

Project program:-

#include <WiFi.h>

#include <WiFiClient.h>

#include <PubSubClient.h> 

#include "DHT.h"

float RS_gas = 0;     //variables for CO level//
float ratio = 0;
float sensorValue = 0;
float sensor_volt = 0;
float R0 =4500.0;
int apin=32; 


int sensorpin=15;    //variables for wind speed//
int a=0;
int lsta;
int b=0;
int lstb;
int c=0;
int s=0;
float m=0;
int h=0;
int k=0;
unsigned int e=0;
void count();
float windspeed();

int dpin=21;       //variables for wind direction//
int dpinst=0;
int led[]={5,18,19};
byte x=0b00000000; 
int i=0;
int windirection();
int directn[]={0,315,270,225,180,135,90,45};

#define DHTPIN 4 
#define DHTTYPE DHT11
#define ORG "5zg8eg" 
#define DEVICE_TYPE "ESP32" 
#define DEVICE_ID "F4FD8CE350CC" 
#define TOKEN "FU0sof*@G0*ju(e5OC" 

const char* ssid = "prachet hire";
const char* password = "helloiit";

char server[] = ORG ".messaging.internetofthings.ibmcloud.com";
char pubTopic1[] = "iot-2/evt/status1/fmt/json";
char pubTopic2[] = "iot-2/evt/status2/fmt/json";
char pubTopic3[] = "iot-2/evt/status3/fmt/json";
char pubTopic4[] = "iot-2/evt/status4/fmt/json";
char pubTopic5[] = "iot-2/evt/status5/fmt/json";
char authMethod[] = "use-token-auth";
char clientId[] = "d:" ORG ":" DEVICE_TYPE ":" DEVICE_ID;

WiFiClient wifiClient;
PubSubClient client(server, 1883, NULL, wifiClient);
DHT dht(DHTPIN, DHTTYPE);

void setup() {
   Serial.begin(115200);
   pinMode(sensorpin,INPUT); // wind speed hall sensor//
   pinMode(dpin,INPUT);
   pinMode(5,OUTPUT);
   pinMode(18,OUTPUT);
   pinMode(19,OUTPUT);
   
    dht.begin();
    Serial.println();
    Serial.print("Connecting to "); 
    Serial.print(ssid);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    } 
    Serial.println("");
    
    Serial.print("WiFi connected, IP address: "); 
    Serial.println(WiFi.localIP());

    if (!client.connected()) {
        Serial.print("Reconnecting client to ");
        Serial.println(server);
        while (!client.connect(clientId, authMethod, TOKEN)) {
            Serial.print(".");
            delay(500);
        }
        Serial.println("Bluemix connected");
    }
         
}

long lastMsg = 0;
void loop() {
          
    client.loop();
    long now = millis();
    if (now - lastMsg > 1000) {
       lastMsg = now;              
         
        
         float humidity = dht.readHumidity();
         float temperature = dht.readTemperature();

         sensorValue = analogRead(apin);
         sensor_volt = sensorValue/4095*3.3;
         RS_gas = (3.3-sensor_volt)/sensor_volt;
         ratio = RS_gas/R0; //Replace R0 with the value found using the sketch above
         float x = 1538.46 * ratio;
         float ppm = pow(x,-1.709);

         float ws = windspeed();
         int wd = windirection();
         
       String payload = "{\"d\":{\"Name\":\"" DEVICE_ID "\"";
              payload += ",\"co level\":";
              payload += ppm;
              payload += "}}";
       
        Serial.print("Sending payload: ");
        Serial.println(payload);

        if (client.publish(pubTopic1, (char*) payload.c_str())) {
            Serial.println("Publish ok");
        } else {
            Serial.println("Publish failed");
        }
        
        String payload1 = "{\"d\":{\"Name\":\"" DEVICE_ID "\"";
              payload1 += ",\"temperature\":";
              payload1 += temperature;
              payload1 += "}}";

        Serial.print("Sending payload1: ");
        Serial.println(payload1);      
       
         if (client.publish(pubTopic2, (char*) payload1.c_str())) {
            Serial.println("Publish ok");
        } else {
            Serial.println("Publish failed");
        }

        String payload2 = "{\"d\":{\"Name\":\"" DEVICE_ID "\"";
              payload2 += ",\"humidity\":";
              payload2 += humidity;
              payload2 += "}}";

        Serial.print("Sending payload2: ");
        Serial.println(payload2);      
       
         if (client.publish(pubTopic3, (char*) payload2.c_str())) {
            Serial.println("Publish ok");
        } else {
            Serial.println("Publish failed");
        }

        String payload3 = "{\"d\":{\"Name\":\"" DEVICE_ID "\"";
              payload3 += ",\"wind speed\":";
              payload3 += ws;
              payload3 += "}}";

        Serial.print("Sending payload3: ");
        Serial.println(payload3);      
       
         if (client.publish(pubTopic4, (char*) payload3.c_str())) {
            Serial.println("Publish ok");
        } else {
            Serial.println("Publish failed");
        }

         String payload4 = "{\"d\":{\"Name\":\"" DEVICE_ID "\"";
              payload4 += ",\"wind direction\":";
              payload4 += wd;
              payload4 += "}}";

        Serial.print("Sending payload4: ");
        Serial.println(payload4);      
       
         if (client.publish(pubTopic5, (char*) payload4.c_str())) {
            Serial.println("Publish ok");
        } else {
            Serial.println("Publish failed");
        }
    }
}

float windspeed(){
  b=digitalRead(sensorpin); 
  
  if(b!=lstb){
  if(b==LOW ){
    s++;
    }
    }
    lstb=b; 

    if(s==1){
      for(e=0;e<=310;e++){

      delay(10);
      if(e>=0 & e<=300){
         count();
        }
      if(e>309){
        break;
        }
      if(e>300 & e<310){
        m=(c*0.18);
        
        }
      }}
      c=0;
      s=0;
      Serial.println(m);
      return m;
}

void count(){
  a=digitalRead(sensorpin);
  if(a!=lsta){
  if(a==LOW ){
    c++;
    }
    if(a==HIGH){
    c++;
    }
    }
    lsta=a; 
  
}

int windirection(){

  for(i=0;i<=3;i++){
    digitalWrite(led[i],HIGH);
    dpinst=digitalRead(dpin);
    bitWrite(x,i-1,dpinst);
    delay(100);
    digitalWrite(led[i],LOW);
  }
  
return directn[x];
}// code ends here




If you found this blog useful and want to support me, then you can donate me. The money you give will be used to make more advance electronics projects and setting up better lab.



Sunday, 26 April 2020

Anemometer, weather vane, CO2 level, temperature and humidity modules

This project aims at measuring the parameters related to weather and make that information available online with the help of cloud service. This weather station project measures five parameters namely, wind speed, wind direction, temperature, humidity and carbon monoxide level. Below given is the circuit diagram of the project.

The project is divided into five parts or blocks as follows:-

1. ESP32 block
2. DHT 11 temperature and humidity sensor module.
3. MQ7 carbon monoide gas sensor module. 
4. wind speed measurement using anemometer and its interfacing circuit.
5. wind direction using wind vane and its interfacing circuit.
6. IBM watson IoT platform.

ESP32:-

ESP 32 is a series of low cost, low power system on chip microcontrollers with integrated wi-fi and dual mode Bluetooth. The ESP 32 series employs a Tensilica Xtensa LX6 microprocessor in both dual core and single core variations and includes buitlt in antenna switches, RF balun, Power amplifier, low noise receive amplifier, filters, and power management modules. Esp 32 is designed for mobile, wearable electronics, and IoT applications.



Advance peripheral interface:-
• 34 × programmable GPIOs 
• 12-bit SAR ADC up to 18 channels 
• 2 × 8-bit DAC 
• 10 × touch sensors 
• 4 × SPI 
• 2 × I²S 
• 2 × I²C 
• 3 × UART 
• 1 host (SD/eMMC/SDIO) 
• 1 slave (SDIO/SPI) 
• Ethernet MAC interface with dedicated DMA and IEEE 1588 support 
• CAN 2.0 
• IR (TX/RX) 
• Motor PWM 
• LED PWM up to 16 channels 
• Hall sensor

Apart from advance integrated sensors and wireless communication systems. The ESP 32 DEV kit module can be programmed using the Arduino IDE which makes it easier for testing different codes and implementing new ideas.

DHT 11:-

DHT 11 is a module for getting temperature and humidity readings. It sends temperature and humidity data through a single data pin using digital signals. A microcontroller can be programmed to read the digital signals and get the temperature and humidity value. It has three pins , GND, data and VCC.

The digital output is calibrated. This means the readings of temperature and humidity that we will get are accurate according to standards set by laws of physics.

The temperature and humidity sensors include a resistive type humidity measurement component and an NTC temperature measurement component , and connects to a high performance 8 bit microcontroller offering excellent quality , fast response ,anti interference ability and cost effectiveness.  

Technical specifications:-

Communication process:-

  1. MCU sends out a start signal by pulling down the voltage for at least 18ms.
  2. MCU pulls up voltage and waits for DHT response (20us to 40us).
  3. DHT sends out response signal by pulling down voltage and keeps it for 80us.
  4. DHT pulls up voltage and keeps it for 80us.
  5. Data transmission starts.
After the data transmission starts. The data comprised of  bits 0's and 1's is transmitted by modulating the 'on time' of the signal. The 'off time' remains same (50us). For '0' the 'on time' is 26us to 28us. For '1' the 'on time' is 70us.

For data '0'
For data '1'

Data format:-

The total data comprising of temperature and humidity is of 40 bit. and is arranged in the following format.

8 bit integral data + 8 bit decimal RH data + 8 bit integral T data + 8 bit decimal T data + 8 bit check sum.

The 8 bit check sum is the addition of previous four 8 bit data.


MQ7 carbon monoxide gas sensor:-

The MQ7 module has got four pins out of which two are for power and ground . Other two are A0 (analog output) and D0 (digital output). In this project we are using the analog output (A0) pin because we have to determine the concentration of gas.  

The MQ-7 carbon monoxide is especially designed to be sensitive to carbon monoxide (CO) gas which is emitted by vehicles, factories,etc. Since this gas is considered toxic to humans, at certain levels concentration of CO is used to determine the air pollution in given area.

MQ7 carbon monoxide sensor detects 20 to 2000 ppm (parts per million) of CO in air here is sensitivity characteristic curve:-

The function of CO concentration is given by:-

f(x) = f0 ( (x/x0) ^ ( log(f1/f0) / log(x1/x0) )
  
From the graph, f1 = 0.25 , f0 = 0.065 , x1 = 10 , x0 = 100 , substituting these values in the above equation, we get:-

f(x) = 0.065 ((x/100) ^ ( log(0.25/0.065) / log(10/100) )
       = 0.065 (x ^ -0.585)

The relationship between concentration in ppm and Rs/R0 is now:-

(Rs/R0) = 0.00065 (ppm ^ -0.585)

solving for ppm:-

ppm = (1538.46 (Rs/R0)) ^ (-1.709)

Now we can use this equation to write a program for determining the concentration of carbon monoxide in ppm.

The MQ7 needs to be preheated before using it after a long time. To preheat the sensor coil , keep it on at 5V for about 90 min before running the program.

Wind speed measurement using anemometer and it's interfacing circuit:-


Hardware description:- 

The device used for measuring wind speed is a three cup anemometer. The wind pushes against the three cups and rotates the shaft. At the end of the shaft a magnet is attached. The magnet moves with the shaft. The magnet is detected by the detection circuit which uses a hall effect sensor. The detection circuit gives a trigger pulse each time the shaft complete one full rotation. If the number of pulses are counted for a fix time interval then we can determine the wind speed by using simple mathematics.

Circuit description:-

The interfacing circuit's job is to pass the pulses for a fixed time interval. This is achieved with the help of timmer IC 555 in monostable mode. The monostable multivibrator (MMV) is made to pull the output  'high' for a fixed time interval (T)  initially when its triggered by the pulse. In this project T = 3 sec ( It is given by formula T = 1.11*R*C ). The MMV must be such that it doesn't gets re-triggered by the pulse for next 3 sec and gets 'low' irrespective of the pulses at the input. This is only achieved by the IC 555 MMV. 



The ESP32 does the further job of counting the pulses and calculate the speed. The interfacing circuit just helps to simplify the code.  

Calculations:-

Given conditions:- 1. Radius of anemometer from center of the shaft to center of cup is 7.112 cm.
                               2. Therefore circumference (c) = 2*pi* r = 44.66 cm.
                               3.  Let the number of pulses counted in 3sec = pa.   

Solution:-  Speed = Distance/Time.

                  Distance (km) = pa * c = (pa * 44.66 cm) / ( 10 ^ 5 )

                  Time (hr) = 3 sec / 3600

                  Substituting distance (km) and time (hr) in eqaution of speed we get:-
                  
                  Speed = 0.012 * pa * 44.66

Now we can use the above speed equation in our program to get the speed from no of pulses counted.
if only one count is passed then the speed is 0.54 km/hr . This is the minimum speed that can be measured.

Wind vane and its interfacing circuit:-

wind vane is a simple device with a fin attached to a freely rotating shaft, which points to the direction of the wind. Just because of it's one side  has a larger surface area then the other side , it orients itself in such a way that it will always point in the direction of wind. Traditionally there is marking on a wind vane for north, south, east and west, directions. In this project, to convert  direction information into digital signals, a binary coded disc and a 3 bit scanner is used. The binary coded disc has 8 divisions this makes the wind vane to detect all the directions. see the below given image.    
This binary coded disc is attached to the vertical shaft of the wind vane. This disc rotates as the shaft rotates. A 3bit black and white scanner is placed just below the disc to scan the sector and decoded the binary data from which the direction is known. The scanner sequentially scans the surface and the serial data is read by the ESP 32. The image below shows the wind vane's construction diagram, scanner wiring and the binary coded disc.


The code and it's integration with the IoT platform used will be discussed in the next blog.


If you found this blog useful and want to support me, then you can donate me. The money you give will be used to make more advance electronics projects and setting up better lab.