Professional Documents
Culture Documents
PRACTICAL FILE
Bachelor of Technology
In
Computer Science & Engineering
Of IKG Punjab Technical
University, Jalandhar
Outcomes: - Students will be able to understand IOT, Arduino/Raspberry Pi, and also ableto install
software setup of Arduino/Raspberry Pi.
Prerequisites- Fundamentals of Operating Systems
Hardware Requirement- Raspberry Pi Starter Kit, Ardunio Basic Kit
Software Requirement- can be installed on Linux and a stripped-down Internet-of-Things version
of Windows 10.
Introduction: -
“The Internet of Things (IoT) is the interconnection of uniquely identifiable embedded
computing devices within the existing Internet infrastructure. The Internet of Things connects
devices and vehicles using electronic sensors and the Internet.”
3|Page
The IoT is the network of physical objects devices, vehicles, buildings and other items embedded with
electronics, software, sensors, and network connectivity that enables these objects to collect and
exchange data. The IoT allows objects to be sensed and controlled remotely across existing network
infrastructure, creating opportunities for more direct integration of the physical world into computer
based systems, and resulting in improved efficiency, accuracy and economic benefit, when IoT is
augmented with sensors and actuators, the technology becomes an instance of the more general class of
cyber physical systems, which also encompasses technologies such as smart grids, smart homes,
intelligent transportation and smart cities. Each thing is uniquely identifiable through its embedded
computing system but is able to interoperate within the existing Internet infrastructure.
So, Internet of Things or IoT is an architecture that comprises specialized hardware boards, Software
systems, web APIs, protocols which together creates a seamless environment which allows smart
embedded devices to be connected to internet such that sensory data can be accessed and control system
can be triggered over internet.
Embedded Platform
Arduino---is probably the best starting point for embedded based IoT. Basic ArduinoBoards
don't come with Ethernet shield or Wi-Fi shield and for Arduino to be able towork as IoT
device, their need to select Arduino with Ethernet shield or Wi-Fi shield.Arduino run on the
other hand is a board that comes ported with Ethernet shield.
Raspberry Pi ---is probably one of the best things to happen in DIY (Do it yourself) IoT. A
wide range of Data driven applications like Home Automation Server to Home Multimedia
server, File Server can be developed with Pi. PI like Arduino has general purpose IO pins. But
seamless working with sensors is bit tedious in Pi. Another efficient IoT board is Intel Edition
which has integrated BLE, WiFi among host of other features. It supports wide range of
Industry standard hardware (over 30) through 70-pin interface (See Figure 2).
Discription of Raspberry Pi 3 Model B-
1. CPU: Raspberry Pi 3 uses Broadcom BCM2837 SOC 64-bit quad-core ARM Cortex A53
(ARMv8 CPU) with 512KB shared L2 cache.
2. Memory: Provided with 1 GB of RAM
3. Wi-Fi Support: 802.11n Wireless LAN
4. Bluetooth: Supports Bluetooth 4.1 Bluetooth Low Energy (BLE)
5. USB Ports: 4-USB ports which allow attaching four different USB devices like keyboard,
mouse, etc.
6. Ethernet Port: Standard Ethernet port to quickly setup and access internet. This can be very
useful when we want to setup raspberry pi for the first time without a monitor.
7. GPIO Pins: Raspberry Pi 3 supports 40 GPIO Pins General Purpose Input Output. These digital
input/output pins can be used to drive LED, Switches, and Sensors etc.
8. Full HDMI Port: Support HDMI port (High-Definition Multimedia Interface) which can be
used to quickly connect raspberry pi to HDMI Monitor. With HDMI Cable and Monitor we can
add Screen to Raspberry Pi.
9. Micro SD card slot: The Micro SD Card will hold the operating system which will boot while
we power on Raspberry Pi 3.
10. Audio/Video: Combined 3.5mm audio jack and composite video
11. Display interface (DSI): enable us to interface Display Module
12. Camera interface (CSI): enable us to interface Camera Module
13. Graphics Support: VideoCore IV 3D graphics core for advance graphics capabilities. 4|Page
14. Ethernet Port: Standard Ethernet port to quickly setup and access internet. This can be very
useful when we want to setup raspberry pi for the first time without a monitor.
15. GPIO Pins: Raspberry Pi 3 supports 40 GPIO Pins General Purpose Input Output. These digital
input/output pins can be used to drive LED, Switches, andSensors etc.
16. Full HDMI Port: Support HDMI port (High-Definition Multimedia Interface) which can be
used to quickly connect raspberry pi to HDMI Monitor. With HDMI Cable and Monitor we can
add Screen to Raspberry Pi.Micro SD card slot: The Micro SD Card will hold the operating
system which will boot while we power on Raspberry Pi 3.
17. Audio/Video: Combined 3.5mm audio jack and composite video
18. Display interface (DSI): enable us to interface Display Module
19. Camera interface (CSI): enable us to interface Camera Module
20. Graphics Support: VideoCore IV 3D graphics core for advance graphics capabilities.
5|Page
Raspberry Pi Downloads - Software for the Raspberry Pi
Raspberry Pi OS(previously called Raspbian) is our official operating system for all models of the
Raspberry Pi. Use Raspberry Pi Imager for an easy way to install Raspberry Pi OS and other
operating systems to an SD card ready to use with your Raspberry Pi:
Version: 1.4
Install Raspberry Pi Imager to Raspberry Pi OS by running sudo apt install rpi-imager in a
terminal window
RECOVERY
If your Raspberry Pi 4 will not boot, it is possible that the SPI EEPROM has become
corrupted. To check, remove the SD card, disconnect the device from power, then reconnect
it. If the green LED does not flash, this indicates that the EEPROM has become corrupted.
Raspberry Pi Imager provides an easy way to fix this problem, by automatically preparing an
SD card that will reprogram your Raspberry Pi 4’s EEPROM:
1. Find an SD card that is empty, or does not contain any data you want to
keep; it will be completely erased of all data during this process.
2. Download Raspberry Pi Imager for your operating system from the
list near the top of this page.
3. Click “CHOOSE OS” and select “Misc utility images” then “Pi EEPROM
boot recovery”.
4. Insert an SD card, click “CHOOSE SD CARD”, select the card you have
inserted, then click “WRITE”.
5. Once the SD card is ready, insert it into your Raspberry Pi 4 then
connect the Raspberry Pi to power.
6. Once complete, the green LED will blink rapidly in a steady pattern. Disconnect
the device from power. Now you can remove the recovery SD card, insert your
usual SD card, and resume using your Raspberry Pi.
Alternatively, you can download the bootloader and create a recovery SD card manually:
6|Page
Raspberry Pi Desktop (for PC and Mac)
Debian with Raspberry Pi Desktop is the Foundation’s operating system for PC and Mac.You can
create a live disc, run it in a virtual machine, or even install it on your computer.
Internet of Things :
The Internet of things (IoT) is defined as the network of physical objects, things that are embedded with
sensors, software, and other technologies for the purpose of connecting and exchanging data with other
devices and systems over the Internet.
So, Internet of Things or IoT is an architecture that comprises specialized hardware boards, Software
systems, web APIs, protocols which together creates a seamless environment which allows smart
embedded devices to be connected to internet such that sensory data can be accessed and control system
can be triggered over internet.
Arduino---is probably the best starting point for embedded based IoT. Basic Arduino Boards don't
come with Ethernet shield or Wi-Fi shield and for Arduino to be able to work as IoT device, their need
to select Arduino with Ethernet shield or Wi-Fi shield. Arduino run on the other hand is a board that
comes ported with Ethernet shield.
Arduino Pin Diagram:
9|Page
Circuit Diagram:
Program:
#include <LiquidCrystal.h> // includes the LiquidCrystal Library
LiquidCrystal lcd(1, 2, 4, 5, 6, 7); // Creates an LCD object. Parameters: (rs, enable, d4, d5, d6, d7)
const int trigPin = 9; const int
echoPin = 10; long duration;
int distanceCm, distanceInch; void
setup() {
lcd.begin(16,2); // Initializes the interface to the LCD screen, and specifies the dimensions (width and
height) of the display
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() { digitalWrite(trigPin,
LOW); delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distanceCm= duration*0.034/2; distanceInch
= duration*0.0133/2;
lcd.setCursor(0,0); // Sets the location at which subsequent text written to the LCD will be
displayed
lcd.print("Distance: "); // Prints string "Distance" on the LCD
lcd.print(distanceCm); // Prints the distance value from the sensor
lcd.print(" cm");
delay(10);
lcd.setCursor(0,1);
lcd.print("Distance: ");
lcd.print(distanceInch);
lcd.print(" inch"); delay(10);
}
10 | P a g e
EXPERIMENT NO. 3
Requirements:
1. Arduino board
2. Breadboard
3. LED – any color
4. Push button
5. 220 Ohm resistor for the LED. If you don’t have this specific value, any resistor from 330
to 1k Ohm will do
6. 10k Ohm resistor for the push button. If you don’t have, you can go until 20k-50k Ohm
7. A bunch of male to male wires (including if possible black, red, and other colors).
Procedure:
1. First, make sure to power off your Arduino – remove any USB cable.
2. Plug a black wire between the blue line of the breadboard and a ground (GND) pin on the
Arduino board.
3. Plug the LED. You can notice that the LED has a leg shorter than the other. Plug this shorter leg
to the ground (blue line here) of the circuit.
4. Connect the longer leg of the LED to a digital pin (here pin no 8, you can change it). Add a 220
Ohm resistor in between to limit the current going through the LED.
5. Add the push button to the breadboard, like in the picture.
6. Connect one leg of the button to the ground, and put a 10k Ohm resistor in between. This
resistor will act as a “pull down” resistor, which means that the default button’s state will be
LOW.
7. Add a red wire between another leg of the button and VCC (5V).
8. Finally, connect a leg of the button (same side as the pull down resistor) to a digital pin (here
7).
Circuit Diagram:
11 | P a g e
Code:
#define LED_PIN 8
setup() {
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT);
void loop() {
HIGH);
else {
digitalWrite(LED_PIN, LOW);
12 | P a g e
EXPERIMENT NO. 4(a)
AIM: - To interface DHT11 sensor with Arduino/Raspberry Pi and write a program to print
temperature and humidity readings.
DHT11 Temperature and Humidity Sensor: The DHT11 is a basic, ultra-low-cost digital
temperature and humidity sensor. It uses a capacitive humidity sensor and a thermistor to
measure the surrounding air, and spits out a digital signal on the data pin (no analog input pins
needed). It’s fairly simple to use, but requires careful timing to grab data.
DHT11 sensor provides humidity value in percentage in relative humidity (20 to 90% RH) and
temperature values in degree Celsius (0 to 50 °C) DHT11 sensor uses resistive humidity
measurement component, and NTC temperature measurement component.
Pin 1: DC voltage Here, we will connect the DC voltage pin to 5V on the Arduino UNO board.
Pin 2: Analog voltage output, we will consider the Analog voltage output pin as the output.
Pin 3: GND, we will connect the GND pin to Ground on the Arduino UNO board
Requirements:
1. Breadboard,
2. Arduino Uno R3,
3. DHT22, TMP 36 temperature sensor
4. 10K ohm resistor
5. LCD display,
6. Jump wires.
Procedure:
1. Connect the RS pin of LCD to pin 13 of the Arduino board.
2. Connect the Enable pin of LCD to pin 12 of the Arduino board.
3. Connect the D4 pin of LCD to pin 6 of the Arduino board.
4. Connect the D5 pin of LCD to pin 4 of the Arduino board.
5. Connect the D6 pin of LCD to pin 3 of the Arduino board.
6. Connect the D7 pin of LCD to pin 2 of the Arduino board.
7. Connect the Vo pin of LCD to pin 8 of the Arduino board.
8. Connect the middle terminal to a sensor to A0(analog pin).
9. Connect one end of the sensor to GND and another end to 5V.
10. Connect one end of a resistor to the A and K of the LCD and another end to 5V.
13 | P a g e
Circuit Diagram:
Code:
#include <LiquidCrystal.h>
lcd.begin(16, 2);
Serial.begin(9600);
pinMode(D, OUTPUT); }
void loop() {
digitalWrite(D,LOW);
= (Temp / 965.0) * 5;
lcd.print(fahrenheit);
Result: 14 | P a g e
The output is now visible on the LCD screen.
Requirements:
1. Arduino UNO R3 CH340 (you can use any Arduino Boards)
2. Ultrasonic Sensor HC-SR04
3. Male to Male Jumper Wires
4. Breadboard
Procedure:
1. First do the wiring as shown in the circuit diagram.
2. Open Arduino IDE Software and write down your code, or download the code below and open
it.
3. Choose your own Arduino board (in this case Arduino Uno), by selecting Tools > Board >
Arduino/Geniuno Uno
4. Choose your COM Port (usually it appears only one existing port), Tools > Port > COM.. (If
there are more than one ports, try it one by one)
5. Upload your code by pressing Ctrl + U or Sketch > Upload
6. To display the measurement data you can use Serial Monitor by pressing Ctrl + Shift + M (make
sure that the baudrate speed is 9600)
Code:
#include <LiquidCrystal.h> // includes the LiquidCrystal Library
LiquidCrystal lcd(1, 2, 4, 5, 6, 7); // Creates an LCD object. Parameters: (rs, enable, d4, d5, d6,
d7)
const int trigPin = 9; const
int echoPin = 10; long
duration;
int distanceCm, distanceInch; void
setup() { 15 | P a g e
lcd.begin(16,2); // Initializes the interface to the LCD screen, and specifies the dimensions (width
and height) of the display
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() { digitalWrite(trigPin,
LOW); delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distanceCm= duration*0.034/2;
distanceInch = duration*0.0133/2;
lcd.setCursor(0,0); // Sets the location at which subsequent text written to the LCD will be
displayed
lcd.print("Distance: "); // Prints string "Distance" on the LCD
lcd.print(distanceCm); // Prints the distance value from the sensor lcd.print("
cm");
delay(10); lcd.setCursor(0,1);
lcd.print("Distance: ");
lcd.print(distanceInch);
lcd.print(" inch"); delay(10);
}
16 | P a g e
EXPERIMENT NO. 5
Requirements:
1. Arduino board and Arduino IDE software
2. Servo Motor
3. Push button
4. 10k Ohm resistor for the push button.
5. A bunch of male to male wires (including if possible black, red, and other colors).
Servo Motor: A servo motor is a rotary actuator that allows for precise control of angular position. It
consists of a motor coupled to a sensor for position feedback. It also requires a servo drive to complete
the system. The drive uses the feedback sensor to precisely control the rotary position of the motor.
Procedure:
1. First, make sure to power off your Arduino – remove any USB cable.
2. Plug the Servo Motor. Plug this shorter leg to the ground (blue line here) of the circuit.
3. First add the header file for servo motor and declare a variable to call the Servo motor.
4. In void setup() function, declare the Servo pin by the "attach()" function, in this we use the Arduino digital
pin 3 to this purpose. Then we need to set the pin to read the pushbutton, as "INPUT"
5. In the void loop() function we need to use if and else to make a diction. When the push-button is pressed the
output of the push-button be logic LOW. This push-button output is read by digitalRead() function. Here we
use the Arduino Uno Digital pin 2 is used to this purpose. Then write the servo to 180 degree.
Circuit Diagram:
17 | P a g e
Code:
include<Servo.h> Servo
Myservo; int pos=0;
void setup()
{
pinMode(2,INPUT);
Myservo.attach(3);
}
void loop()
{
if(digitalRead(2)==LOW)
{ Myservo.write(180);
}
else
Myservo.write(0);
}
18 | P a g e
EXPERIMENT NO. 6
Requirements:
1. Arduino board
2. SSD1306 OLED screen (128×64 Pixel)
3. DHT11/DHT22 temperature and humidity sensor
4. 4.7k ohm resistor
5. Jumper wires
OLED Screen: The SSD1306 is a 128×64 dot single chip driver with a controller that's used for
graphic display systems. It's commonly integrated into OLED display modules like the one seen above
for Arduino, Raspberry Pi, or other microcontroller usages. The OLED (Organic Light- Emitting
Diode) display is an alternative for LCD display. The OLED is super-light, almost paper-thin, flexible,
and produce a brighter and crisper picture.
Procedure:
1. Connect the SSD1306 OLED GND pin to Arduino GND (ground).
2. Connect the SSD1306 OLED VDD pin to Arduino 5V.
3. Connect the SSD1306 OLED SDA pin (serial data) to pin A4 (Arduino UNO I2C SDA pin).
4. Connect the SSD1306 OLED SCK pin (serial clock) to pin A5 (Arduino UNO I2C SCL pin).
5. Connect the SSD1306 OLED RES pin (reset) to Arduino pin 4.
6. Connect the DHT11 data pin to Arduino pin 8.
Circuit Diagram:
19 | P a g e
Code:
#include <Wire.h> #include
<Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);
setup(void) {
// by default, we'll generate the high voltage from the 3.3v line internally! (neat!)
delay(1000);
display.clearDisplay();
display.setTextColor(WHITE, BLACK);
display.setCursor(10, 5);
display.print("DHT11 TEMPERATURE:");
20 | P a g e
display.setCursor(19, 37);
display.print("DHT11 HUMIDITY:");
display.display();
void loop() {
// Read humidity
byte RH = dht.readHumidity();
Temp = dht.readTemperature();
= RH % 10 + 48;
display.setCursor(46, 20);
display.print(temperature);
display.setCursor(46, 52);
display.print(humidity);
display.display();
delay(1000);
21 | P a g e
EXPERIMENT NO. 7
Bluetooth is one of the most popular wireless communication technologies because of its low power
consumption, low cost and a light stack but provides a good range. In this, data from a DHT-11 sensor is
collected by an Arduino and then transmitted to a smartphone via Bluetooth.
Requirements:
1. Arduino Board and Arduino IDE
2. An Android Smartphone that has Bluetooth
3. HC-05 Bluetooth Module
4. Android Studio (To develop the required Android app)
5. USB cable for programming and powering the Arduino
6. DHT-11 temperature and humidity sensor.
Working:
To use the HC-05 Bluetooth module, simply connect the VCC to the 5V output on the Arduino, GND
to Ground, RX to TX pin of the Arduino, and TX to RX pin of the Arduino. If the module is being used
for the first time, you’ll want to change the name, passcode etc. To do this the module should be set
to command mode. Connect the Key pin to any pin on the Arduino and set it to high to allow the
module to be programmed.
Circuit Diagram:
22 | P a g e
Code:
#include "DHT.h" #define DHTPIN 2
void setup() {
Serial.begin(9600);
dht.begin();}
void loop()
{ char c; if(Serial.available())
{
c = Serial.read(); if(c=='t')
readSensor(); }}
void readSensor() {
dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
23 | P a g e
EXPERIMENT NO. 8
3. LED
4. Resister.
Introduction: Experiment use Arduino and Bluetooth Module HC-05 to control a LED light. In this
experiment, we will use an Android smartphone to send Bluetooth signal to the Bluetooth module.
Working:
In this experiment main components are an Android Smartphone, Bluetooth transceiver, and an
Arduino.
The Android app is built to send serial data to the Bluetooth Module HC-05 by pressing ON button.
As Bluetooth Module HC-05 works on serial communication. It receives the data from the app and
sends it through TX pin of Bluetooth module to RX pin of Arduino. The uploaded code inside
Arduino checks the data received. If the receive data is 1, the LED turns ON, and if the received data
is 0 the LED turns OFF.
Connect Led Pin1 with Ground and Led pin 2 with Arduino pin 13.
the Vcc pin Tx with Arduino pin 5v. Connect the Hc-05
24 | P a g e
Circuit Diagram:
Code:
char data = 0; //Variable for storing received data void
setup() {
}
void loop() {
{
data = Serial.read(); //Read the incoming data and store it into variable
}
25 | P a g e
EXPERIMENT NO. 9
Requirements:
1. ESP32 Node Mcu and Arduino IDE
2. DHT11 – Temperature and Humidity Sensor
3. Micro USB Cable
4. Bread Board
5. Connecting Wires
Node MCU ESP32: ESP32 is in the series of low power and low cost on chip microcontroller. It comes up
with already integrated dual mode Bluetooth and Wi-Fi. ESP32 comes up with a USB port so we can say
that it is a plug and play device i.e. just plug in cable and your device is turned on and you are able to
program it just like Arduino development boards.
1. Built in Wi-Fi module of standard 802.11 and Wi-Fi module operate in range of 2.4 GHz – 2.5
2. GHz.
3. Three modes of operation: 1. Access point. 2. Client. 3. Access point + station.
4. Dual core microprocessor of 32 – bit.
5. Operating voltage is 3.3 V and Clock frequency from 80 MHz and goes up to 240 MHz.
6. SRAM memory is of 512 KB and ROM memory is 448 KB.
7. External flash memory is supported and is up to 32 Mb i.e. 4MB.
8. It has 36 general purpose input / output pins.
9. General purpose input / output pins comes up with PWM / I2C and SPI functionality.
10. Bluetooth version 4.2 is available and Bluetooth low energy (BLE) version and its having 2 to
11. 3.6 V operating voltage.
Procedure:
1. For creating your channel on ThingSpeak you first need to sign up on ThingSpeak. In case if you
already have account on ThingSpeak just sign in using your id and password.
For creating your account go to www.thinspeak.com
26 | P a g e
1. Create a Channel for Your Data
After clicking on “New Channel”, enter the Name and Description of the data you want to
upload on this channel. For example I am sending DHT11 sensor data (temperature and
humidity), so I named it as “DHT11”.
Enter the name of your data ‘Temperature’ in Field1 and ‘Humidity’ in Field2. If you want
to use more thanone Field you can check the box next to Field option and enter the name and
description of your data.
After this click on save channel button to save your details.
2. API Key: To send data to ThingSpeak, we need an unique API key, which we will use later
in our code to upload the Temperature and Humidity to ThingSpeak Website. Click on “API
Keys” button to get your unique API key for uploading DHT11 sensor data.
Now copy your “Write API Key”. We will use this API key in our code. After this, navigate to
your Thingspeak page and open your channel in ThingSpeak and output will be shown as
below.
27 | P a g e
Circuit Diagram:
Code:
#include <DHT.h> #include
<ESP8266WiFi.h>
String apiKey = "Your API KEY"; // Enter your Write API key here const
char *ssid = "WiFi Name"; // Enter your WiFi Name
const char *pass = "WiFi Password"; // Enter your WiFi Password const
char* server = "api.thingspeak.com";
#define DHTPIN 4 // GPIO Pin where the dht11 is connected DHT
dht(DHTPIN, DHT11);
WiFiClient client; void setup() {
Serial.begin(115200);
delay(10); dht.begin();
Serial.println("Connecting to ");
Serial.println(ssid); WiFi.begin(ssid,
pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(550); Serial.print(".");
} Serial.println("");
Serial.println("WiFiconnected");
}
void loop()
float h = dht.readHumidity();
28 | P a g e
float t = dht.readTemperature(); if
(isnan(h) || isnan(t))
{
Serial.println("Failed to read from DHT sensor!"); return;
}
if (client.connect(server,80)) {
String postStr = apiKey;
postStr +="&field1="; postStr
+= String(t); postStr
+="&field2="; postStr +=
String(h); postStr += "\r\n\r\
n";
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n"); client.print("Content-
Type: application/x-www-form-urlencoded\n"); client.print("Content-
Length: ");
client.print(postStr.length());
client.print("\n\n");
client.print(postStr);
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(h);
client.stop();
Serial.println("Waiting...");
delay(10000);
29 | P a g e
EXPERIMENT NO. 10
ThingSpeak: ThingSpeak™ is an IoT analytics platform service that allows you to aggregate,
visualize and analyze live data streams in the cloud. ThingSpeak provides instant visualizations of data
posted by your devices to ThingSpeak.
ThingSpeak enables sensors, instruments, and websites to send data to the cloud where it is stored in
either a private or a public channel. ThingSpeak stores data in private channels by default, but public
channels can be used to share data with others.
ThingSpeak provides instant visualizations of data posted by your devices to ThingSpeak. With the
ability to execute MATLAB® code in ThingSpeak you can perform online analysis and processing of
the data as it comes in. ThingSpeak is often used for prototyping and proof of concept IoT systems that
require analytics.
In previous experiment we saw how data collecting from sensor is sent to thingspeak cloud. In this
experiment we will find how data is retrieving from thingspeak cloud.
Procedure:
Steps to retrieve temperature and humidity data from thingspeak cloud:
30 | P a g e
1. Sign in to ThingSpeak using your MATLAB account.
2. Select Channels > My Channels.
3. Select the channel from which to read data.
4. Click the Channel Settings tab and copy the channel ID from the Channel ID parameter.
5. Open the ThingSpeak Read block in your model and paste the copied ID to the Channel ID
parameter.
You can read data from your ThingSpeak channels using the HTTP calls and the REST API. You can
use the MQTT subscribe method to receive messages whenever the channel is updated. And you can
use thingSpeakRead to read data from your channel in desktop MATLAB.
Code:
delay(10); dht.begin();
Serial.println("Connecting to ");
31 | P a g e
Serial.println(ssid); WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(550); Serial.print("."); }
Serial.println("");
Serial.println("WiFiconnected"); }
void loop() {
float h = dht.readHumidity();
float dht.readTemperature(); if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!"); return;
}
if (client.connect(server,80))
{ String postStr = apiKey;
postStr +="&field1=";
postStr += String(t);
postStr +="&field2=";
postStr += String(h);
postStr += "\r\n\r\n";
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length()); client.print("\n\n");
client.print(postStr);
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" degrees Celcius, Humidity: ");
Serial.print(h);
Serial.println("%. Send to Thingspeak.");
}
client.stop();
Serial.println("Waiting...");
delay(10000)}
32 | P a g e
EXPERIMENT NO. 11
MySQL is one of the world’s most popular relational database system and is a common inclusion in
most LAMP ( Linux, Apache, MYSQL, and PHP) stacks. It is one of the pieces of technology that helps
drive the modern web.
A database such as MYSQL is often a key component of dynamic websites and is one of the best ways
of storing data for web applications.Arduino DHT22 Humidity Sensor
If you’re unfamiliar with MySQL, it is a relational database management system and allows you
to store and maintain large amounts of data easily.
Setup something like PHPMyAdmin if you want a graphical user interface rather than the command line.
It does make managing a database slightly easier.
You will need to go through this tutorial for setting up any web server project that requires a database.
For example, we use it in our WordPress tutorial.
Requirements:
1. Raspberry Pi
2. Micro SD Card
3. Power Supply
4. Ethernet Cable or Wi-Fi
Procedure:
1. Before we get started with installing MySQL to our Raspberry Pi, we must first update our
package list and all installed packages.
We can do this by running the following two commands. sudo apt update sudo apt upgrade Copy
2. The next step is to install the MySQL server software to your Raspberry Pi.
Installing MySQL to the Raspberry Pi is a simple process and can be done with the following
command.
3. With the MySQL server software installed to the Raspberry Pi, we will now need to secure it
by setting a password for the “root” user.
By default, MySQL is installed without any password set up meaning you can access the MySQL
server without any authentication.
33 | P a g e
Run the following command to begin the MySQL securing process.
sudomysql_secure_installation Copy
Just follow the prompts to set a password for the root user and to secure your MySQL
installation.
For a more secure installation, you should answer “Y” to all prompts when asked to answer “Y” or
“N“.
These prompts will remove features that allows someone to gain access to the server easier.
Make sure you write down the password you set during this process as we will need to use it to access
the MySQL server and create databases and users for software such as WordPress or PHPMyAdmin.
4. Now if you want to access your Raspberry Pi’s MySQL server and start making changes to your
databases, you can enter the following command.
5. You will be prompted to enter the password that we just created in step 3 for MySQL’s root
user.
Note: Like most Linux password inputs, the text will not show up as you type.
6. You can now enter MYSQL commands to create, alter, and delete databases. Through this
interface, you can also create or delete users and assign them the rights to manage any database.
7. There are two different ways you can quit out of the MYSQL command line, the first of those
is to type “quit;” into the MySQL interface.
The other way of quitting out of the MYSQL command line is to press CTRL + D.
8. At this point, you will now have successfully setup MySQL on your Raspberry Pi. Our next few
sections will go into making better use of this database.
1. Before we proceed to create a MySQL user and database on our Raspberry Pi, we must first log
back into the MySQL command-line tool.
Run the following command to log in to the MySQL command line. You will be prompted to
enter the password for the “root” account that you set up earlier
34 | P a g e
This command is super simple and is just “CREATE DATABASE” followed by the name that
you want to give the database.
3. Next, we will create a MySQL user that we will assign to our new database. We can create this user
by running the following command.
For this example, we will be calling the user “exampleuser” and giving it the password
“pimylifeup“. When creating your own, make sure you replace both of these.
4. With the user created, we can now go ahead and grant all privileges to the user so that it can
interact with the database.
This command will grant all permissions to our “exampleuser” for all tables within our
“exampledb” database.
GRANT ALL PRIVILEGES ON exampledb.* TO 'exampleuser'@'localhost';
Copy
5. The final thing we need to do for both our MySQL database and user to be finalized is to flush the
privilege table. Without flushing the privilege table, the new user won’t be able to access the database.
We can do this by running the following command.
FLUSH PRIVILEGES;
Copy
If you rather not use the command line to administrate your databases then you can always install
PHPMyAdmin instead.
Installing the PHP MySQL Connector
1. If you intend on using a MySQL database from PHP, you will need to make sure that you have the
module installed.
You can install the MySQL connector for PHP to your Raspberry Pi by running the following command.
sudo apt install php-mysql Copy
As I mentioned earlier, there are many projects where a database will come in handy. Most
modern websites will require a database to be able to function correctly.
At this point of the tutorial you should now have a MySQL server up and running on your
Raspberry Pi
35 | P a g e
EXPERIMENT NO. 12
ThingsBoard is an open-source server-side platform that allows you to monitor and control IoT
devices. It is free for both personal and commercial usage and you can deploy it anywhere. If this is
your first experience with the platform we recommend to reviewwhat-is-thingsboard page and getting-
started guide.
This sample application performs collection of temperature and humidity values produced by DHT22
sensor and further visualization on the real-time web dashboard. Collected data is pushed via MQTT
to ThingsBoard server for storage and visualization. The purpose of this application is to demonstrate
ThingsBoarddata collection API and visualization capabilities.
The DHT22 sensor is connected to Raspberry Pi.
Raspberry Pi offers a complete and self-contained Wi-Fi networking solution. Raspberry Pi push data
to ThingsBoard server via MQTT protocol by using pahomqtt python library. Data is visualized using
built-in customizable dashboard. The application that is running on Raspberry Pi is written in Python
which is quite simple and easy to understand.
Prerequisites
The alternative option is to install ThingsBoard using Installation Guide. Windows users should
follow this guide. Linux users that have docker installed should execute the following
mkdir -p ~/.mytb-data && sudo chown -R 799:799 ~/.mytb-data
1mkdir -p ~/.mytb-logs && sudo chown -R 799:799 ~/.mytb-logs 2
docker run -it -p 9090:9090 -p 7070:7070 -p 1883:1883 -p 5683-5688:5683-5688/udp -v
43 ~/.mytb-data:/data \
5 -v ~/.mytb-logs:/var/log/thingsboard --name mytb --restart always thingsboard/tb-postgres
These commands install ThingsBoard and load demo data and accounts.
36 | P a g e
Requirements:
1. Raspberry Pi 3
2. DHT22 sensor
Wiring schemes:
Finally, place a resistor (between 4.7K and 10K) between pin number 1 and 2 of the DHT
sensor. The following picture summarizes the connections for this project:
ThingsBoard configuration
NoteThingsBoard configuration steps are necessary only in case of local ThingsBoard
installation. If you are using Live Demo instance all entities are pre-configured for your demo
account. However, we recommend reviewing this steps because you will still need to get
device access token to send requests to ThingsBoard.
36 page
Once device created, open its details and click “Manage credentials”. Copy auto-generated
access token from the “Access token” field. Please save this device token. It will be referred
to later as $ACCESS_TOKEN.
Click “Copy Device ID” in device details to copy your device id to the clipboard. Paste your
device id to some place, this value will be used in further steps.
The following command will install MQTT Python library: sudo pip install paho-mqtt
Our application consists of a single python script that is well documented. You will need to
modify THINGSBOARD_HOST constant to match your ThingsBoard server installation IP
address or hostname. Use “demo.thingsboard.io” if you are using live demo server.
The value of ACCESS_TOKEN constant corresponds to sample DHT22 demo device. If you
are using live demo server - get the access token for pre-provisioned “DHT22 Demo Device”.
import os import
time import sys
import Adafruit_DHT as dht
import paho.mqtt.client as
mqtt import json
THINGSBOARD_HOST = 'demo.thingsboard.io'
ACCESS_TOKEN = 'DHT22_DEMO_TOKEN'
# Data capture and upload interval in seconds. Less interval will eventually hang the
DHT22.
INTERVAL=2
sensor_data = {'temperature': 0, 'humidity':
0} next_reading = time.time()
client = mqtt.Client()
# Set access token
client.username_pw_set(ACCESS_TOKEN)
# Connect to ThingsBoard using default MQTT port and 60 seconds keepalive interval
client.connect(THINGSBOARD_HOST, 1883, 60)
client.loop_star
t() try:
while True:
humidity,temperature = dht.read_retry(dht.DHT22, 4)
humidity = round(humidity, 2)
temperature = round(temperature, 2)
print(u"Temperature: {:g}\u00b0C, Humidity: {:g}
%".format(temperature, humidity))
sensor_data['temperature'] = temperature
sensor_data['humidity'] = humidity
next_reading += INTERVAL
sleep_time = next_reading-
time.time()
if sleep_time> 0: 38 page
time.sleep(sleep_time)
except
KeyboardInterrupt:
pass
client.loop_stop()
client.disconnect()
Finally, open ThingsBoard Web UI. You can access this dashboard by logging in as a
tenant administrator.
In case of local installation:
login: tenant@thingsboard.org
password: tenant
Go to “Devices” section and locate “DHT22 Demo Device”, open device details and switch to
“Latest telemetry” tab. If all is configured correctly you should be able to see latest values of
“temperature” and “humidity” in the table.
After, open “Dashboards” section then locate and open “DHT22: Temperature & Humidity
Demo Dashboard”. As a result you will see two digital gauges and two time-series charts
displaying temperature and humidity level
39 page