0% found this document useful (0 votes)
4 views

IoT lab file

The document is a practical file for an Internet of Things (IoT) lab at Amity University, detailing various programming experiments and installations related to Python and Arduino. It includes an index of programs, aims, theories, and sample codes for Python libraries, data types, arithmetic operations, and Arduino IDE setup. The file serves as a comprehensive guide for students in the Computer Science and Engineering department to understand and implement IoT concepts using Python and Arduino.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

IoT lab file

The document is a practical file for an Internet of Things (IoT) lab at Amity University, detailing various programming experiments and installations related to Python and Arduino. It includes an index of programs, aims, theories, and sample codes for Python libraries, data types, arithmetic operations, and Arduino IDE setup. The file serves as a comprehensive guide for students in the Computer Science and Engineering department to understand and implement IoT concepts using Python and Arduino.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

AMITY UNIVERSITY MADHYA

PRADESH, GWALIOR
PRACTICAL FILE OF
INTERNET OF THINGS (IOT) LAB
CSE 623

SUBMITTED TO SUBMITTED BY
Dr. Shyam Sundar Gupta Pragya Gupta
A60205221026
B.Tech(CSE)
Section – B
2021-25

Department of Computer Science & Engineering


Amity School of Engineering & Technology
INDEX
S.No. Programs Page no. Date Signature
1. Describe features and applications of python. 1-2

2. Mention 5 libraries of python and their uses 3-7


along with code implementing those libraries.
3. Study and Install Python. 8-10

4. Write a program for data types in python. 11-12

5. Write a Program for arithmetic operation in 13


Python.
6. Write a Program for looping statement in 14-15
Python.
7. Write a Program for plotting graph in python. 16

8. Study and Install IDE of Arduino. 17-18

9. Study of different types of Arduino boards. 19-21

10. Write program using Arduino IDE for Blink 22-23


LED.
11. Write Program for RGB LED using Arduino. 24-25

12. Write a program for Buzzer using arduino. 26

13. Write a program for LDR. 27

14. Write code for ultrasonic sensor using arduino. 28-29

15. Study the Temperature sensor and Write 30-31


Program for monitor temperature using Arduino.
16. Study and Implement RFID, NFC using 32-34
Arduino.
17. Study and implement MQTT protocol using 35-36
Arduino.
18. Study and Configure Raspberry Pi. 37-40
19. Write a program for LED blink using Raspberry 41
Pi.
20. Study and Implement ZIGBEE Protocol using 42
Arduino / Raspberry Pi.
LAB EXPERIMENT – 1

AIM: To understand features and applications of python.


Theory: Features of Python are:
1. Simple and Easy to Learn: Python syntax is straightforward and easy to understand,
making it accessible for beginners.
2. High-level Language: Python abstracts complex low-level details, allowing
programmers to focus on problem-solving rather than system intricacies.
3. Interpreted: Python code is executed line by line by the Python interpreter, facilitating
rapid development and debugging.
4. Cross-platform: Python programs can run on various operating systems without any
modifications, including Windows, macOS, Linux, and more.
5. Extensive Standard Library: Python comes with a vast collection of modules and
libraries for various tasks, reducing the need for writing code from scratch.
6. Dynamic Typing: Python uses dynamic typing, enabling variables to change types as
needed during runtime, providing flexibility.
7. Object-Oriented: Python supports object-oriented programming paradigms, allowing
for the creation and manipulation of objects with attributes and methods.
8. Versatile: Python is suitable for a wide range of applications, including web
development, data analysis, artificial intelligence, scientific computing, automation,
and more.
9. Large Community and Ecosystem: Python has a vibrant community of developers
worldwide, contributing to its extensive ecosystem of libraries, frameworks, and
resources.

Applications of Python:
1. Web Development: Frameworks like Django and Flask are used to build dynamic web
applications and APIs.
2. Data Science and Machine Learning: Python's libraries such as NumPy, Pandas,
Matplotlib, and scikit-learn are widely used for data analysis, visualization, and
machine learning tasks.
3. Scripting: Python is popular for scripting tasks, automation, and system administration
due to its simplicity and versatility.
4. Scientific Computing: Python, along with libraries like SciPy and OpenCV, is used for
scientific computing, simulations, and image processing.
5. Game Development: Python, with libraries like Pygame, is utilized in game
development for prototyping, scripting, and building simple games.
6. Desktop GUI Applications: Libraries like Tkinter and PyQt enable the development
of desktop graphical user interface (GUI) applications.
7. Network Programming: Python's socket library facilitates network programming,
including server-client applications and networking tools.
8. Education: Python is extensively used in educational institutions for teaching
programming due to its simplicity and readability.

