Arduino to PC Commmunicaton over Ethernet Technology and MQTT Protocol

details

Description:

In this tutorial, the Ethernet technology will be used to connect an Arduino board over internet with a PC. The Arduino based IOT device and the PC will be setup to communicate using MQTT protocol  via HiveMQ Broker.

An IOT device based on Arduino will be designed in this project. The Arduino will be interfaced with an Arduino Ethernet Shield to connect with a router via Ethernet cable (Cat 5e). The Ethernet modem has TCP/IP stack in itself and MQTT protocol can be implemented over TCP/IP stack. So, an Ethernet modem is used to connect the device to the Internet. The Arduino board will also be interfaced a DHT-11 temperature and humidity sensor and an LED.

The Arduino device will communicate with a remote PC via MQTT broker. So, both the Arduino based device as well as the PC will act as MQTT Clients. The Arduino sketch will be written to read temperature information from the sensor and send it to the MQTT broker. A remote PC which is configured as another MQTT client will then receive the temperature readings and display them on the browser. It will also control the LED interfaced at the Arduino based IOT device by sending appropriate control commands over MQTT protocol. The PC connects with the broker using a chrome add-on – MQTTLens.

 

Components:

Arduino Uno

Arduino Ethernet Shield W5200

DHT sensor

LED

Resistor 220 ohm

Resistor 10k ohm.

Software Required –

• Arduino IDE
• HiveMQ broker
• MQTTlens (chrome addon)

Block Diagram:

104

Circuit Connection:

There is an Arduino based temperature monitor designed in this project. The IOT device has been designed by interfacing an Ethernet Shield, DHT-11 Temperature and Humidity sensor and an LED with the Arduino UNO.

105

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 board can communicate with the Arduino Ethernet Shield using the SPI interface. The Atmega 328 is the sitting MCU on the Arduino board.

The Arduino can be connected with the Ethernet shield by placing the Ethernet shield on the top of Arduino UNO or by connecting wires (wherever require!). The Ethernet shield is connected to the router (LAN) via Ethernet cable (Cat 5e). The Arduino is connected to the Ethernet shield as shown in the image below:

106

https://www.engineersgarage.com/Contributions/IoT-Communication-MQTT-Clients-HiveMQ-Broker

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 are sent as messages to the “current_temeprature” topic. The PC client receives messages on the topic and display the reading as message received.
The PC Client after connecting to the internet can publish messages on “Ethernet/LED_status” topic. The PC Client must be operated by a human. On the “Ethernet/LED_status” topic, either ‘on’ or ‘off’ message can be sent. If the message ON is published by the PC client, it will be received by the Arduino client and its firmware code interprets the message to switch on the LED light. If the message OFF is published by the PC client, it will be received by the Arduino client and its firmware code interprets the message to switch off the LED light.
#include<SPI.h>                                                             //include library for serial communication

#include<Ethernet.h>                                                        //include library for Ethernet communication

#include <PubSubClient.h>                                                   //include library for MQTT pub sub protocol

#include <DHT.h>                                                            //include library for Temperature sensor 


#define DHTPIN  7                                                            //DHT temperature sensor connected to pin 7

#define DHTTYPE DHT11                                                       //TYPE of DHT 11 or 22

DHT dht(DHTPIN, DHTTYPE);                                                   //Create the instance of DHT


#define ledPin 2                                                            //led connected to pin 2

char* tempC;                                                                //Variable to hold the temperature of the hall

char message_buffer[100];                                                   //initialize a buffer for incoming temperature values                                     


byte mac[]= {0x00, 0xAA, 0xBB, 0xCC, 0xDD, 0xEF};                           //MAC address of your unique Arduino device

IPAddress ip(192,168,1,111);                                                //IP address of the Arduin Etherent shield        

const char* mqtt_server = "broker.mqtt-dashboard.com";                      //The broker or server domain name


EthernetClient ethClient;                                                   //Create an Ethernet Client class to connect to the MQTT server.

PubSubClient client(ethClient);                                             //create the MQTT client objects  


int timer1_count = 46874;                                                  //Timer1-16 bit, Required time = 3 sec, F_CPU= 16MHz


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 that

   // was calculated for generating a Delay Time period 

   // This updates the temperature after every Delay Time Period

   OCR1A = timer1_count;

    

   //Start timer1                                                                                       

   //Set up timer with prescaler = 1024 and CTC mode

   TCCR1B |= (1 << WGM12)|(1 << CS12)|(1 << CS10);    

}



void setup() {

  

   pinMode(ledPin,OUTPUT);                                      //configure the led pin as OUTPUT

   Serial.begin(115200);                                        //Set the baudrate of ESP8266 to show the process on serial monitor

   Ethernet.begin(mac, ip);                                     //Start the Ethernet communication   

   dht.begin();                                                 //start the dht sensor to sense temperature


   timer1_init();                                              //Initialize the timer function

   

   //By setting server and messgae callback function, the client is ready to use 

   client.setServer(mqtt_server, 1883);

   client.setCallback(Received_Message);

}


