In the previous tutorial, features, advantages and limitations of TCP/IP Protocol were discussed. Though, TCP/IP is not best suited for IoT applications due to packet overheads, still being the most common protocol stack on internet, it offer ubiquitous connectivity. An IoT device can be made to communicate with a cloud or server using TCP/IP protocol without any hassle of network programming and network administration. In this project, an IoT device will be designed that could transmit sensor data to ThingSpeak Platform using the TCP/IP protocol.
The IoT device designed in this project is built using Arduino UNO. The Arduino is just a microcontroller board and cannot connect to an internet network on its own. For internet connectivity, the Arduino UNO is interfaced with ESP8266 module. The ESP8266 Wi-Fi Module is a self contained SOC with integrated TCP/IP protocol stack that can access to a Wi-Fi network. The ESP module allows the Arduino board to connect with a router and access internet network. The Arduino is programmed to communicate with the cloud platform i.e. ThingSpeak over TCP/IP protocol. The Arduino can implement TCP/IP protocol by passing AT commands serially to the ESP8266 module.
The IoT device designed is a visitor counter as well as temperature and humidity monitor. For working as visitor counter, the IR sensors and Photodiodes are interfaced with the Arduino board. For working as temperature and humidity monitor, a DHT-11 sensor is interfaced with the Arduino board. The Arduino reads data from the sensors and send it to the ThingSpeak platform. A 0.6 inch 128 X 64 OLED is also interfaced with the Arduino which receives serial data from the board on I2C protocol and display the current temperature and humidity readings. The user can monitor the number of occupants in the house, temperature and humidity values from anywhere by accessing the ThingSpeak platform.
The Arduino board controls all the functionalities of the IoT device like counting visitors, reading temperature and humidity values from DHT-11 sensor, displaying temperature and humidity data on OLED, implementing TCP/IP protocol, connecting with ThingSpeak platform and sending data to the cloud server. For this, the Arduino code is written and compiled using Arduino IDE.
Components Required –
Fig. 1: List of components required for TCP/IP based IoT Communication with Thingspeak Server
Software Required –
• ThingSpeak server
• Arduino IDE
Block Diagram –
Fig. 2: Block Diagram of TCP/IP based IoT Communication between Arduino and Thingspeak Server
Circuit Connections –
The IoT device that communicates with the ThingSpeak Cloud is built on Arduino UNO. The DHT-11 Sensor, IR sensor, Photodiodes, ESP8266 module and OLED module are interfaced with the Arduino board to make the IoT device.
ESP8266 based TCP-IP Connected ThingSpeak Arduino Temperature Monitor Circuit
The IoT device has the following circuit connections –
Arduino UNO – Arduino UNO is one of the most popular prototyping boards. It is an Atmega 328 based controller board which has 14 GPIO pins, 6 PWM pins, 6 Analog inputs and on board UART, SPI and TWI interfaces. The Atmega 328 is the sitting MCU on the Arduino board. The controller has the following pin configuration –
Fig. 3: Table listing pin configuration of Arduino Uno
There are two GPIO pins (external interrupt pins INT0 and INT1) of Arduino board used to interface photodiodes, TX and RX pins (pins 3 and 2 respectively)are used interface ESP module, SDA and SCL (pins 27 and 28 respectively) pins used to interface the OLED module.
OLED Module – The OLED module is used to display the temperature and humidity information as well as the count of the visitors (occupants) in the house. The module communicates with the Arduino board using I2C protocol. This is a two wire protocol. The module has four pins – SDA, SCL, VCC and GND. The VCC and Ground are connected to 5V DC and common ground respectively. The 5V DC can be supplied through a battery via 7805 voltage regulator IC. The SDA and SCL pins of the OLED module are connected to the SDA and SCL pins ((pins 27 and 28 respectively) of the Arduino board. The OLED are made up of carbon based organic materials. So unlike LCD displays, they do not require backlight and filters.
Fig. 4: Image showing initial messages flashed on OLED Display
ESP8266 Module – The ESP8266 Wi-Fi Module is a self contained SOC with integrated TCP/IP protocol stack that can access to a Wi-Fi network. The ESP8266 is capable of either hosting an application or off loading all Wi-Fi networking functions from another application processor. Each ESP8266 module comes pre-programmed with an AT command set firmware. The module comes available in two models – ESP-01 and ESP-12. ESP-12 has 16 pins available for interfacing while ESP-01 has only 8 pins available for use. The ESP-12 has the following pin configuration –
Fig. 5: Table listing pin configuration of ESP8266 ESP-12 Module
The ESP-01 model is used in the project. The ESP-01 model has the following pin configuration –
Fig. 6: Table listing pin configuration of ESP8266 ESP-01 Module
The Chip Enable and VCC pins of the module are connected to the 3.3 V DC while Ground pin is connected to the common ground. The chip enable pin is connected to VCC via a 10K pull up resistor. The RESET pin is left not connected. The Tx and Rx pins of the module are connected to the RX and TX pins of the Arduino UNO. The GPIO-0 pin of the module is connected to VCC through a 10K pull up resistor.
The ESP module allows Arduino to access the internet by connecting to a router through Wi-Fi.
Fig. 7: Typical Image of ESP8266 ESP-01 Wi-Fi Modem
IR Sensors – An array of two IR LEDs is used in the circuit to detect entrance of any visitor. These IR LEDs are installed at the entrance of the house. An IR LED is a type of LED which emits light in the Infra-Red frequency range. The infra-red radiations are not visible to the human eye but can be seen by the lenses of a camera. Operationally, IR LEDs are not much different from normal LEDs. They also need a 3V DC for biasing and consume 20 mA current. They also need to be connected with pull-up resistor in a circuit. In the array, IR LEDs are connected with 220 ohm pull-up resistors.
Photodiodes – The photodiodes are used as IR receivers in the circuit. A photodiode is a type of diode which gets forward biased when light is incident on it. It has a high resistance when no light is falling on it. When the intensity of light incident on it increases, it starts getting forward biased and current starts flowing through it. So, when light is incident on it, its resistance decreases and there is less voltage drop across it. When light is not incident on it, its resistance increases and there is higher voltage drop across it. The photodiode looks exactly like an LED and may have a dark blue or black film on the outer casing. The photodiodes are used in reverse bias configuration in the circuit. An array of two photodiodes installed in line with IR transmitters is used in the circuit. The photodiodes are interfaced at external interrupt pins INT0 and INT1 of the Arduino board.
Fig. 8: Image of IR Transmitter and Photodiode Array used for counting visitors
DHT-11 Sensor – DHT-11 is a temperature and humidity sensor. The DHT11 sensor consists of two main components – one is Humidity sensing component and other is NTC temperature sensor (or Thermistor). The Thermistor is actually a variable resistor that changes its resistance with change in temperature. They both sense the temperature and humidity of area and give the output to the IC (which is placed on back side of sensor). The sensor has four pins – VCC, Ground, data Out and NC. The VCC and Ground pins are connected to the common VCC and Ground respectively. The Data Out pin of the sensor is connected to PD7 pin of the Arduino board via 10K pull-up resistor.
Fig. 9: Pin Diagram of DHT-11 Temperature and Humidity Sensor
ThingSpeak Server – The ThingSpeak server is used to visualize the data received from the IoT device. The data is displayed in the form of graphs on the platform. The ThingSpeak generates the read and write API key. The Write API key is used to write the data to the channel and read API channel is used to allow other people to view private channel feeds and charts. The data can also be saved on the platform for future reference.
In order to configure the ThingSpeak platform to access the data on it, first an account must be created on the platform. Then a channel must be created for the data on that account. It can be done by navigating to channel window and creating a new channel. The required information must be filled in the given form at the website so that the needed fields are created. For this project, there must be created three fields – Total Persons, Temperature and Humidity. These fields can then be checked live on the server. After saving the channel settings, a Write API key is generated which must be noted down. This Write API key is used in the firmware code of the Arduino to access the private channel created on the ThingSpeak account.
Fig. 10: Prototype of ESP8266 based TCP-IP Connected Thingspeak Arduino Visitor Counter
How the circuit works –
As the circuit is powered on the Arduino board starts reading data from the IR receivers and the DHT-11 sensor. The IR receivers are connected in series with variable resistors between VCC and ground in reverse bias configuration forming a voltage divider circuit. The output from the IR receivers (photodiodes) are drawn from the junction of cathode terminals of the IR receiver. Under normal conditions, the light emitted by the IR transmitters is continuously received by the photodiodes. This keeps the digital logic output of the photodiodes to HIGH. When a person enters the house, the light from the IR transmitters is blocked and the logical output from the photodiodes is switched to LOW. The IR receivers are connected at the external interrupt pins of the Arduino, so an interrupt is generated at the INT0 and INT1 pin of the Arduino when a person enters or exits the house. There are two pairs or IR transmitter and receiver used. The sequence in which the interrupts are generated at the INT0 and INT1 pins indicate whether a person has entered or exit from the house. Accordingly, the count of the current occupants of the house is increased or decreased.
The DHT11 Temperature and Humidity Sensor is a digital sensor with inbuilt capacitive humidity sensor and Thermistor. It relays a real-time temperature and humidity reading every 2 seconds. The sensor operates on 3.5 to 5.5 V supply and can read temperature between 0° C and 50° C and relative humidity between 20% and 95%. The DHT11 detects water vapors by measuring the electrical resistance between the two electrodes. The humidity sensing component is a moisture holding substrate with electrodes applied to the surface. When water vapors are absorbed by the substrate, ions are released by the substrate which increases the conductivity between the electrodes. The change in resistance between the two electrodes is proportional to the relative humidity. Higher relative humidity decreases the resistance between the electrodes, while lower relative humidity increases the resistance between the electrodes.
The DHT11 measures temperature with a surface mounted NTC temperature sensor (Thermistor) built into the unit. The DHT 11 Sensor sends data in the digital form to the Arduino board on one-wire protocol which must be implemented on firmware side. First the data pin is configured to input and a start signal is sent to it. The start signal comprises of a LOW for 18 milliseconds followed by a HIGH for 20 to 40 microseconds followed by a LOW again for 80 microseconds and a HIGH for 80 microseconds. After sending the start signal, the pin is configured to digital output and 40-bit data comprising of the temperature and humidity reading is latched out. Of the 5-byte data, the first two bytes are integer and decimal part of reading for relative humidity respectively, third and fourth bytes are integer and decimal part of reading for temperature and last one is checksum byte. The one-wire protocol is implemented on the firmware using an open-source library available for Arduino. The Arduino also connects with the Ethernet using an open-source library. The read temperature and humidity values along with the occupants number is displayed on the OLED module.
Fig. 11: Screenshot of Graph showing number of visitors on Thingspeak Server
The same data is passed to the ThingSpeak server every three seconds by accessing the server through Write API key. The data is passed over TCP/IP protocol by sending AT commands to the ESP module through serial communication. The data passed for all the three fields is updated every three seconds and is displayed in the form of graphs on the server. The visitor count is displayed as follow –
Fig. 11: Screenshot of Graph showing number of visitors on Thingspeak Server
Similarly, the temperature is displayed on server as follow –
Fig. 12: Screenshot of Graph showing temperature on Thingspeak Server
The humidity is also displayed graphically on the server as follow –
Fig. 13: Screenshot of Graph showing humidity on Thingspeak Server
Programming Guide –
The Arduino board is loaded with a sketch for counting visitors, reading temperature and humidity values from DHT-11 sensor, displaying temperature and humidity data on OLED, implementing TCP/IP protocol, connecting with ThingSpeak platform and sending data to the cloud server. The Arduino code loads a standard library for interfacing OLED module and DHT-11 sensor. The variables and objects are declared to store temperature, humidity and visitor count information.
The timer1_init() function is defined to initialize the timers. The OLED_Welcome_Message(void) is called to display initial messages n the OLED.
The Arduino use ESP module to connect with local network and so with the ThingSpeak server. The following code is used to initialize the connection with the Wi-Fi access point and to define the Write API key for accessing the ThingSpeak server.
//ESP866-01 WIFI Connection
#define SSID “Write your SSID” //”SSID-WiFiname”
#define PASS “password //”password”
#define IP “184.106.153.149” //thingspeak.com ip
String msg = “GET /update?key=Write_API_Key”; //API KEY of our channel
The connectWiFi() function is called to connect with the Wi-Fi access points. The AT commands – AT+CWMODE=1 is passed to the ESP module to set the Wi-Fi to station mode. The AT command – AT+CWJAP is passed to the ESP module to connect with the Wi-Fi access point.
After the connection is established with the local network and the ThingSpeak server, the Arduino reads data from the sensors. The PERSONIN() and PERSONOUT() functions are used to increment and decrement the visitor count. The Temperature_and_Humidity_Test() function is used to read temperature and humidity values from the DHT-11 sensor and format the information into a string. The Display_Data_on_OLED() function manages to display the data on the OLED module.
The update_Data_To_Server() function is called to update sensor data to the ThingSpeak server. In the function, the AT command – AT+CIPSTART is passed to the ESP module to start TCP connection and then AT command – AT+CIPSEND is passed to send data to the server. The TCP connection is closed by passing the AT command – AT+CIPCLOSE to the ESP module.
Check out the complete Arduino sketch from the code section for better understanding.
In the next tutorial, the UDP Protocol will be discussed.
You may also like:
Project Source Code
### //Program to /* * File Name - IR_based_Visitor_counter_and_DHT11_test.ino * Created: 2/14/2017 11:02:11 AM * Main Source Code for IR based Visior couter and DHT11 test * Tested on ATmega328 based Arduino board running on Internal Oscillator at 16MHz */ /* * Input/Output Pins of the Arduino Baord *A5 - OLED SCL pin *A4 - OLED SDA pin *Tx - ESP8266-01 Rx *Rx - ESP8266-01 Tx *D2 - IR1 (PERSONIN) output *D3 - IR2 (PERSONOUT) output *D7 - DHT11 output (pin2) */ //Universal graphic Library for Oled(128x64) Dispaly #include "U8glib.h" //DHT11 or DHT22 Temperature sensor Library #include "DHT.h" //Setup u8g object U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE|U8G_I2C_OPT_DEV_0); //Declare all global variables const int PersonIn = 2; //Variable to hold Incoming Entry of person const int PersonOut = 3; //Variable to hold Outgoing Entry of person volatile unsigned int count = 0; //Variable to hold the count value int temperature; //Variable to hold Temperature int humidity; //Variable to hold Humidity String tempC; //Variable to hold the character value char str[10]; //Array Initialization to hold the String // DHT11 or DHT22 pin and Type declaration #define DHTPIN 7 //DHT11 ouptput connected to Digital Pin 7 #define DHTTYPE DHT11 //DHT TYPE-DHT 11 or 22 DHT dht(DHTPIN, DHTTYPE); //DHTPIN and TYPE declaration //ESP866-01 WIFI CONNECTION #define SSID "NOT UR WIFI" //"SSID-WiFiname" #define PASS "marketing" //"password" #define IP "184.106.153.149" //thingspeak.com ip String msg = "GET /update?key=03JHV63FG27FYL3R"; //API KEY of our channnel //Initialise the variable in setup Function void setup() { Serial.begin(115200); //Initialise Serial communication at 115200 bps Serial.println("AT"); //When baud rate matches, Print AT on Serial Monitor delay(5000); //Condition to check Whether Serial finds Ok response from ESP8266 or not //If It finds Ok response the call the connectWifi() Function if(Serial.find("OK")) { connectWiFi(); } pinMode(PersonIn, INPUT); //Initialise the Digital Pin-2 as Input pinMode(PersonOut, INPUT); //Initialise the Digital Pin-3 as Input attachInterrupt(digitalPinToInterrupt (2), PERSONIN, FALLING); //Attach Interrupt handler for D2 attachInterrupt(digitalPinToInterrupt (3), PERSONOUT, FALLING); //Attach interrupt handler for D3 //Initialize Timer1 Function timer1_init(); //Display Welcome messgage on OLED OLED_Welcome_Message(); } //Loop function void loop() { // check whether the flag bit is set // if set, it means that there has been a compare match // and the timer has been cleared // use this opportunity to update the data on OLED and Thingspeak if (TIFR1 & (1 << OCF1A)) { //Get the temperature and Humidity value from DHT11 Sensor Temperature_and_Humidity_Test(); //Update the Temperature, Humidity and Total Person on Server(Thingspeak) update_Data_To_Server(); //Display the Temperature, Humidity and Total Person on OLED Display_Data_on_OLED(); } // wait! we have one more thing to do // clear the flag bit manually since there is no ISR to execute // clear it by writing '1' to it (as per the datasheet) TIFR1 |= (1 << OCF1A); } /* * Function Name - OLED_Welcome_messgage * To diplay the text when OLED starts * Input Paraameter - void * Return - void */ void OLED_Welcome_Message(void) { u8g_uint_t x = 0; u8g_uint_t y = 20; const char *s = "VISIOR COUNTER!"; //Draw the string "VISITOR COUNTER!" on OLED with given reference points u8g.firstPage(); do { u8g.setFont(u8g_font_unifont); u8g.drawStr( x, y,s ); } while( u8g.nextPage() ); } /* * External Interrupt Function INT0- PERSONIN * To count the person coming in the room */ void PERSONIN() { count++; } /* * External Interrupt Function INT1- PERSONOUT() * To count the person coming out of the room */ void PERSONOUT() { count--; if (count <= 0) count = 0; } /* *Function Name - Temperature_and_Humidity_Test() *Read the Temperature and Humidity value from DHT sensor */ void Temperature_and_Humidity_Test() { //Read the Temperature and Humidity from DHT sensor temperature = dht.readTemperature(); humidity = dht.readHumidity(); char buffer[10]; //There is a useful c function called dtostrf() which will convert a float to a char array so it can then be printed easily. //The format is: dtostrf(floatvar, StringLengthIncDecimalPoint, numVarsAfterDecimal, charbuf); tempC = dtostrf(temperature, 4, 1, buffer); } /* *Function Name= Display_Data_on_OLED() *To display the data on OLED with paticular format */ void Display_Data_on_OLED() { //To Display on OLED u8g.firstPage(); do { //Set the font of display u8g.setFont(u8g_font_helvB08); //Draw the string "Total Person" with specified reference points(x,y) u8g.drawStr( 0, 15, "TOTAL Person:"); //set the count value to OLED specied points u8g.drawStr( 80, 15, dtostrf(count, 5, 2, str)); //Draw the string "Humidity" with specified reference points(x,y) u8g.drawStr( 0, 30, "Humidity:"); //set the Humidity value to OLED specied points u8g.drawStr( 80, 30, dtostrf(humidity, 5, 2, str)); u8g.drawStr( 120, 30, "%"); //Draw the string "Temperature" with specified reference points(x,y) u8g.drawStr( 0, 45, "Temperature:"); //set the Temperature value to OLED specied points u8g.drawStr( 80, 45, dtostrf(temperature, 5, 2, str)); u8g.drawStr( 120, 45, "260C"); } while( u8g.nextPage() ); } /* * Function Name- update_Data_To_Server() * Establish TCP connection and send the updated Data to Server(Thingspeak) */ void update_Data_To_Server() { //Specify which connection channel you wish to connect on ( 0 - 4 ), //the protocol type (TCP/UDP),the IP address (or domain if you have DNS access) //and the port number using the CIPSTART command: String cmd = "AT+CIPSTART="TCP",""; cmd += IP; cmd += "",80"; Serial.println(cmd); if(Serial.find("Error")) { return; } cmd = msg ; cmd += "&field1="; //Creates field1 for Total Person in the Room cmd += String(count); //Upload count data to thingspeak cmd += "&field2="; //Creates field2 for Temperature cmd += tempC; //Upload Temperature data to Thingspeak cmd += "&field3="; //Creates field3 for Humidity cmd += String(humidity); //Upload Humidity data to Thingpeak cmd += "rnrn"; //Send Data Length Serial.print("AT+CIPSEND="); Serial.println(cmd.length()); //If Everything works ok, then we get ">" if(Serial.find(">")) { //Serial monitor prints the Get command with the API key and fields speacified Serial.print(cmd); } else { //close the TCP connection Serial.println("AT+CIPCLOSE"); Temperature_and_Humidity_Test(); count; } } /* *Function Name- connectWifi() *It establishes the connection between the ESP8266 and Wifi *Input paramerter-void *Return type- boolean */ boolean connectWiFi() { //Enable the module to act as both Station and an access point Serial.println("AT+CWMODE=1"); delay(2000); //Join the WIFI access point String cmd="AT+CWJAP=""; cmd+=SSID; cmd+="",""; cmd+=PASS; cmd+="""; //Print the Wifi SSID and Password on Serial monitor Serial.println(cmd); delay(5000); if(Serial.find("OK")) { return true; } else { return false; } } /* *Function Name- timer1_init() Timer1(16bit) creates the delay time period in order to display the data on OLED and Server(Thingpeak) */ void timer1_init() { //Initialize registers TCCR1A = 0; //set entire TCCR1A register to 0 TCCR1B = 0; //set entire TCCR1B register to 0 //Initialize counter TCNT1 = 0; // Set the Compare value equal to count_value_for_Delay_time that // was calculated for generating a Delay Time period // This updates the temperature, Humidity and Total person after every Delay Time Period OCR1A = 46874; //Start timer1 //Set up timer with prescaler = 1024 and CTC mode TCCR1B |= (1 << WGM12)|(1 << CS12)|(1 << CS10); } ###
Project Video
Filed Under: Arduino Projects, Electronic Projects, ESP8266
Filed Under: Arduino Projects, Electronic Projects, ESP8266
Questions related to this article?
👉Ask and discuss on EDAboard.com and Electro-Tech-Online.com forums.
Tell Us What You Think!!
You must be logged in to post a comment.