1
9. Embedded Systems: Python can be used for developing applications for embedded
systems and IoT devices, leveraging microcontroller platforms like Raspberry Pi and
Arduino.
10. Finance and Trading: Python is employed in finance for quantitative analysis,
algorithmic trading, and building financial models due to its robust libraries and tools.

2
LAB EXPERIMENT – 2
AIM: To understand 5 libraries of python and their uses along with code implementing those
libraries.
Theory: 5 libraries of Python and their uses:
1. NumPy (Numerical Python): NumPy is a fundamental package for numerical
computing in Python. It provides support for arrays, matrices, and a wide range of
mathematical functions to operate on these arrays efficiently.
Applications:

• NumPy is extensively used in scientific computing, engineering, and data


analysis for tasks such as linear algebra operations, Fourier transforms, random
number generation, and more.
• It serves as the foundation for many other libraries in the Python ecosystem,
including Pandas, SciPy, and Matplotlib, due to its efficient array manipulation
capabilities.

2. Pandas: Pandas is a powerful library for data manipulation and analysis, particularly
with labeled and relational data. It provides data structures like DataFrame and Series,
along with functions to manipulate and analyze them efficiently.
Applications:

• Pandas is commonly used in data preprocessing tasks, data cleaning, data


exploration, and data wrangling before analysis or visualization.
• It facilitates tasks such as data aggregation, filtering, grouping, and merging,
making it indispensable for working with structured data.

3. Matplotlib: Matplotlib is a comprehensive library for creating static, interactive, and


animated visualizations in Python. It provides a wide range of plotting functions to
create various types of plots, including line plots, scatter plots, bar plots, histograms,
and more.
Applications:

• Matplotlib is widely used in scientific computing, data analysis, and data


visualization tasks to present data in a visually appealing and understandable
manner.
• It enables researchers, analysts, and developers to explore data, identify
patterns, and communicate insights effectively through visualizations.

4. Scikit-learn: Scikit-learn is a versatile machine learning library that provides simple


and efficient tools for data mining and data analysis. It includes a wide range of
algorithms for classification, regression, clustering, dimensionality reduction, and
more.

3
Applications:

• Scikit-learn is used in various machine learning tasks, including predictive


modeling, pattern recognition, feature extraction, and model evaluation.
• It is suitable for both academic research and real-world applications, offering easy-
to-use interfaces and robust implementations of machine learning algorithms.

5. TensorFlow (or PyTorch): TensorFlow and PyTorch are leading deep learning
frameworks used for building and training neural networks. They provide high-level
APIs for constructing complex neural network architectures, along with efficient
implementations of automatic differentiation for training models.
Applications:
• These frameworks are used in various deep learning tasks, including image
recognition, natural language processing, speech recognition, and reinforcement
learning.
• They are utilized in both research and industry for developing state-of-the-art
deep learning models and deploying them in production environments.

Programs:
1. Code for Numpy:
Code:
import numpy as np

# Create a NumPy array


arr = np.array([1, 2, 3, 4, 5])

# Perform operations on the array


arr_squared = np.square(arr)
print(arr_squared)

2. Code for Pandas:


Code:
import pandas as pd

# Create a DataFrame from a dictionary

4
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']}
df = pd.DataFrame(data)

# Display the DataFrame


print(df)

3. Code for Matplotlib:


Code:
import matplotlib.pyplot as plt

# Create data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# Plot data
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Line Plot')
plt.show()

4. Code for Scikit-learn:


Code:
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier

# Load Iris dataset

5
iris = load_iris()
X, y = iris.data, iris.target

# Split data into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

# Initialize and train a k-nearest neighbors classifier


knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)

# Evaluate the classifier


accuracy = knn.score(X_test, y_test)
print('Accuracy:', accuracy)

5. Code for TensorFlow:


Code:
import tensorflow as tf

