You are on page 1of 22

SAGAR INSTITUTE OF RESEARCH

& TECHNOLOGY, BHOPAL (M.P)

LAB MANUAL
Subject Code: CE-705
Sub Name: IOT Lab
Semester: 7th
Department: Civil Engineering
Session: July – Dec 2022

Submitted by: Submitted to:


ANISHU KUMAR Prof. Ruchi Dorawat
Enroll.No.:- 0133CE191014
RAJIV GANDHI PROUDYOGIKI VISHWAVIDYALAYA, BHOPAL

New Scheme Based On AICTE Flexible Curriculum

Civil Engineering, VII-Semester

CE705- IOT Lab

List of Experiments

1. Study and Install IDE of Arduino and different types of Arduino.

2. Write program using Arduino IDE for Blink LED.

3. Write Program for RGB LED using Arduino.

4. Study the Temperature sensor and Write Program foe monitor temperature using Arduino.

5. Study and Implement RFID, NFC using Arduino.

6. Study and Configure Raspberry Pi.

7. WAP for LED blink using Raspberry Pi.

8. Study and Implement Zigbee Protocol using Arduino / Raspberry Pi.

9 . Study and implement MQTT protocol using Arduino.

10. Study and implement CoAP protocol using Arduino


Experiment 01
Study and Install IDE of Arduino and different types of Arduino.
Arduino – Installation
After learning about the main parts of the Arduino UNO board, we are ready to learn how to set up the Arduino IDE. Once we learn this, we will be ready to upload our
program on the Arduino board.

In this section, we will learn in easy steps, how to set up the Arduino IDE on our computer and prepare the board to receive the program via USB cable.

Step 1 − First you must have your Arduino board (you can choose your favorite board) and a USB cable. In case you use Arduino UNO, Arduino Duemilanove, Nano,
Arduino Mega 2560, or Diecimila, you will need a standard USB cable (A plug to B plug), the kind you would connect to a USB printer as shown in the following
image.

In case you use Arduino Nano, you will need an A to Mini-B cable instead as shown in the following image.

Step 2 − Download Arduino IDE Software.

You can get different versions of Arduino IDE from the Download page on the Arduino Official website. You must select your software, which is compatible with your
operating system (Windows, IOS, or Linux). After your file download is complete, unzip the file.

Step 3 − Power up your board.

The Arduino Uno, Mega, Duemilanove and Arduino Nano automatically draw power from either, the USB connection to the computer or an external power supply. If
you are using an Arduino Diecimila, you have to make sure that the board is configured to draw power from the USB connection. The power source is selected with a
jumper, a small piece of plastic that fits onto two of the three pins between the USB and power jacks. Check that it is on the two pins closest to the USB port.

Connect the Arduino board to your computer using the USB cable. The green power LED (labeled PWR) should glow.

Step 4 − Launch Arduino IDE.

After your Arduino IDE software is downloaded, you need to unzip the folder. Inside the folder, you can find the application icon with an infinity label
(application.exe). Double-click the icon to start the IDE.

Step 5 − Open your first project.

Once the software starts, you have two options −

 Create a new project.

 Open an existing project example.


To create a new project, select File → New.

To open an existing project example, select File → Example → Basics → Blink.

Here, we are selecting just one of the examples with the name Blink. It turns the LED on and off with some time delay. You can select any other example from the list.
Step 6 − Select your Arduino board.

To avoid any error while uploading your program to the board, you must select the correct Arduino board name, which matches with the board connected to your
computer.

Go to Tools → Board and select your board.

Here, we have selected Arduino Uno board according to our tutorial, but you must select the name matching the board that you are using.

Step 7 − Select your serial port.

Select the serial device of the Arduino board. Go to Tools → Serial Port menu. This is likely to be COM3 or higher (COM1 and COM2 are usually reserved for
hardware serial ports). To find out, you can disconnect your Arduino board and re-open the menu, the entry that disappears should be of the Arduino board. Reconnect
the board and select that serial port.

Step 8 − Upload the program to your board.

Before explaining how we can upload our program to the board, we must demonstrate the function of each symbol appearing in the Arduino IDE toolbar.

A − Used to check if there is any compilation error.

B − Used to upload a program to the Arduino board.

C − Shortcut used to create a new sketch.

D − Used to directly open one of the example sketch.

E − Used to save your sketch.

F − Serial monitor used to receive serial data from the board and send the serial data to the board.

Now, simply click the "Upload" button in the environment. Wait a few seconds; you will see the RX and TX LEDs on the board, flashing. If the upload is successful,
the message "Done uploading" will appear in the status bar.

Note − If you have an Arduino Mini, NG, or other board, you need to press the reset button physically on the board, immediately before clicking the upload button on
the Arduino Software.
Experiment 02
Write program using Arduino IDE for Blink LED.