/*

* Function name = Received_message

* Client receives the message and functions accordingly

* Input parameter = Topic, Payload and message length

* Output parameter = void

*/

void Received_Message(char* topic, byte* payload, unsigned int length) {

   Serial.print("Message arrived [");

   Serial.print(topic);

   Serial.print("] ");

   for (int i = 0; i < length; i++) {

    Serial.print((char)payload[i]);

  }

  

   // Handle the message we received 

   // Here, we are only looking at the characters of the received message (payload[0])

   // If it is on, turn the led will be on.

   // If it is off, turn the led will be off.

   if((char)payload[0] == 'o' && (char)payload[1] == 'n') //on

    digitalWrite(2,HIGH);

  else if((char)payload[0] == 'o' && (char)payload[1] == 'f' && (char)payload[2] == 'f') //off

    digitalWrite(2,LOW);

    

  Serial.println();

}


/*

* Function Name = Reconnect

* To establish the connection of Ethernet with MQTT broker 

* and Will publish and subsribe to the topic

*/

void reconnect() {

   // Loop until we're reconnected

   while (!client.connected()) {

    Serial.print("Attempting MQTT connection...");

     //Attempt to connect

     if (client.connect("ethClient")) {

      Serial.println("connected");

      //and resubscribe

      client.subscribe("Ethernet/LED_status");

    } 

  else {

      Serial.print("failed, rc=");

      Serial.print(client.state());

      Serial.println(" try again in 5 seconds");

      // Wait 5 seconds before retrying

      delay(5000);

    }

  }

}



void loop() {

  //When Ethernet client will be connected to the broker, 

  //then call the function reconnect and publish and subscribe the data from broker.

  if (!client.connected()) {

    reconnect();

  }

  client.loop();


   float tempF = dht.readTemperature();                   //Read the temperature from DHT sensor

   

   //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(tempF,5,2,message_buffer);

      

      // 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 publish the temperature value

      if(TIFR1 & (1 << OCF1A))

      {

      //publish the temperature value

      client.publish("current_temperature", tempC);

      }

      

      // wait! we are not done yet!

      // 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);

}

 

Demo:

 

 

 

 

Description:

In this tutorial, the Ethernet technology will be used to connect an Arduino board over internet with a PC. The Arduino based IOT device and the PC will be setup to communicate using MQTT protocol  via HiveMQ Broker.

An IOT device based on Arduino will be designed in this project. The Arduino will be interfaced with an Arduino Ethernet Shield to connect with a router via Ethernet cable (Cat 5e). The Ethernet modem has TCP/IP stack in itself and MQTT protocol can be implemented over TCP/IP stack. So, an Ethernet modem is used to connect the device to the Internet. The Arduino board will also be interfaced a DHT-11 temperature and humidity sensor and an LED.

The Arduino device will communicate with a remote PC via MQTT broker. So, both the Arduino based device as well as the PC will act as MQTT Clients. The Arduino sketch will be written to read temperature information from the sensor and send it to the MQTT broker. A remote PC which is configured as another MQTT client will then receive the temperature readings and display them on the browser. It will also control the LED interfaced at the Arduino based IOT device by sending appropriate control commands over MQTT protocol. The PC connects with the broker using a chrome add-on – MQTTLens.

 

Components:

Arduino Uno

Arduino Ethernet Shield W5200

DHT sensor

LED

Resistor 220 ohm

Resistor 10k ohm.

Software Required –

• Arduino IDE
• HiveMQ broker
• MQTTlens (chrome addon)

Block Diagram:

104

Circuit Connection:

There is an Arduino based temperature monitor designed in this project. The IOT device has been designed by interfacing an Ethernet Shield, DHT-11 Temperature and Humidity sensor and an LED with the Arduino UNO.

105

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 board can communicate with the Arduino Ethernet Shield using the SPI interface. The Atmega 328 is the sitting MCU on the Arduino board.

The Arduino can be connected with the Ethernet shield by placing the Ethernet shield on the top of Arduino UNO or by connecting wires (wherever require!). The Ethernet shield is connected to the router (LAN) via Ethernet cable (Cat 5e). The Arduino is connected to the Ethernet shield as shown in the image below:

106