# Create a simple neural network model


model = tf.keras.Sequential([
tf.keras.layers.Dense(64, activation='relu', input_shape=(784,)),
tf.keras.layers.Dense(10, activation='softmax')
])

# Compile the model


model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])

# Train the model

6
model.fit(X_train, y_train, epochs=5, batch_size=32)

# Evaluate the model


test_loss, test_acc = model.evaluate(X_test, y_test)
print('Test accuracy:', test_acc)

OUTPUT:
For Numpy:

For Pandas:

For Matplotlib:

For Scikt-learn:

7
LAB EXPERIMENT – 3

AIM: Study and Install Python.


Theory: Python is an interpreted, object-oriented, high-level programming language with
dynamic semantics. Its high-level built in data structures, combined with dynamic typing and
dynamic binding, make it very attractive for Rapid Application Development, as well as for
use as a scripting or glue language to connect existing components together. Python's simple,
easy to learn syntax emphasizes readability and therefore reduces the cost of program
maintenance. Python supports modules and packages, which encourages program modularity
and code reuse. The Python interpreter and the extensive standard library are available in
source or binary form without charge for all major platforms, and can be freely distributed.

Steps to Install Python:


Step - 1: Visit www.python.org Select the Python's version to download.
Click on the download button to download the exe file of Python.

Step - 2: Click on the Install Now, & Double-click the executable file, which is downloaded.

8
The following window will open. Click on the Add Path check box, it will set the Python path
automatically.
Now, Select Customize installation and proceed. We can also click on the customize installation
to choose desired location and features. Other important thing is install launcher for the all user
must be checked.
Here, under the advanced options, click on the checkboxes of " Install Python 3.11 for all users
", which is previously not checked in. This will checks the other option " Precompile standard
library " automatically. And the location of the installation will also be changed. We can change
it later, so we leave the install location default. Then, click on the install button to finally install.

Step - 3 Installation in Process

The set up is in progress. All the python libraries, packages, and other python default files will
be installed in our system. Once the installation is successful, the following page will appear
saying " Setup was successful ".

9
Step - 4: Verifying the Python Installation
To verify whether the python is installed or not in our system, we have to do the following.
Go to "Start" button, and search " cmd ".
Then type, " python - - version ".
If python is successfully installed, then we can see the version of the python installed.
If not installed, then it will print the error as " 'python' is not recognized as an internal or
external command, operable program or batch file. ".

10
LAB EXPERIMENT – 6

AIM: To write a program data types in python.


Program:
# Integer
integer_var = 10

# Float
float_var = 3.14

# String
string_var = "Hello, World!"

# Boolean
boolean_var = True

# List
list_var = [1, 2, 3, 4, 5]

# Tuple
tuple_var = (6, 7, 8, 9, 10)

# Dictionary
dictionary_var = {"apple": 5, "banana": 3, "orange": 2}

# Set
set_var = {1, 2, 3, 4, 5}

print("Integer Variable:", integer_var)


print("Float Variable:", float_var)
print("String Variable:", string_var)
print("Boolean Variable:", boolean_var)
print("List Variable:", list_var)
print("Tuple Variable:", tuple_var)
print("Dictionary Variable:", dictionary_var)
print("Set Variable:", set_var)

Output:

AIM: To write a program for arithmetic operation in Python.


Program:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

print("Addition result:", num1 + num2)


print("Subtraction result:", num1 - num2)
print("Multiplication result:", num1 * num2)
print("Division result:", num1 / num2)

Output:
AIM: To write a program for looping statement in Python.
Program:
# For loop example
print("For loop example:")
for i in range(1, 6):
print("Iteration", i)

# While loop example


print("\nWhile loop example:")
count = 1
while count <= 5:
print("Iteration", count)
count += 1

# Using break statement


print("\nUsing break statement:")
for i in range(1, 6):
if i == 4:
break
print("Iteration", i)

# Using continue statement


print("\nUsing continue statement:")
for i in range(1, 6):
if i == 3:
continue
print("Iteration", i)
Output:

AIM: Write a Program for plotting graph in python.


Program:
import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]

# Plotting the graph


plt.plot(x, y, marker='o', linestyle='-')

# Adding title and labels


plt.title('Sample Graph')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

Output:
LAB EXPERIMENT – 1