LEDs are small, powerful lights that are used in many different applications. To start, we will work on blinking an LED, the Hello World of microcontrollers. It is as
simple as turning a light on and off. Establishing this important baseline will give you a solid foundation as we work towards experiments that are more complex.

Components Required :-

 1 × Breadboard

 1 × Arduino Uno R3

 1 × LED

 1 × 330Ω Resistor

 2 × Jumper

Procedure

Follow the circuit diagram and hook up the components on the breadboard as shown in the image given below.

Note − To find out the polarity of an LED, look at it closely. The shorter of the two legs, towards the flat edge of the bulb indicates the negative
terminal.

Components like resistors need to have their terminals bent into 90° angles in order to fit the breadboard sockets properly. You can also cut the
terminals shorter.
Sketch :- Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the new sketch File by
clicking New.

Arduino Code

*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.
*/

// the setup function runs once when you press reset or power the board

void setup() { // initialize digital pin 13 as an output.


pinMode(2, OUTPUT);
}

// the loop function runs over and over again forever

void loop() {
digitalWrite(2, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(2, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
Code to Note
pinMode(2, OUTPUT) − Before you can use one of Arduino’s pins, you need to tell Arduino Uno R3 whether it is an INPUT or OUTPUT. We use a built-in
“function” called pinMode() to do this.

digitalWrite(2, HIGH) − When you are using a pin as an OUTPUT, you can command it to be HIGH (output 5 volts), or LOW (output 0 volts).

Result :- You should see your LED turn on and off. If the required output is not seen, make sure you have assembled the circuit correctly, and verified and uploaded
the code to your board.
Experiment 3

Aim: Write a program for RGB LEDs using Arduino


RGB LEDs can be used to display a variety of colors without the need to wire multiple different colored LEDs at once.

Materials List

 Breadboard
 RGB LED
 Four Jumper wires (red, green, blue, black)
 Three 220 OHM resistors
 Arduino Uno
 USB Cable

RGB LED Wiring Diagram for Arduino

We can use the wiring diagram to connect the RGB LED to our breadboard. First, place the LED on the breadboard so that all four pins are
in different numbered columns.

Most LEDs have a polarity. This one has a common cathode configuration, which means we’re going to be plugging the longer leg into the
ground. Then we’ll connect the remaining legs from left to right (red, ground, blue, green). Double-check your LEDs datasheet to ensure
you have the proper configuration.

Next, add the resistors to the breadboard. Each color pin needs its resistor. This is to limit the amount of current that the LED is getting so
that we don’t burn it out. Then, take the jumper wires and connect the red pin’s resistor side to the Arduino digital signal pin. Start with the
red jumper wire and plug it into pin 11. Connect the Cathode pin to Ground on the Arduino. Then attach the blue pin’s resistor side to pin
10. Finally, run a jumper wire from the green pin’s resistor side to pin 9.

Overview of Coding Arduino

Arduino populates two methods automatically: setup() and loop(). These methods are required, which means you have to have them
in your code for it to compile. The setup() method is like an initialization routine. The loop() method is similar to the main method. It
gets executed from top to bottom sequentially, and then when it gets to the bottom it goes back to the top and it runs through the code again.

Program an RGB LED with Arduino

First, let’s map the pins that are plugged into the signal lines. Create three variables for each LED color. The first pin is for the red color, so
I’ll call it redPin and set it to 11.

You can use any of the PWM pins for this, just make sure that all of the signal pins are plugged into a PWM pin so that we can control the
colors later. For the blue and green pins, I’ll create variables equal to 10 and 9, respectively.

Next, go into the setup() method and set all of the signal pins equal to OUTPUTS using the pinMode() method. The LEDs are going
to be taking information from the controller and sending it to the environment, which is also known as an output.
Control Color Patterns with an RGB LED

If you’ve ever worked photo editing or graphics programs like Photoshop or PowerPoint, or if you’ve ever used any tool that has a fill
button, you’ll notice that colors are represented using an RGB or a Hex value.

You can use RGB color values to set the color of your RGB LED. All you need to do is set your red, green, and blue values (from 0 to
255), and the LED will light up according to that color code.

First, open this color picker, and then look in the bottom left corner for the RGB values.

Play around with the slider wheel and select a color. The closer you are to the red, green, or blue colors, directly, the better the color is
going to look on the LED. That’s based on resolution and also how our eyes interpret colors, but for the most part, the purpose of this
activity is to show you color mapping, and then using the Hex codes to create RGB LED color patterns. Once you have a color you like, jot
down (or remember) the RGB values. We’ll use these to program the RGB LEDs in just a minute.

Program RGB LEDs with Arduino

The Arduino has an 8-bit PWM output command that we can use to write the Hex values to the signal pins on the LED. It’s
called analogWrite(...).

Here’s what it looks like:

analogWrite(redPin, value); //set the red pin to a value 0-255, where 0 is off and 255 is on

We’ll repeat this code for each of the colors to create a combination. So, if you wanted to command the RGB LED to red, then you’d use
the following lines:

analogWrite(redPin, 255);
analogWrite(greenPin, 0);
analogWrite(bluePin,0);

Store these in your method, and upload the code to your board. The LED should be red. If it’s not, be sure that you’ve assigned the proper
pin values to the redPin, greenPin, and bluePin variables. Also, verify that each of the pins is connected to PWM pins on the Arduino.
Rather than writing a single line to command each color, we can write one line that includes all three values for red, green, and blue. Let’s
store this in a method called setColor(...).

void setColor(int red, int green, int blue){


analogWrite(redPin, red);analogWrite(greenPin, green);analogWrite(bluePin,blue);
}
Then, if we want to set the RGB LED to green, we can use the command as follows:

setColor(0,255,0); //set the RGB color to red value, green value, blue value

And that’s it! Call the method in loop() and upload the code to your board.
EXPERIMENT 4

Aim : Study temperature sensor and write a program to monitor temperature using Arduino.

To read Temperature using LM35 Temperature sensor

The LM35 series are precision integrated-circuit temperature devices with an output voltage linearly proportional to the Centigrade
temperature. The LM35 device has an advantage over linear temperature sensors calibrated in Kelvin, as the user is not required to
subtract a large constant voltage from the output to obtain convenient Centigrade scaling. The LM35 device has an advantage over
linear temperature sensors calibrated in Kelvin, as the user is not required to subtract a large constant voltage from the output to obtain
convenient Centigrade scaling. The LM35 device does not require any external calibration or trimming to provide typical accuracies
of ±¼°C at room temperature and ±¾°C over a full −55°C to 150°C temperature range.

Technical Specifications:--
 Calibrated directly in Celsius (Centigrade)
 Linear + 10-mV/°C scale factor
 0.5°C ensured accuracy (at 25°C)
 Rated for full −55°C to 150°C range
 Suitable for remote applications

Components Required:- 1 × Breadboard , 1 × Arduino Uno R3, 1 × LM35 sensor

Procedure:- Follow the circuit diagram and hook up the components on the breadboard as shown in the image given below.

Arduino Code
float temp; int tempPin = 0;
void setup() { Serial.begin(9600); }
void loop() {
temp = analogRead(tempPin); temp = temp * 0.48828125; Serial.print("TEMPERATURE = ");
Serial.print(temp); Serial.print("*C"); Serial.println(); delay(1000);
}

LM35 sensor has three terminals - Vs, Vout and GND. We will connect the sensor as follows −
 Connect the +Vs to +5v on your Arduino board.
 Connect Vout to Analog0 or A0 on Arduino board.
 Connect GND with GND on Arduino.
The Analog to Digital Converter (ADC) converts analog values into a digital approximation based on the formula ADC Value =
sample * 1024 / reference voltage (+5v). So with a +5 volt reference, the digital approximation will be equal to input voltage * 205.

Result :- You will see the temperature display on the serial port monitor which is updated every second.
Experiment -05
Study and Implement RFID, NFC using Arduino

RFID tagging is an ID system that uses small radio frequency identification devices for identification and tracking purposes. An RFID tagging
system includes the tag itself, a read/write device, and a host system application for data collection, processing, and transmission.
In simple words an RFID uses electromagnetic fields to transfer data over short distances. RFID is useful to identify people, to make transactions,
etc. You can use an RFID system to open a door. For example, only the person with the right information on his card is allowed to enter. An RFID
system uses:
 tags attached to the object to be identified, in this example we have a keychain and an electromagnetic card. Each tag has his own
identification (UID).
 two-way radio transmitter-receiver, the reader, that sends a signal to the tag and read its response

Keychain and Electromagnetic card are commonly used tags and Radio transmitter receiver

Basic Specifications:
 Input voltage: 3.3V
 Frequency: 13.56MHz
Now, before typing out the necessary code, you need to download the necessary library for this sensor from this repository. Extract the
contents from the zip folder "rfid-master" and add this library folder under the existing libraries of Arduino. After doing so, restart
your ArduinoIDE. Now, our Arduino is ready to take commands and execute accordingly. The Arduino Code has been uploaded at the
end of this tutorial. Compile the code and eliminate "typo" errors (if any).
Now, its time to connect our Arduino with the RFID reader. Refer to the PIN wiring below,as well as the Connection schematic
diagram for easy reference. PinWiring to Arduino Uno
SDA------------------------Digital 10 MISO----------------------Digital 12 RST------------------------Digital 9
SCK------------------------Digital 13 IRQ------------------------unconnected 3.3V------------------------3.3V (DO
NOT CONNECT TO 5V)
MOSI----------------------Digital 11 GND-----------------------GND
Reading data from an RFID tag
After having the circuit ready, go to File > Examples > MFRC522 > DumpInfo and upload the code. This code will be available in
Arduino IDE (after installing the RFID library). Then, open the serial monitor. You should see something like the figure below:
CODE
Arduino code for RFID reader Arduino
In the piece of code above you need to change the if (content.substring(1) == “REPLACE WITH YOUR UID”) and type the UID card
you’ve written previously.
#include <MFRC522.h>
#include <SPI.h>
#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.

void setup() {
Serial.begin(9600);SPI.begin();mfrc522.PCD_Init();
Serial.println("Approximate your card to the reader...");Serial.println();
}
void loop() {
if (!mfrc522.PICC_IsNewCardPresent() or !mfrc522.PICC_ReadCardSerial()) return;
Serial.print("UID tag :"); String content = ""; byte letter;
for (byte i = 0; i < mfrc522.uid.size; i++) {
Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
Serial.print(mfrc522.uid.uidByte[i], HEX);
content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
content.concat(String(mfrc522.uid.uidByte[i], HEX));
}
Serial.println(); Serial.print("Message : "); content.toUpperCase();
if (content.substring(1) == "BD 31 15 2B")
Serial.println("Authorized access"); Serial.println(); delay(3000);
else Serial.println(" Access denied"); delay(3000);
}
SCHEMATICS
Connection schematic diagram

Near field communication(NFC) are protocols that electronic devices use to communicate and transfer data between each other. Near
field communication devices have to be very near to each other, usually between 10cm, but the range can vary depending on the
device that is transmitting and the size of the tag. NFC tags require no power input whatsoever. They use magnetic induction between
two between two small loop antennas. The tags these days carry between 96 and 4,096 bytes of information.

Reading an NFC Tag

These header files are extremely important and the project won’t work without them. Afterwards you want to write the following
code.

void setup(void) {
Serial.begin(9600); Serial.println("NFC TAG READER"); nfc.begin();
}
void loop(void) {
Serial.println("\nScan your NFC tag on the NFC Shield\n");
if (nfc.tagPresent()) {
NfcTag tag = nfc.read();Serial.println(tag.getTagType()); Serial.print("UID: ");
Serial.println(tag.getUidString());
if (tag.hasNdefMessage()) {
NdefMessage message = tag.getNdefMessage();
Serial.print("\nThis Message in this Tag is "); Serial.print(message.getRecordCount());
Serial.print(" NFC Tag Record");
if (message.getRecordCount() != 1) Serial.print("s")
Serial.println(".");
int recordCount = message.getRecordCount();
for (int i = 0; i < recordCount; i++) {
Serial.print("\nNDEF Record ");Serial.println(i + 1);
NdefRecord record = message.getRecord(i);
int payloadLength = record.getPayloadLength();
byte payload[payloadLength];record.getPayload(payload); String payloadAsString = "";
for (int c = 0; c < payloadLength; c++)payloadAsString += (char)payload[c];
Serial.print(" Information (as String): ");
Serial.println(payloadAsString); String uid = record.getId();
if (uid != "") Serial.print(" ID: "); Serial.println(uid);
}
}
}
delay(10000);
}

Notice that it gives the the unique identification of the NFC tag and it tells me what information I have written on the tags. On this
particular tag I have a simple welcome message and a link to the Arduino Twitter. The Arduino is successfully reading the info on my
tag. The video below shows how my Nexus 5 reads the tag and displays the messages.

Writing on an NFC Tag

Now to be able to write a message on a tag, the process is similar except we are going to change the code a little bit. The header before
void setup() will stay the same but this will be the code you want to write and upload to the Arduino

void setup() {
Serial.begin(9600); Serial.println("NFC Tag Writer");nfc.begin();
}
void loop() {
Serial.println("\nPlace an NFC Tag that you want to Record these Messages on!");
NdefMessage message = NdefMessage();
message.addTextRecord("My First NFC Tag Write"); message.addUriRecord("http://allaboutcircuits.com");
message.addTextRecord("Way to Go, It Worked!");
boolean success = nfc.write(message);
if (success) Serial.println("Good Job, now read it with your phone!");
else Serial.println("Write failed");
delay(10000);
}

This Code is Saving three messages on the tag: an intro text saying “My First NFC Tag Write”, then a link to AllAboutCircuits and
lastly an ending message saying “Way to Go, It Worked!”
Experiment -06

Study and Configure Raspberry Pi


Raspberry Pi, developed by Raspberry Pi Foundation in association with Broadcom, is a series of small single-board computers and
perhaps the most inspiring computer available today.

Generations and Models

In 2012, the company launched the Raspberry Pi and the current generations of regular Raspberry Pi boards are Zero, 1, 2, 3, and 4.
Generation 1 Raspberry Pi had the following four options −

 Model A
 Model A +
 Model B
 Model B +
Among these models, the Raspberry Pi B models are the original credit-card sized format.
On the other hand, the Raspberry Pi A models have a smaller and more compact footprint and hence, these models have the reduced
connectivity options.
Raspberry Pi Zero models, which come with or without GPIO (general-purpose input output) headers installed, are the most
compact of all the Raspberry Pi boards types.

Speed Specifications
The table below gives the speed specifications of various Raspberry Pi models and generations focusing on the version’s release date,
form factor and dimensions −

Raspberry Pi Version Release Date Form Factor Dimensions (in mm)

Raspberry Pi 4 Model B 2019-2020 Standard 85.6 x 56.5

Raspberry Pi 3 Model B+ 2018 Standard 85.6 x 56.5

Raspberry Pi 3 Model B 2016 Standard 85.6 x 56.5

Raspberry Pi 3 Model A+ 2018 Compact 65 x 56.5

Raspberry Pi Zero Wireless with Headers 2017 Mini 65 x 30 x 5

Raspberry Pi Zero Wireless 2016 Mini 65 x 30 x 5

Raspberry Pi Zero 2015 Mini 65 x 30 x 5

Raspberry Pi 2 Model B 2015 Standard 85.6 x 56.5

Raspberry Pi 1 Model B + 2014 Standard 85.6 x 56.5

Raspberry Pi 1 Model B 2012 Standard 85.6 x 56.5

Raspberry Pi 1 Model A+ 2014 Compact 65 x 56.5

Raspberry Pi 1 Model A 2013 Standard 85.6 x 56.5

Raspberry Pi - Getting Started


In this modern age when computers are sleek, Raspberry Pi seems alien with tiny codes printed all over its circuit board. That’s a big
part of Raspberry Pi’s appeal. Let us have a look at what we can do with this appealing circuit board.
Uses
Like a desktop computer, you can do almost anything with the Raspberry Pi. You can start and manage programs with its graphical
windows desktop. It also has the shell for accepting text commands.
We can use the Raspberry Pi computer for the following −

 Playing games  Word processing  Paying bills online


 Browsing the  Spreadsheets  Managing your
internet  Editing photos accounts.

The best use of Raspberry Pi is to learn how a computer works. You can also learn how to make electronic projects or programs with
it.
It comes with two programming languages, Scratch and Python. Through GPIO (general-purpose input output) pins, Raspberry Pi
can be connected to other circuits, so that you can control the other devices of your choice.

Connecting Raspberry Pi
It is quite easy to connect Raspberry Pi. Let us understand about the same in detail in this chapter.

Ports and Sockets

You should make sure that you have to face your Raspberry Pi in the right way. Most components and sockets, with the help of which
you connect it, are sticking out at the top side whereas the back side is relatively flat. The spiky GPIO (general-purpose input output)
pins should be at the top left.
Let us have a look at the diagrams below representing the location of connectors and main integrated circuits (ICs) on the Raspberry
Pi boards.
The source of the diagrams is https://core-electronics.com.au
Experiment - 07
WAP for LED blink using Raspberry Pi

Setting up the circuit

The first step in this project is to design a simple LED circuit. Then we will make the LED circuit controllable from the Raspberry Pi
by connecting the circuit to the general purpose input/output (GPIO) pins on the Raspberry Pi.

A simple LED circuit consists of a LED and resistor. The resistor is used to limit the current that is being drawn and is called a current
limiting resistor. Without the resistor the LED would run at too high of a voltage, resulting in too much current being drawn which in
turn would instantly burn the LED, and likely also the GPIO port on the Raspberry Pi.

To calculate the resistor value we need to examine the specifications of the LED. Specifically we need to find the forward voltage
(VF) and the forward current (IF). A regular red LED has a forward voltage (VF) of 1.7V and forward current of 20mA (IF).
Additionally we need to know the output voltage of the Raspberry Pi which is 3.3V. We can then calculate the resistor size needed to
limit the current to the LED’s maximum forward current (IF) using ohm’s law like this:

RΩ=VI=3.3–VFIF=3.3–1.720mA=80Ω

Unfortunately 80 ohm is not a standard size of a resistor. To solve this we can either combine multiple resistors, or round up to a
standard size. In this case we would round up to 100 ohm.

With the value calculated for the current limiting resistor we can now hook the LED and resistor up to GPIO pin 8 on the Raspberry
Pi. The resistor and LED needs to be in series like the diagram below. To find the right resistor use the resistor color code – for a 100
ohm resistor it needs to be brown-black-brown. You can use your multimeter to double check the resistor value.

When hooking up the circuit note the polarity of the LED. You will notice that the LED has a long and short lead. The long lead is the
positive side also called the anode, the short lead is the negative side called the cathode. The long should be connected to the resistor
and the short lead should be connected to ground via the blue jumper wire and pin 6 on the Raspberry Pi as shown on the diagram. To
find the pin number refer to this diagram showing the physical pin numbers on the Raspberry Pi

Writing the Python Software to blink the LED


With the circuit created we need to write the Python script to blink the LED. Before we start writing the software we first need to
install the Raspberry Pi GPIO Python module. This is a library that allows us to access the GPIO port directly from Python.

To install the Python library open a terminal and execute the following
$ sudo apt-get install python-rpi.gpio python3-rpi.gpio
With the library installed now open your favorite Python IDE (I recommend Thonny Python IDE more information about using
it here).

Our script needs to do the following:


 Initialize the GPIO ports
 Turn the LED on and off in 1 second intervals

To initialize the GPIO ports on the Raspberry Pi we need to first import the Python library, the initialize the library and setup pin 8 as
an output pin.
import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library
from time import sleep # Import the sleep function from the time module
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW) # Set pin 8 to be an output pin and set initial value to low (off)

Next we need to turn the LED on and off in 1 second intervals by setting the output pin to either high (on) or low (off). We do this
inside a infinite loop so our program keep executing until we manually stop it.

while True: # Run forever


GPIO.output(8, GPIO.HIGH) # Turn on
sleep(1) # Sleep for 1 second
GPIO.output(8, GPIO.LOW) # Turn off
sleep(1) # Sleep for 1 second

Combining the initialization and the blink code should give you the following full Python program:
import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library
from time import sleep # Import the sleep function from the time module
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW) # Set pin 8 to be an output pin and set initial value to low (off)
while True: # Run forever
GPIO.output(8, GPIO.HIGH) # Turn on
sleep(1) # Sleep for 1 second
GPIO.output(8, GPIO.LOW) # Turn off
sleep(1) # Sleep for 1 second

With our program finished, save it as blinking_led.py and run it either inside your IDE or in the console with:

$ python blinking_led.py
With the program running you should see something like this:
Experiment -08

Study and Implement Zigbee Protocol using Arduino / Raspberry Pi

ZigBee is a communication device used for the data transfer between the controllers, computers, systems, really anything with a serial
port. As it works with low power consumption, the transmission distances is limited to 10–100 meters line-of-sight. ZigBee devices
can transmit data over long distances by passing data through a mesh network of intermediate devices to reach more distant ones.
ZigBee is typically used in low data rate applications that require long battery life and secure networking. Its main applications are in
the field of wireless sensor network based on industries as it requires short-range low-rate wireless data transfer. The technology
defined by the ZigBee specification is intended to be simpler and less expensive than other wireless networks.

Here we make use of an interface of Zigbee with Raspberry Pi2 for a proper wireless communication. Raspberry Pi2 has got four USB
ports, so it is better to use a Zigbee Dongle for this interface. Now we want to check the communication between the two paired
ZigBee modules.
Modules Needed : Raspberry Pi2, XBee 1mW Wire Antenna- Series 1 (2 No:), XBee Explorer Dongle (2 No:)

The two Zigbee must be paired with the same baudrate (for Ex: 9600) with X-CTU Software. Attach the two Zigbee’s to the two
dongle’s and connect one pair on the USB port of the Raspberry Pi2. Connect the other pair to the USB port of a computer or a
Laptop. Install the FTDI Driver on the Computer /laptop to provide usb communication. Create a hyperterminal, select the
corresponding com port and the baudrate for the connected device.
Click here to see the instructions to Test your XBee Explorer Dongle with PC.
1import serial
2
3# Enable USB Communication
4ser = serial.Serial('/dev/ttyUSB0', 9600,timeout=.5)
5
6while True:
7 ser.write('Hello User \r\n') # write a Data
8 incoming = ser.readline().strip()
9 print 'Received Data : '+ incoming
The two zigbee must be in a line of sight and check the results in the Python shell and in the hyperterminal of
the computer.
Experiment -09

Study and implement MQTT protocol using Arduino


MQTT is a lightweight transfer protocol aimed at small IoT enabled devices. While the Arduino on its own has no networking capability, it can be
connected to an Ethernet shield, allowing it to connect to the internet. Using the Ethernet and MQTT library, we can quickly get our Arduino talking
to MQTT servers to submit and retrieve data!

Install Needed Libraries:- By default, the Arduino IDE comes with the Ethernet library needed, but the MQTT library needs to be installed.
Navigate to Sketch > Include Library > Manager Libraries, and search for MQTT in the search field. The library that we will use is called
“PubSubClient” which is a lightweight library for use with MQTT. The library is somewhat close to the bottom of the list, so carefully look through
the list for it!

Create a new file, call it whatever you want (such as “MyFirstMQTT”) and then include the following libraries at the top of your program. SPI is
needed for the Ethernet shield, the Ethernet.h is the Ethernet library that gets passed to the PubSubClient.h library. This handles the MQTT protocol
and messaging
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>

The first step into using MQTT is to define a number of variables, including the IP address, MAC, server, and some objects. The first line in our
program is a function prototype of the function that will handle incoming messages, but this will be looked at more in depth later. The next few lines
create our MAC address - which must be unique - and the IP address of our Ethernet. It should be noted that this IP address will be ignored if our
router can assign one for us. If it can’t, it will fall back and use this IP address.

The next line defines the MQTT broker that we will connect to. A broker in the world of MQTT is simply a server, but unlike a server, brokers can
send messages to clients at any time and they are not designed to store data, only relay it. The last two lines define an Ethernet object that is used to
control the Ethernet shield and an MQTT client that takes the Ethernet object. Because the MQTT client takes the Ethernet object, it makes coding
incredibly simple as we do not have to handle the Ethernet shield at all!

void subscribeReceive(char* topic, byte* payload, unsigned int length);


byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 160);
const char* server = "test.mosquitto.org";
EthernetClient ethClient;
PubSubClient mqttClient(ethClient);