https://www.engineersgarage.com/Contributions/IoT-Communication-MQTT-Clients-HiveMQ-Broker

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 are sent as messages to the “current_temeprature” topic. The PC client receives messages on the topic and display the reading as message received.
The PC Client after connecting to the internet can publish messages on “Ethernet/LED_status” topic. The PC Client must be operated by a human. On the “Ethernet/LED_status” topic, either ‘on’ or ‘off’ message can be sent. If the message ON is published by the PC client, it will be received by the Arduino client and its firmware code interprets the message to switch on the LED light. If the message OFF is published by the PC client, it will be received by the Arduino client and its firmware code interprets the message to switch off the LED light.
#include<SPI.h>                                                             //include library for serial communication

#include<Ethernet.h>                                                        //include library for Ethernet communication

#include <PubSubClient.h>                                                   //include library for MQTT pub sub protocol

#include <DHT.h>                                                            //include library for Temperature sensor 


#define DHTPIN  7                                                            //DHT temperature sensor connected to pin 7

#define DHTTYPE DHT11                                                       //TYPE of DHT 11 or 22

DHT dht(DHTPIN, DHTTYPE);                                                   //Create the instance of DHT


#define ledPin 2                                                            //led connected to pin 2

char* tempC;                                                                //Variable to hold the temperature of the hall

char message_buffer[100];                                                   //initialize a buffer for incoming temperature values                                     


byte mac[]= {0x00, 0xAA, 0xBB, 0xCC, 0xDD, 0xEF};                           //MAC address of your unique Arduino device

IPAddress ip(192,168,1,111);                                                //IP address of the Arduin Etherent shield        

const char* mqtt_server = "broker.mqtt-dashboard.com";                      //The broker or server domain name


EthernetClient ethClient;                                                   //Create an Ethernet Client class to connect to the MQTT server.

PubSubClient client(ethClient);                                             //create the MQTT client objects  


int timer1_count = 46874;                                                  //Timer1-16 bit, Required time = 3 sec, F_CPU= 16MHz


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 that

   // was calculated for generating a Delay Time period 

   // This updates the temperature after every Delay Time Period

   OCR1A = timer1_count;

    

   //Start timer1                                                                                       

   //Set up timer with prescaler = 1024 and CTC mode

   TCCR1B |= (1 << WGM12)|(1 << CS12)|(1 << CS10);    

}



void setup() {

  

   pinMode(ledPin,OUTPUT);                                      //configure the led pin as OUTPUT

   Serial.begin(115200);                                        //Set the baudrate of ESP8266 to show the process on serial monitor

   Ethernet.begin(mac, ip);                                     //Start the Ethernet communication   

   dht.begin();                                                 //start the dht sensor to sense temperature


   timer1_init();                                              //Initialize the timer function

   

   //By setting server and messgae callback function, the client is ready to use 

   client.setServer(mqtt_server, 1883);

   client.setCallback(Received_Message);

}


/*

* Function name = Received_message

* Client receives the message and functions accordingly

* Input parameter = Topic, Payload and message length

* Output parameter = void

*/

void Received_Message(char* topic, byte* payload, unsigned int length) {

   Serial.print("Message arrived [");

   Serial.print(topic);

   Serial.print("] ");

   for (int i = 0; i < length; i++) {

    Serial.print((char)payload[i]);

  }

  

   // Handle the message we received 

   // Here, we are only looking at the characters of the received message (payload[0])

   // If it is on, turn the led will be on.

   // If it is off, turn the led will be off.

   if((char)payload[0] == 'o' && (char)payload[1] == 'n') //on

    digitalWrite(2,HIGH);

  else if((char)payload[0] == 'o' && (char)payload[1] == 'f' && (char)payload[2] == 'f') //off

    digitalWrite(2,LOW);

    

  Serial.println();

}


/*

* Function Name = Reconnect

* To establish the connection of Ethernet with MQTT broker 

* and Will publish and subsribe to the topic

*/

void reconnect() {

   // Loop until we're reconnected

   while (!client.connected()) {

    Serial.print("Attempting MQTT connection...");

     //Attempt to connect

     if (client.connect("ethClient")) {

      Serial.println("connected");

      //and resubscribe

      client.subscribe("Ethernet/LED_status");

    } 

  else {

      Serial.print("failed, rc=");

      Serial.print(client.state());

      Serial.println(" try again in 5 seconds");

      // Wait 5 seconds before retrying

      delay(5000);

    }

  }

}



void loop() {

  //When Ethernet client will be connected to the broker, 

  //then call the function reconnect and publish and subscribe the data from broker.

  if (!client.connected()) {

    reconnect();

  }

  client.loop();


   float tempF = dht.readTemperature();                   //Read the temperature from DHT sensor

   

   //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(tempF,5,2,message_buffer);

      

      // 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 publish the temperature value

      if(TIFR1 & (1 << OCF1A))

      {

      //publish the temperature value

      client.publish("current_temperature", tempC);

      }

      

      // wait! we are not done yet!

      // 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);

}

 

Demo:

 

 

 

 

COMMENTS

Please Login to comment
  Subscribe  
Notify of