AIM: Study and Install IDE of Arduino. Study of different types of Arduino boards.
Theory: The Arduino Integrated Development Environment - or Arduino Software (IDE) -
contains a text editor for writing code, a message area, a text console, a toolbar with buttons
for common functions and a series of menus. It connects to the Arduino hardware to upload
programs and communicate with them.

Installation of Arduino IDE:


Get the latest version from the download page. You can choose between the Installer (.exe) and
the Zip packages. We suggest you use the first one that installs directly everything you need to
use the Arduino Software (IDE), including the drivers. With the Zip package you need to install
the drivers manually. The Zip file is also useful if you want to create a portable installation.
When the download finishes, proceed with the installation and please allow the driver
installation process when you get a warning from the operating system.

Choose the components to install.

Choose the installation directory.


Installation in progress.

The process will extract and install all the required files to execute properly the Arduino
Software (IDE) and then IDE is ready to use.

The Uno is a huge option for your initial Arduino. This Arduino board depends on an
ATmega328P based microcontroller. As compared with other types of arduino boards, it is very
simple to use like the Arduino Mega type board. .It consists of 14-digital I/O pins, where 6-
pins can be used as PWM(pulse width modulation outputs), 6-analog inputs, a reset button, a
power jack, a USB connection, an In-Circuit Serial Programming header (ICSP), etc. It
includes everything required to hold up the microcontroller; simply attach it to a PC with the
help of a USB cable and give the supply to get started with an AC-to-DC adapter or battery.

Arduino Uno (R3)

Arduino Uno is the most frequently used board and it is the standard form apart from all the
existing Arduino Boards. This board is very useful for beginners.

Arduino Nano
This is a small board based on the microcontrollers like ATmega328P otherwise ATmega628
but the connection of this board is the same as to the Arduino UNO board. This kind of
microcontroller board is very small in size, sustainable, flexible, and reliable.

Arduino Nano
As compared with the Arduino Uno board, it is small in size. The devices like mini USB and
Arduino IDE are necessary to build the projects. This board mainly includes analog pins-8,
digital pins-14 with the set of an I/O pin, power pins-6 & RST (reset) pins-2.

Arduino Micro
The Arduino Micro board mainly depends on the ATmega32U4 based Microcontroller that
includes 20-sets of pins where the 7-pins are PWM pins, 12-analog input pins. This board
includes different components like an ICSP header, RST button, small USB connection, crystal
oscillator-16MHz. The USB connection is inbuilt and this board is the shrunk version of the
Leonardo board.

Arduino Micro

Arduino Due
This Arduino board depends on the ARM Cortex-M3 and it is the first Arduino microcontroller
board. This board includes digital I/O pins-54 where 12-pins are PWM o/p pins, analog pins -
12, UARTs-4, a CLK with 84 MHz, an USB OTG, DAC-2, a power jack, TWI-2, a JTAG
header, an SPI header, two buttons for reset & erase.

Arduino Due

This board works with 3.3V where the highest voltage that the pins of input/output can stand
is 3.3V because providing a high voltage to any I/O pin can lead to damage the board This
board is simply connected to a computer through a small USB cable otherwise it can be
powered through an AC to DC adapter. This Arduino Due board is suitable with all shields of
Arduino at 3.3V.

LilyPad Arduino Board


The Lily Pad Arduino board is a wearable e-textile technology expanded by Leah “ Buechley”
and considerately designed by “Leah and SparkFun”. Each board was imaginatively designed
with huge connecting pads & a smooth back to let them to be sewn into clothing using
conductive thread. This Arduino also comprises of I/O, power, and also sensor boards which
are built especially for e-textiles. These are even washable!

LilyPad Arduino Board

Arduino Leonardo Board


The first development board of an Arduino is the Leonardo board. This board uses one
microcontroller along with the USB. That means, it can be very simple and cheap also. Because
this board handles USB directly, program libraries are obtainable which let the Arduino board
to follow a keyboard of the computer, mouse, etc.

Arduino Leonardo Board

RedBoard Arduino Board


The RedBoard Arduino board can be programmed using a Mini-B USB cable using the Arduino
IDE. It will work on Windows 8 without having to modify your security settings. It is more
constant due to the USB or FTDI chip we used and also it is entirely flat on the back. Creating
it is very simple to utilize in the project design. Just plug the board, select the menu option to
choose an Arduino UNO and you are ready to upload the program. You can control the
RedBoard over a USB cable using the barrel jack.