Setup:- In our setup function, we need to start by enabling the serial port so we can see the status of our Arduino and begin an Ethernet connection.
The .begin() function takes two arguments: the MAC address and the IP address (which we simply pass). It’s at this point that we also include a small
delay to allow the Ethernet Shield to do its thing!

The next step is to set the MQTT broker that we will be communicating on. The .connect() function takes several arguments including usernames and
passwords, but since we are using a public testing MQTT broker, we only need to define a user ID. For now, our user ID will be “myClientID”. This
function will return a Boolean value depending on the success of the connection to the broker. If the connection was successful, then it returns true.
Otherwise, it returns false. If the connection is true then we create an event handler that will call the function “subscribeReceive” upon receiving a
message.

void setup(){
Serial.begin(9600);Ethernet.begin(mac, ip);delay(3000);
mqttClient.setServer(server, 1883);
if (mqttClient.connect("myClientID")) {
Serial.println("Connection has been established, well done");
mqttClient.setCallback(subscribeReceive);
} else Serial.println("Looks like the server connection failed...");
}

Main Loop
In our main loop, the first function is .loop(). In essence, it handles keep-alive signals, as well as handling incoming messages. The next line in the
loop gets our Arduino to subscribe to a topic, “MakerIOTopic”. In MQTT, a topic can be thought of as a string variable stored on the broker that can
hold some data and users can publish to a topic, subscribe to a topic, or do both! For example, if a user publishes the value “door is open” to the topic
“door state” then any device subscribed to the topic “door state” will receive the message “door it open.” If any device in the world publishes a
message to “MakerIOTopic” then our program will call the function “subscribeReceive.”