RedBoard Arduino Boards


LAB EXPERIMENT – 10

AIM: Write program using Arduino IDE for Blink LED.


Program:
void setup() {
pinMode(9,OUTPUT);
pinMode(11,OUTPUT);
pinMode(13,OUTPUT);
}
void loop() {
digitalWrite(9,HIGH);
delay(100);
digitalWrite(9,LOW);
delay(100);

digitalWrite(11,HIGH);
delay(100);

digitalWrite(11,LOW);
delay(100);

digitalWrite(13,HIGH);
delay(100);

digitalWrite(13,LOW);
delay(100);
}
Output:
LAB EXPERIMENT – 4

AIM: Write Program for RGB LED using Arduino.


Program:
void setup() {
pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
pinMode(11, OUTPUT);
}
void loop() {
digitalWrite(13, HIGH);
delay(1000);

digitalWrite(13, LOW);
delay(1000);

digitalWrite(12, HIGH);
delay(1000);

digitalWrite(12, LOW);
delay(1000);

digitalWrite(11, HIGH);
delay(1000);

digitalWrite(11, LOW);
delay(1000);
}
Output:
LAB EXPERIMENT – 2

AIM: Write a program for Buzzer using arduino.


Program:
const int buzPin = 13;
void setup() {
// Set the buzzer pin as an output
pinMode(buzPin, OUTPUT);
}
void loop() {
digitalWrite(buzPin, HIGH);
delay(1000);
digitalWrite(buzPin, LOW);
delay(100);
}

Output:
LAB EXPERIMENT – 13

AIM: Write a program for LDR.


Program:
const int ledPin = 12;
const int ldrPin = A0;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(ldrPin, INPUT);
}
void loop() {
int ldrStatus = analogRead(ldrPin);
Serial.println(ldrStatus);
if (ldrStatus <= 100) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}
Output:
LAB EXPERIMENT – 5

AIM: Write code for ultrasonic sensor using arduino.


Program:
int trigPin = 12;
const int echoPin = 13;

void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

long duration = pulseIn(echoPin, HIGH);

int distanceCM = duration * 0.034 / 2;

Serial.print("Distance: ");
Serial.print(distanceCM);
Serial.println(" cm");

delay(1000);
}
Output:
LAB EXPERIMENT – 15

AIM: Study the Temperature sensor and Write Program for monitor temperature using
Arduino.
Theory: LM35 Temperature Sensor is an integrated analog temperature sensor whose electrical
output is proportional to Degree Centigrade. LM35 Sensor does not require any external
calibration or trimming to provide typical accuracies. The LM35’s low output impedance,
linear output, and precise inherent calibration make interfacing to readout or control circuitry
especially easy.

LM35 Temperature Sensor

Features of LM35 Temperature Sensor:


• Calibrated directly in Degree Celsius (Centigrade)
• Linear at 10.0 mV/°C scale factor
• 0.5°C accuracy guarantee-able (at a25°C)
• Rated for full -55°C to a 150°C range
• Suitable for remote applications
• Low cost due to wafer-level trimming
• Operates from 4 to 30 volts
• Less than 60 mA current drain
• Low self-heating, 0.08°C instill air
• Non-linearity only 0.25°C typical
• Low impedance output, 0.1Ωfor 1 mA load

Program:
const int lm35Pin = A0;

30
void setup() {
Serial.begin(9600);
}
void loop() {
int sensorValue = analogRead(lm35Pin);

// Convert the analog value to temperature in Celsius


float temperatureCelsius = (sensorValue / 1024.0) * 500.0;

Serial.print("Temperature: ");
Serial.print(temperatureCelsius);
Serial.println(" degrees Celsius");
delay(1000);
}

Output:

31
LAB EXPERIMENT – 16

AIM: Study and Implement RFID, NFC using Arduino.


Theory: RFID (radio frequency identification) and NFC (near field communication) are both
wireless communication technologies that power the Internet of Things (IoT). The
technologies can be used in everything from access control to asset tracking to payment.

Code:
#include <SPI.h>
#include <MFRC522.h>
#define SS_PIN 10
#define RST_PIN 5
MFRC522 rfid(SS_PIN, RST_PIN);

void setup() {
Serial.begin(9600);
SPI.begin();
rfid.PCD_Init();
Serial.println("Tap RFID/NFC Tag on reader");
}

void loop() {
if (rfid.PICC_IsNewCardPresent()) {
if (rfid.PICC_ReadCardSerial()) {
MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);

32
//Serial.print("RFID/NFC Tag Type: ");
//Serial.println(rfid.PICC_GetTypeName(piccType));

Serial.print("UID:");
for (int i = 0; i < rfid.uid.size; i++) {
Serial.print(rfid.uid.uidByte[i] < 0x10 ? " 0" : " ");
Serial.print(rfid.uid.uidByte[i], HEX);
}
Serial.println();
rfid.PICC_HaltA();
rfid.PCD_StopCrypto1();
}
}
}

Output:
On Arduino IDE, Go to Tools -> Manage Libraries

Search “MFRC522”, then find the library by Github Community.


Click Install button to install MFRC522 library.

33
Run the above code and open with Arduino IDE.
Click Upload button on Arduino Ide to upload code to Arduino.
Open Serial Monitor.
Tap several RFID/NFC tags on RFID-RC522 module.
See UID on Serial Monitor.

34
LAB EXPERIMENT – 17

AIM: Study and implement MQTT protocol using Arduino.


Theory: 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! Write a Program for RGB
LED using Raspberry Pi.
Code:
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>

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

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...");
}
}

35
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);
}
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("");
}

Output:

36
LAB EXPERIMENT – 18

AIM: Study and Configure Raspberry Pi.


Theory: Raspberry Pi is defined as a minicomputer the size of a credit card that is interoperable
with any input and output hardware device like a monitor, a television, a mouse, or a keyboard
– effectively converting the set-up into a full-fledged PC at a low cost.
List of Raspberry pi models and releases year:
• pi 1 model B – 2012
• pi 1 model A – 2013
• pi 1 model B+ -2014
• pi 1 model A+ – 2014
• Pi 2 Model B – 2015
• Pi 3 Model B- 2016
• Pi 3 Model B+ -2018
• Pi 3 Model A+ -2019
• Pi 4 Model A – 2019
• Pi Model B – 2020
• Pi 400 – 2021

Specs of the Computer: – The computer has a quad-core ARM processor that doesn’t support
the same instruction as an X86 desktop CPU. It has 1GB of RAM, One HDMI port, four USB
ports, one Ethernet connection, Micro SD slot for storage, one combined 3.5mm audio/video
port, and a Bluetooth connection. It has got a series of input and output pins that are used for
making projects like – home security cameras, Encrypted Door lock, etc.

Raspberry Pi - Configuration
For configuring Raspberry Pi in Raspbian, we are using Raspbian with PIXEL desktop. It is
one of the best ways to get Raspbian started with the Raspberry Pi. Once we finish booting, we
will be in the PIXEL desktop environment.

37
Now to open the menu, you need to click the button that has the Raspberry Pi logo on it. This
button will be in the top left. After clicking the button, choose Raspberry Pi configuration from
the preferences.

Configuration tool
Following is the configuration tool in PIXEL desktop –

By default, the configuration tool opens to its system tab which has the following options −

• Change Password − The default password is raspberry. You can change it by clicking
the change password button.
• Change the hostname − The default name is raspberry pi. You can also change it to
the name, which you want to use on the network.
• Boot − You can choose from the two options and control whether Raspberry Pi boots
into the desktop or CLI i.e., command line interface.
• Auto Login − With the help of this option, you can set whether the user should
automatically log in or not.
• Network at Boot − By choosing this option, you can set whether the pi user is
automatically logged in or not.
• Splash screen − You can enable or disable it. On enabling, it will display the graphical
splash screen that shows when Raspberry Pi is booting.
• Resolution − With the help of this option, you can configure the resolution of your
screen.
• Underscan − There are two options, enable or disable. It is used to change the size of
the displayed screen image to optimally fill the screen. If you see a black border around