The next section of code attempts to publish a message to the topic “MakerIOTopic.” In this case, we send the message “Hello World” to the
“MakerIOTopic” topic so that any devices subscribed to that topic will receive this message. The last line is a simple delay that prevents us from
abusing the server with a million messages!

void loop() {
mqttClient.loop();mqttClient.subscribe("MakerIOTopic");
if (mqttClient.publish("MakerIOTopic", "Hello World")) Serial.println("Publish message
success");
else Serial.println("Could not send message :(");
delay(4000);
}

Subscribe Handle :- The last function in our program is subscribeReceive, which is called whenever a message arrives from the MQTT broker.
Three variables are passed to it: the topic name (in the form of a char array), the message itself (in the form of a byte array), and the length of those
bytes. Both the topic and payload are printed and the output window shows the result below.

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


Serial.print("Topic: ");Serial.println(topic);Serial.print("Message: ");
for (int i = 0; i < length; i++) Serial.print(char(payload[i]));
Serial.println("");
}
Experiment - 10
Study and implement CoAP protocol using Arduino
CoAP simple server, client library for Arduino IDE/PlatformIO, ESP32, ESP8266.

Source Code:- source code contains only 2 files. coap-simple.cpp, coap-simple.h.

coap-simple.cpp
@ @-19, 6 + 19, 16 @ @Coap::Coap() {
this->_udp = &udp; this->coap_buf_size = coap_buf_size;
this->tx_buffer = new uint8_t[this->coap_buf_size]; this->rx_buffer = new uint8_t[this->coap_buf_size];
}
Coap::~Coap() {
if (this->tx_buffer != NULL) delete[] this->tx_buffer;
if (this->rx_buffer != NULL) delete[] this->rx_buffer;
}
bool Coap::start() {
@ @-36, 8 + 46, 7 @ @uint16_t Coap::sendPacket(CoapPacket & packet, IPAddress ip) { }
uint16_t Coap::sendPacket(CoapPacket & packet, IPAddress ip, int port) {
uint8_t buffer[coap_buf_size]; uint8_t *p = buffer;
uint8_t *p = this->tx_buffer; uint16_t running_delta = 0; uint16_t packetSize = 0;
@ @-48, 7 + 57, 7 @ @uint16_t Coap::sendPacket(CoapPacket & packet, IPAddress ip,int port) {
*p++ = packet.code; *p++ = (packet.messageid >> 8);
*p++ = (packet.messageid & 0xFF); p = buffer + COAP_HEADER_SIZE;
p = this->tx_buffer + COAP_HEADER_SIZE; packetSize += 4;
@ @-104, 7 + 113, 7 @ @uint16_t Coap::sendPacket(CoapPacket & packet, IPAddress ip,int port) {}
_udp->beginPacket(ip, port); _udp->write(buffer, packetSize);
_udp->write(this->tx_buffer, packetSize); _udp->endPacket();
return packet.messageid;
@@ -220,29 +229,27 @@ int Coap::parseOption(CoapOption *option, uint16_t *running_delta, uint8_t **buf
}
bool Coap::loop() {
uint8_t buffer[coap_buf_size];
int32_t packetlen = _udp->parsePacket();
while (packetlen > 0) {
packetlen = _udp->read(buffer, packetlen >= coap_buf_size ? coap_buf_size : packetlen);
packetlen = udp->read(this->rx_buffer, >= coap_buf_size ? coap_buf_size : packetlen);
CoapPacket packet;
if (packetlen < COAP_HEADER_SIZE || (((buffer[0] & 0xC0) >> 6) != 1)) {
if (packetlen < COAP_HEADER_SIZE || (((this->rx_buffer[0] & 0xC0) >> 6) != 1))
packetlen = _udp->parsePacket();continue;
packet.type = (buffer[0] & 0x30) >> 4; packet.tokenlen = buffer[0] & 0x0F; packet.code = buffer[1];
packet.messageid = 0xFF00 & (buffer[2] << 8); packet.messageid |= 0x00FF & buffer[3];
packet.type = (this->rx_buffer[0] & 0x30) >> 4;packet.tokenlen = this->rx_buffer[0] & 0x0F;
packet.code = this->rx_buffer[1]; packet.messageid = 0xFF00 & (this->rx_buffer[2] << 8);
packet.messageid |= 0x00FF & this->rx_buffer[3];
if (packet.tokenlen == 0)packet.token = NULL;
else if (packet.tokenlen <= 8)packet.token = buffer + 4;
else if (packet.tokenlen <= 8)packet.token = this->rx_buffer + 4;
else packetlen = _udp->parsePacket();continue;
@ @-252, 8 + 259, 8 @ @ bool Coap::loop() {
if (COAP_HEADER_SIZE + packet.tokenlen < packetlen) {
int optionIndex = 0;
uint16_t delta = 0; uint8_t *end = buffer + packetlen;
uint8_t *p = buffer + COAP_HEADER_SIZE + packet.tokenlen;
uint8_t *end = this->rx_buffer + packetlen;
uint8_t *p = this->rx_buffer + COAP_HEADER_SIZE + packet.tokenlen;
while (optionIndex < COAP_MAX_OPTION_NUM && *p != 0xFF && p < end) {
if (0 != parseOption(&packet.options[optionIndex], &delta, &p,end - p))
@@ -347,4 +354,3 @@ uint16_t Coap::sendResponse(IPAddress ip, int port, uint16_t messageid, const ch
return this->sendPacket(packet, ip, port);
}
}
}
}
}
}
}
}

coap-simple.h
@ @-178, 6 + 178, 8 @ @class Coap {
CoapCallback resp; int _port; int coap_buf_size;
uint8_t *tx_buffer = NULL; uint8_t *rx_buffer = NULL;
uint16_t sendPacket(CoapPacket &packet, IPAddress ip);
uint16_t sendPacket(CoapPacket &packet, IPAddress ip, int port);
@ @-188, 6 + 190, 7 @ @class Coap {
UDP& udp,int coap_buf_size = COAP_BUF_MAX_SIZE
~Coap(); bool start(); bool start(int port);
void response(CoapCallback c) { resp = c; }
}
}
#endif

How to use
USE this source code branch zip file and extract it to the Arduino libraries directory or checkout repository.

cd $HOME/Documents/Arduino/libraries/
git clone https://github.com/hirotakaster/CoAP-simple-library
# restart Arduino IDE, you can find CoAP-simple-library examples.

These examples need CoAP server libcoap or microcoap server to test the example program.

This is how to use the example with libcoap on Ubuntu Linux. You don't need to use CoAP server(request/reseponse), simply follow
these steps :

git clone https://github.com/obgm/libcoap


cd libcoap/
./autogen.sh
./configure
make
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:.libs
gcc -o coap-server ./examples/coap-server.c -I./include -I. -L.libs -lcoap-1 -DWITH_POSIX
gcc -o coap-client ./examples/client.c ./examples/coap_list.c -I./include -I. -L.libs -lcoap-1 -DWITH_POSIX
./coap-server
# next start Arduino and check the request/response.

You might also like