38
the screen, you should disable the underscan. Whereas, you should enable the
underscan, if your desktop does not fit your screen.
There are three other tabs namely Interfaces, Performance, and Localization. The job of
interface tab is to enable or disable various connection options on your Raspberry Pi.
You can enable the Pi camera from the interface tab. You can also set up a secure connection
between computers by using SSH (short for Secure Shell) option.
If you want to remote access your Pi with a graphical interface then, you can enable RealVNC
software from this tab. SPI, I2C, Serial, 1-wire, and Remote GPIO are some other interfaces
you can use.
There is another tab called Performance, which will give you access to the options for
overclocking and changing the GPU memory.
The localization tab, as the name implies, enable us to set −
• The character set used in our language.
• Our time zone.
• The keyboard setup as per our choice.
• Our Wi-Fi country.

Configure Wi-Fi
You can check at the top right, there would be icons for Bluetooth and Wi-Fi. The fan-shaped
icon is on the Wi-Fi. To configure your Wi-Fi, you need to click on that icon. Once clicked, it
will open a menu showing the available networks. It also shows the option to turn off your Wi-
Fi.
Among those available networks, you need to select a network. After selecting, it will prompt
for entering the Wi-Fi password i.e., the Pre Shared Key.
If you see a red cross on the icon, it means your connection has been failed or dropped. To test
whether your Wi-Fi is working correctly, open a web browser and visit a web page.

Configure Bluetooth Devices


We can use wireless Bluetooth devices such as keyboard and/or mouse with Pi 3 and Pi zero
W because these models are Bluetooth-enabled. In PIXEL desktop, you can set up your
Bluetooth devices easily.
• Following are the steps to configure the Bluetooth devices −
• First, make your device discoverable for pairing.
• Now, you need to click on the Bluetooth menu at the top right of the screen. It is aligned
to the Wi-Fi button.
• Now, choose the Add Device option.
• The Raspberry will start searching for the devices and when it finds your device, click
it and click the pair button.

39
Data Partition Setup
As we know that data partition is that area on your memory card (SD or MicroSD) which can
be shared by various distributions. One of the best examples of use of a data partition is
transferring the files between distributions.
The data partition has the label data.
You can use this labeled data to make a directory point to it as follows −

Step 1 − First, you need to boot the Raspberry Pi into Raspbian.


Step 2 − Now, click the Terminal icon to get to the command line.
Step 3 − Next, type the command mkdir shared. It will create a directory named shared.
Step 4 − Write the command sudo mount -L data shared. This command will point the directory
to the shared partition.
Step 5 − Write the command sudo chown $USER: shared. It will set the permission for writing
in this shared folder.
Step 6 − Now, to go to this shared folder, you need to type the command cd shared.
Once all the files are created in this shared folder, they will be available to all the distributions
that have the permission to access the data partition.

40
LAB EXPERIMENT – 7

AIM: WAP for LED blink using Raspberry Pi.


Program:
import Rpi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(4,GPIO.OUT)
GPIO.setup(5,GPIO.OUT)

while l:
print(“LED ON”)
GPIO.output(4,GPIO.HIGH)
GPIO.output(5.GPIO.HIGH)
Time.sleep(1)
print(“LED OFF”)
GPIO.output(4,GPIO.LOW)
GPIO.output(5.GPIO.LOW)
Time.sleep(1)

Output:

41
LAB EXPERIMENT – 20

AIM: Study and Implement ZIGBEE Protocol using Arduino / Raspberry Pi.
Theory: Zigbee is a standards-based wireless technology developed to enable low-cost, low-
power wireless machine-tomachine (M2M) and internet of things (IoT) networks. Zigbee is
for low-data rate, low-power applications and is an open standard.

In above circuit. TX and RX pin of zigbee and Arduino are connected to each other. Arduino
will send some instruction to zigbee and according to these instruction zigbee respond.
Similaryzigbee receive intructions from other zigbee to which it have address. After receiving
instructions or data from other zigbee. It send data to arduino through serial pins as shown in
connection. Similarly other module can be connected with one more Arduino or computer.
Same connection diagram is used for other zigbee and arduino pair.
Code:
void setup() {
Serial.begin(9600);
}

void loop() {
while (Serial.available()) {
Serial.write(Serial.read());
}
}
After connecting Arduino with it, upload the above code in Arduino, Arduino start receiving
whatever zigbee send to Arduino through serial communication.

42

You might also like