15CS81 IoT Module 5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 49
At a glance
Powered by AI
The document discusses Internet of Things and Arduino boards. It explains the different Arduino boards like UNO, Mega, Micro etc and the components of Arduino UNO board.

The document discusses Arduino Mega, Micro, MKR100 and Flora boards in addition to the popular Arduino UNO board.

The major components of the Arduino UNO board discussed are the microcontroller, analog and digital pins, reset switch, crystal oscillator, USB interface chip and power sources.

Internet of Thins -15CS81 2020

MAHARAJA INSTITUTE OF TECHNOLOGY MYSORE


Department of Computer Science and Engineering
Module 5 Notes
8th Semester
Subject: Internet of Things Subject Code: 15CS81

Introduction to Arduino
Arduino is an open-source advancement prototyping platform which depends on
simple to-utilize equipment and programming. Arduino can read inputs- such as detecting
the power of light, events triggered by a Button or a twitter message and can respond into
a yield, for example, run the engine, on the LED, send data though online. You can tell your
board what to do by sending a set of instructions to the microcontroller on the board. It is
like the brain of a project.

The Arduino is a small computer that you can program to read information from the
world around you and to send commands to the outside world. All of this is possible
because you can connect several devices and components to the Arduino to do what you
want. You can do amazing projects with it, there is no limit for what you can do, and using
your imagination everything possible.

Arduino is a tiny computer that you can connect to electrical circuits. This makes it
easy to read inputs – read data from the outside – and control outputs- send a command to
the outside. The brain of this board( Arduino Uno) is an ATmega328p chip where you can
store your programs that will tell your Arduino what to do.

Why Arduino?

 Arduino is an open source product, software/hardware which is accessible and


flexible to customers.
 Arduino is flexible because of offering variety of digital and analog pins, SPI and
PWM outputs.
 Arduino is easy to use, connected to a computer via a USB and communicates using
serial protocol.
 Inexpensive, around 500 rupees per board with free authoring software.
 Arduino has growing online community where lots of source code is available for
use, share and post example for others to use too, too!
 Arduino is Cross-platform, which can work on Windows, Mac or Linux platforms.
 Arduino follows Simple, clear programming environment as C language.

Which Arduino?

In the years since Arduino was released, hundreds of ―Arduino boards‖ are
available in the market serving every kind of purpose. We focus on popular Arduino UNO
which is used in almost 99% of projects use.
Some of the Boards from Arduino family are given below:
Arduino Mega is a big sister to the UNO with more memory and pins with a different
chip the ATmega2560, useful when your project doesn‘t fits in an UNO.

1 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

Arduino Micro is it smaller with a chip Atmega32u4 that can act like a keyboard or
mouse which does its task native USB. Its slim with download pins which can be plugged
into a breadboard.
The Arduino MKR100 is a little like an Arduino Micro but has a more powerful32-bit ATSAM
ARM chip and build-in WiFi!. A great upgrade for when you want to do Internet of Thing
projects.
Flora is an Arduino compatible from Adafruit which is a round wearable which can be
sewed into clothing.

Exploring Arduino UNO Learning Board


In the figure below you can see an Arduino Board labelled. Let‘s see what each part
does.

The major components of Arduino UNO board are as follows:


 USB connector
 Power port
 Microcontroller
 Analog input pins
 Digital pins
 Reset switch
 Crystal oscillator
 USB interface chip
 TX RX LEDs

USB connector:

USB connector
This is a printer USB port used to load a program from the Arduino IDE onto the Arduino board. The
board can also be powered through this port.

2 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

Power port:

Power port
The Arduino board can be powered through an AC-to-DC adapter or a battery. The power source
can be connected by plugging in a 2.1mm center-positive plug into the power jack of the board.

2.1mm center-positive plug


The Arduino UNO board operates at a voltage of 5 volts, but it can withstand a maximum voltage of
20 volts. If the board is supplied with a higher voltage, there is a voltage regulator (it sits between
the power port and USB connector) that protects the board from burning out.

Microcontroller:

Atmega328P microcontroller
It is the most prominent black rectangular chip with 28 pins. Think of it as the brains of your
Arduino. The microcontroller used on the UNO board is Atmega328P by Atmel ( a major
microcontroller manufacturer). Atmega328P has the following components in it:
 Flash memory of 32KB. The program loaded from Arduino IDE is stored here.
 RAM of 2KB. This is a runtime memory.
 CPU: It controls everything that goes on within the device. It fetches the program
instructions from flash memory and runs them with the help of RAM.
 Electrically Erasable Programmable Read Only Memory (EEPROM) of 1KB. This is a
type of nonvolatile memory, and it keeps the data even after device restart and reset.
Atmega328P is pre-programmed with bootloader. This allows you to directly upload a new Arduino
program into the device, without using any external hardware programmer, making the Arduino
UNO board easy to use.

3 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

Analog input pins:

Analog input pins


The Arduino UNO board has 6 analog input pins, labeled ―Analog 0 to 5.‖ These pins can
read the signal from an analog sensor like a temperature sensor and convert it into a digital value
so that the system understands. These pins just measure voltage and not the current because they
have very high internal resistance. Hence, only a small amount of current flows through these pins.

Although these pins are labeled analog and are analog input by default, these pins can also be
used for digital input or output.

Digital pins:

Digital pins
You can find these pins labeled ―Digital 0 to 13.‖ These pins can be used as either input or output
pins. When used as output, these pins act as a power supply source for the components connected
to them. When used as input pins, they read the signals from the component connected to them.
When digital pins are used as output pins, they supply 40 milliamps of current at 5 volts, which is
more than enough to light an LED.
Some of the digital pins are labeled with tilde (~) symbol next to the pin numbers (pin numbers 3,
5, 6, 9, 10, and 11). These pins act as normal digital pins but can also be used for Pulse-Width
Modulation (PWM), which simulates analog output like fading an LED in and out.

Reset switch:

Reset switch
When this switch is clicked, it sends a logical pulse to the reset pin of the Microcontroller, and now
runs the program again from the start. This can be very useful if your code doesn‘t repeat, but you
want to test it multiple times.

4 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

Crystal oscillator:

Crystal oscillator
This is a quartz crystal oscillator which ticks 16 million times a second. On each tick, the
microcontroller performs one operation, for example, addition, subtraction, etc.

USB interface chip:

USB interface chip


Think of this as a signal translator. It converts signals in the USB level to a level that an Arduino UNO
board understands.

TX – RX LEDs:

TX – RX indicator
TX stands for transmit, and RX for receive. These are indicator LEDs which blink whenever the UNO
board is transmitting or receiving data.

When set as inputs, these pins can read voltage. They can only read two different states HIGH or
LOW. When set as outputs, these pins can apply voltage. They can only apply 5V (HIGH) or OV
(LOW)
Things that Arduino can do
 The simplest thing you can control with your Arduino is an LED
 You can also display a message in a display, like the LCD display.
 You can also control DC or servo motors.
 You can also Read data from the outside world.
5 Dept. of CSE MIT Mysore
Internet of Thins -15CS81 2020

 Motion sensor: The motion sensor allows you detect movement.


 Light sensor: this allows you to ―measure‖ the quality of light in the outside world.
 Humidity and temperature sensor: this is used to measure the humidity and temperature.
 Ultrasonic sensors: this sensors allows to determine the distance to an object through sonar.
 Shields – an extension of the Arduino.
 Shields are boards that will expand the functionalities of your Arduino. You just need to plug
them over the top of the Arduino. There are countless types of shields to do countless tasks.

Installing the Software (Arduino IDE)


The Arduino IDE (Integrated Development Environment) is where you develop your
programs that will tell your Arduino what to do.
You can load new program onto the main chip, the ATmega328p, via USB using the Arduino IDE. To
download your Arduino IDE, browse on the following link:
https://www.arduion.cc/en/Main/Software. Select which Operating System you‘re using and
download it. We won‘t go into much detail on how to install this software, since the official Arduino
web site does a great job explaining how to do it in all three operating Systems- Windows, Mac and
Linux.

Figure: Arduino IDE

Connecting Arduino Uno Learning Board


After connecting your Arduino with a USB cable, you need to make sure that Arduino IDE
has selected the right board you are using. In our case, we‘re using Arduino Uno, so you go to
Tool>Board: ― Arduino/Genuino Uno‖> Arduino/Genuino as shown in figure below:

6 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

Figure: Selecting the right board

Then, you should select the right port as show in the figure below.

Serial Port
COM3 (Arduino/Genuine)

Figure: Selecting the right port

Figure below shows the layout of Arduino IDE.


7 Dept. of CSE MIT Mysore
Internet of Thins -15CS81 2020

The Toolbar buttons and functions of each button are as shown in the below table.
Verify / Compile Check the code for errors
Stop Stop the serial monitor, or un-highlight other buttons
New Create a new blank sketch, enter a name and a location for your sketch
Open Shows a list of Sketches in your sketchbook
Upload Uploads the current Sketch to the Arduino. You need to make sure that
you have the current board and port selected before uploading.
Serial Monitor Display Serial data being sent from the Arduino
Verify/ Compile Button is used to check that your code is correct, before you upload it to
your Arduino.
Stop button Will stop the Serial Monitor from operating. If you need to obtain a
snapshot of the serial data so far.

Breadboard for prototyping Arduino Uno Circuits


In order to keep your circuit organized you need to use a breadboard, pictured below in
figure. The breadboard allows you to connect components together by plugging them into the little
holes. The key is to understand how the holes are connected.

As we can see in the diagram, the holes in a column are connected together. So to connect
components together you need to plug the leads you want connected into the same column. Note

8 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

that the columns are not connected across the ―trench‖ in the center of the board. Also notice that
as the long rows at the top and bottom are connected together.
These are typically used to create ―rails‖. These are typically used for ground and supply voltage
you might need to connect many components to. Notice some rows are marked (+) and some (-).
These are just marking.

Arduino Uno Technical Specifications


Technical Specification

Microcontroller ATmega328P – 8 bit AVR family microcontroller

Operating Voltage 5V

Recommended Input Voltage 7-12V

Input Voltage Limits 6-20V

Analog Input Pins 6 (A0 – A5)

Digital I/O Pins 14 (Out of which 6 provide PWM output)

DC Current on I/O Pins 20 mA

DC Current on 3.3V Pin 50 mA

Flash Memory 32 KB ATmega328P (0.5 KB is used for Bootloader)

SRAM 2 KB (ATmega328P)

EEPROM 1 KB (ATmega328P)

Frequency (Clock Speed) 16 MHz

Fundamentals of Arduino Programming


Below table explains the basic structure of Arduino programming with respect to usage of
variables, constants, control flow statements and finally the predefined functions used to read
analog and digital inputs.
Structure The structure of Arduino programming contains of two parts as shown below:

void setup( ) // Preparation function used to declare variables


{ // first function that runs only one in the program
statements-1;
.
..
statement-n;
}
void loop ( ) // Execution block where instructions are executed repeatedly
{ // this is the core of the Arduino programming
statement-1; // Functionalities involve reading inputs, triggering outputs etc.
.
.
.
statement-n;
}

void setup() void setup ( )


{
pinMode (pin-number, OUTPUT); // set the ‗pin-number‘ as output

9 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

pinMode (pin-number, INPUT); // set the ‗pin-number‘ as output


}

void loop() // After calling setup(), loop() function does its task.
Void loop ( )
{
digitalWrite (pin-number,HIGH); // turns ON the component connected to ‗pin-
number‘
delay (1000); // wait for 1 sec
digitalWrite (pin-number, LOW); // turns OFF the component connected to ‗pin-
number‘
delay (1000); //wait for 1sec
}
Note: Arduino always measures the time duration in millisecond. Therefore, whenever
you mention the delay, keep it in mili seconds.
Functions A function is piece of code that has a name and se of statements executed when
function is called. Functions are declared by its type followed with name of a
function.
Syntax:

Example:
int sum_func (int x, int y) // function declaration
{
int z = 0;
z = x+y ;
return z; // return the value
}
{ } curly They define beginning and end of function blocks, unbalanced braces may lead to
braces compile errors.
semicolon It is used to end a statement and separate elements of a program.
Syntax: int x =14;
/* ….. */ Multiple comments begin with /* with a description of the block and ends with */
block Example:
comments /* This is a valid comment */
// Line Single line comment begin with //
comments Example:
// single line comment is OK inside a multiline comment
Variables A variable is a way of naming and storing a value for later use by the program, such as
data from a sensor or an intermediate value used in a calculation.
Local Variables
Variables that are declared inside a function or block are local variables. They can be
used only by the statements that are inside that function or block of code. Local variables
are not known to function outside their own. Following is the example using local
variables

10 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

Void setup () {

Void loop () {
int x , y ;
int z ; Local variable declaration
x = 0;
y = 0; actual initialization
z = 10;
}
Global Variables
Global variables are defined outside of all the functions, usually at the top of the
program. The global variables will hold their value throughout the life-time of your
program.
A global variable can be accessed by any function. That is, a global variable is available
for use throughout your entire program after its declaration.
The following example uses global and local variables −
Int T , S ;
float c = 0 ; Global variable declaration

Void setup () {

Void loop () {
int x , y ;
int z ; Local variable declaration
x = 0;
y = 0; actual initialization
z = 10;
}

Data Types Data Type Syntax Range


Byte byte x = 100; 0-255
Int int y = 200; -32768 to 32767
Long long var=8000; from -2,147,483,648 to
2,147,483,647
Float float x=3.14; -3.4028235E38 to 3.4028235E38
Array int myarray[] = {1,2,3}; Size depends on the data type
associated with declaration
 boolean (8 bit) - simple logical true/false
 byte (8 bit) - unsigned number from 0-255
 char (8 bit) - signed number from -128 to 127. The compiler will attempt to interpret
this data type as a character in some circumstances, which may yield unexpected
results
 unsigned char (8 bit) - same as 'byte'; if this is what you're after, you should use 'byte'
instead, for reasons of clarity
 word (16 bit) - unsigned number from 0-65535
 unsigned int (16 bit)- the same as 'word'. Use 'word' instead for clarity and brevity
 int (16 bit) - signed number from -32768 to 32767. This is most commonly what you
see used for general purpose variables in Arduino example code provided with the
IDE
 unsigned long (32 bit) - unsigned number from 0-4,294,967,295. The most common
usage of this is to store the result of the millis() function, which returns the number of
milliseconds the current code has been running
 long (32 bit) - signed number from -2,147,483,648 to 2,147,483,647
 float (32 bit) - signed number from -3.4028235E38 to 3.4028235E38. Floating point on
the Arduino is not native; the compiler has to jump through hoops to make it work.
Operators An operator is a symbol that tells the compiler to perform specific mathematical or
logical functions. C language is rich in built-in operators and provides the following
types of operators −

11 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

 Arithmetic Operators
 Comparison Operators
 Boolean Operators
 Bitwise Operators
 Compound Operators
Arithmetic Operators
Assume variable A holds 10 and variable B holds 20 then −
Operator name Operator Description Example
simple

Stores the value to the right of the


assignment
= equal sign in the variable to the left A=B
operator
of the equal sign.

A + B will
addition + Adds two operands
give 30

Subtracts second operand from the A - B will


subtraction -
first give -10

A * B will
multiplication * Multiply both operands
give 200

B / A will
division / Divide numerator by denominator
give 2

Modulus Operator and remainder B % A will


modulo %
of after an integer division give 0
Comparison Operators
Assume variable A holds 10 and variable B holds 20 then −
Operator Operator Description Example
name simple

Checks if the value of two operands is


(A == B) is
equal to == equal or not, if yes then condition
not true
becomes true.

Checks if the value of two operands is


(A != B) is
not equal to != equal or not, if values are not equal
true
then condition becomes true.

Checks if the value of left operand is


(A < B) is
less than < less than the value of right operand, if
true
yes then condition becomes true.

Checks if the value of left operand is


greater than the value of right (A > B) is
greater than >
operand, if yes then condition not true
becomes true.

Checks if the value of left operand is


less than or less than or equal to the value of right (A <= B) is
<=
equal to operand, if yes then condition true
becomes true.

Checks if the value of left operand is


greater than or greater than or equal to the value of (A >= B) is
>=
equal to right operand, if yes then condition not true
becomes true.
Boolean Operators
Assume variable A holds 10 and variable B holds 20 then −
12 Dept. of CSE MIT Mysore
Internet of Thins -15CS81 2020

Operator Operator Description Example


name simple

Called Logical AND operator. If both the


(A && B) is
and && operands are non-zero then then condition
true
becomes true.

Called Logical OR Operator. If any of the


(A || B) is
or || two operands is non-zero then then
true
condition becomes true.

Called Logical NOT Operator. Use to


reverses the logical state of its operand. If !(A && B) is
not !
a condition is true then Logical NOT false
operator will make false.
Bitwise Operators
Assume variable A holds 60 and variable B holds 13 then −
Operator Operator Description Example
name simple

(A & B) will
Binary AND Operator copies a bit to the give 12
and &
result if it exists in both operands. which is
0000 1100

(A | B) will
Binary OR Operator copies a bit if it exists give 61
or |
in either operand which is
0011 1101

(A ^ B) will
Binary XOR Operator copies the bit if it is give 49
xor ^
set in one operand but not both. which is
0011 0001

(~A ) will
Binary Ones Complement Operator is give -60
not ~
unary and has the effect of 'flipping' bits. which is
1100 0011

Binary Left Shift Operator. The left A << 2 will


operands value is moved left by the give 240
shift left <<
number of bits specified by the right which is
operand. 1111 0000

Binary Right Shift Operator. The left A >> 2 will


operands value is moved right by the give 15
shift right >>
number of bits specified by the right which is
operand. 0000 1111
Compound Operators
Assume variable A holds 10 and variable B holds 20 then −
Operator name Operator Description Example
simple

Increment operator, increases A++ will give


increment ++
integer value by one 11

Decrement operator, decreases


decrement -- A-- will give 9
integer value by one

13 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

Add AND assignment operator. It


B += A is
compound adds right operand to the left
+= equivalent to B
addition operand and assign the result to
= B+ A
left operand

Subtract AND assignment operator.


B -= A is
compound It subtracts right operand from the
-= equivalent to B
subtraction left operand and assign the result
=B-A
to left operand

Multiply AND assignment operator.


B*= A is
compound It multiplies right operand with the
*= equivalent to B
multiplication left operand and assign the result
= B* A
to left operand

Divide AND assignment operator.


B /= A is
compound It divides left operand with the
/= equivalent to B
division right operand and assign the result
=B/A
to left operand

Modulus AND assignment


B %= A is
compound operator. It takes modulus using
%= equivalent to B
modulo two operands and assign the result
=B%A
to left operand

compound bitwise inclusive OR and A |= 2 is same


|=
bitwise or assignment operator as A = A | 2

compound A &= 2 is same


&= Bitwise AND assignment operator
bitwise and as A = A & 2
Flow Control Statements
if if (expression)
{
Block of statements; // Evaluated only if expression
//results in a true value
}
Ex:
if (A > B) /* if condition is true then execute the following statement*/
A++;
if…else An if statement can be followed by an optional else statement, which executes when the
expression is false.
if (expression)
{
Block of statements;
}
else
{
Block of statements;
}

Ex:
if (A > B) /* if condition is true then execute the following statement*/
{
A++;
}
else
{
B -= A;
}

for A for loop executes statements a predetermined number of times. The control

14 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

expression for the loop is initialized, tested and manipulated entirely within the for loop
parentheses.
Syntax:
for ( initialize; control; increment or decrement)
{
// statement block
}
Ex:
for(counter = 1;counter <= 9;counter++)
{
//statements block will executed 10 times
}
while while loops will loop continuously, and infinitely, until the expression inside the
parenthesis, () becomes false. Something must change the tested variable, or the while
loop will never exit.
Syntax:
while(expression)
{
Block of statements;
}
Ex:
var = 0;
while (var < 200)
{
// do something repetitive 200 times
var++;
}
Do-while The do…while loop is similar to the while loop. In the while loop, the loop-continuation
condition is tested at the beginning of the loop before performed the body of the loop.
The do…while statement tests the loop-continuation condition after performed the loop
body. Therefore, the loop body will be executed at least once.
Syntax:
do
{
Block of statements;
}while (expression);
int x = 0;
do
{
delay(50); // wait for sensors to stabilize
x = readSensors(); // check the sensors
} while (x < 100);
Digital and Analog input output pins and their usage
Digital i/o Method Usage
pinMode (pin , mode); The pinMode() function is used to configure a specific pin to
behave either as an input or an output. It is possible to enable
the internal pull-up resistors with the mode INPUT_PULLUP.
Additionally, the INPUT mode explicitly disables the internal
pull-ups.
 pin − the number of the pin whose mode you wish to
set
 mode − INPUT, OUTPUT, or INPUT_PULLUP.
Digital Write(pin, digitalWrite() Function
value) The digitalWrite() function is used to write a HIGH or a LOW
value to a digital pin. If the pin has been configured as an
OUTPUT with pinMode()
Ex:
digitalWrite(LED,HIGH); // turn on led

Digital Read(pin) Example:


Read value from a specified pin with result being HIGH/LOW
Val=digital Read(pin)
Val will be equal to input pin
Sets pin 13 to the same value as pin 7, declared as an input.
15 Dept. of CSE MIT Mysore
Internet of Thins -15CS81 2020

int ledPin = 13; // LED connected to digital pin 13


int inPin = 7; // pushbutton connected to digital pin 7
int val = 0; // variable to store the read value

void setup() {
pinMode(ledPin, OUTPUT); // sets the digital pin 13 as output
pinMode(inPin, INPUT); // sets the digital pin 7 as input
}

void loop() {
val = digitalRead(inPin); // read the input pin
digitalWrite(ledPin, val); // sets the LED to the button's value
}
Analog i/o Methods Usage
analogRead(pin); By using the analogRead() function, we can read the voltage
applied to one of the pins.
pin − the number of the analog input pin to read from (0 to 5 on
most boards, 0 to 7 on the Mini and Nano, 0 to 15 on the Mega)
val = analogRead(analogPin); // read the input pin

analogWrite(pin, Writes an analog value using pulse width modulation


value); (PWM).
analogWrite(pin, value)
pin: the Arduino pin to write to. Allowed data types: int.
value: the duty cycle: between 0 (always off) and 255
(always on). Allowed data types: int.
const int pwm = 2 ; //naming pin 2 as ‗pwm‘ variable
const int adc = 0 ; //naming pin 0 of analog input side as ‗adc‘
void setup()
{
pinMode(pwm,OUTPUT) ; //setting pin 2 as output
}
void loop()
{
int adc = analogRead(0) ; //reading analog voltage and
//storing it in an integer
// adc = map(adc, 0, 1023, 0, 255);
analogWrite(pwm,adc) ;
}
time Methods Usage
delay (ms) ; The way the delay() function works is pretty simple. This
number represents the time (measured in milliseconds). The
program should wait until moving on to the next line of code
when it encounters this function.
Ex:
delay(1000); // waits for a second

millis () ; This function is used to return the number of milliseconds at the


time, the Arduino board begins running the current program.
time = millis();
//prints time since program started
Serial.println(time);

math Methods Usage


min(x,y); Find minimum of two numbers
Val = min(Val, 10);
max(x,y); Find maximum of two numbers
Val = max(Val, 10);
random Methods Usage
The function randomSeed(seed) resets Arduino‘s
randomSeed (val) pseudorandom number generator.

16 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

random(min, max) The random function generates pseudo-random numbers from


min to max
Example long randNumber;
void setup()
{
randomSeed(analogRead(0));
randNumber = random(300);
Serial.println(randNumber);
// print a random number from 0to 299
Serial.print("random2=");
randNumber = random(10, 20);
// print a random number from 10 to 19
Serial.println (randNumber);
delay(50);
}
Serial Methods Usage
Serial.begin(rate); Sets the data rate in bits per second (baud) for serial
data transmission.
void setup()
{
Serial.begin(9600); // opens serial port, sets data
//rate to 9600 bps
}
Serial.println(val); Prints data to the serial port as human -readable ASCII
Serial.println(val, text followed by a carriage return character (ASCII 13,
format); or '\r') and a newline character (ASCII 10, or ' \n').

This command takes the same forms as Serial.print().

Serial: serial port object. See the list of available serial


ports for each board on the Serial main page.
val: the value to print. Allowed data types: any data
type.
format: specifies the number base (for integral data
types) or number of decimal places (for floating point
types).

Physical Devices and Endpoints - RaspberryPi: Introduction to


RaspberryPi
Introduction to RaspberryPi
The Raspberry Pi is a series of credit card sized single-board computers developed in
the United Kingdom by the Raspberry Pi Foundation to promote teaching of basic computer
science in schools and in developing countries. The original model became far more popular than
anticipated, selling outside its target market for uses such as robotics. It now is widely used even
in research projects, such as for weather monitoring because of its low cost and portability. It does
not include peripherals (such as keyboards and mice) or cases. However, some accessories have
been included in several official and unofficial bundles.
Several generations of Raspberry Pis have been released.
The first generation (Raspberry Pi 1 Model B) was released in February 2012, followed by the simpler
and cheaper Model A. In 2014, the Foundation released a board with an improved design, Raspberry
Pi 1 Model B+. These boards are approximately credit-card sized and represent the
standard mainline form-factor. Improved A+ and B+ models were released a year later. A "Compute
Module" was released in April 2014 for embedded applications. The Raspberry Pi 2, which added
more RAM, was released in February 2015.
A Raspberry Pi Zero with smaller size and reduced input/output (I/O) and general-purpose
input/output (GPIO) capabilities was released in November 2015 for US$5. On 28 February 2017,
the Raspberry Pi Zero W was launched, a version of the Zero with Wi-Fi and Bluetooth capabilities, for
US$10. On 12 January 2018, the Raspberry Pi Zero WH was launched, a version of the Zero W with pre-
soldered GPIO headers.

17 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

Raspberry Pi 3 Model B was released in February 2016 with a 1.2 GHz 64-bit quad core processor, on-
board 802.11n Wi-Fi, Bluetooth and USB boot capabilities. On Pi Day 2018 the Raspberry Pi 3
Model B+ was launched with a faster 1.4 GHz processor and a three-times faster gigabit
Ethernet (throughput limited to ca. 300 Mbit/s by the internal USB 2.0 connection) or 2.4 / 5 GHz dual-
band 802.11ac Wi-Fi (100 Mbit/s). Other features are Power over Ethernet (PoE) (with the add-on PoE
HAT), USB boot and network boot (an SD card is no longer required).
Raspberry Pi 4 Model B was released in June 2019 with a 1.5 GHz 64-bit quad core ARM Cortex-
A72 processor, on-board 802.11ac Wi-Fi, Bluetooth 5, full gigabit Ethernet (throughput not limited),
two USB 2.0 ports, two USB 3.0 ports, and dual-monitor support via a pair of micro HDMI (HDMI Type D)
ports for up to 4K resolution . The Pi 4 is also powered via a USB-C port, enabling additional power to be
provided to downstream peripherals, when used with an appropriate PSU. The initial Raspberry Pi 4
board has a design flaw where third-party e-marked USB cables, such as those used on Apple
MacBooks, incorrectly identify it and refuse to provide power. Tom's Hardware tested 14 different
cables and found that 11 of them turned on and powered the Pi without issue.
All models feature a Broadcom system on a chip (SoC) with an integrated ARM-compatible central
processing unit (CPU) and on-chip graphics processing unit (GPU).
Processor speed ranges from 700 MHz to 1.4 GHz for the Pi 3 Model B+ or 1.5 GHz for the Pi 4;
on-board memory ranges from 256 MiB to 1 GiB random-access memory (RAM), with up to 4 GiB
available on the Pi 4. Secure Digital (SD) cards in MicroSDHC form factor (SDHC on early models) are
used to store the operating system and program memory. The boards have one to five USB ports. For
video output, HDMI and composite video are supported, with a standard 3.5 mm tip-ring-sleeve jack for
audio output. Lower-level output is provided by a number of GPIO pins, which support common
protocols like I²C. The B-models have an 8P8C Ethernet port and the Pi 3, Pi 4 and Pi Zero W have on-
board Wi-Fi 802.11n and Bluetooth.
Why Raspberry Pi?
Inexpensive, Cross-platform, Simple, clear programming environment, Open Source and
extensible software and Open Source and extensible hardware.
Technical Specification of Raspberry Pi Models
Raspberry Pi Model A+ Model B Model B+ 2, Model B Model 3
Quick Cheapest, The original More USB and Most Newest with
Summary smallest single Raspberry Pi. GPIIO than the advanced wireless
board B. Ideal choice Raspberry Pi. connectivity
computer for schools
Chip Broadcom BCM 2835 Broadcom Broadcom
BCM2836 BCM2837
Processor ARMv6 single core ARMv7 quad 4xARM
core Cortex-A53
Processor 700 MHz 900 MHz 1.2GHz
Speed
Voltage and 600mA @ 5V 650mA @ 5V
power draw
GPU Dual core Videocore IV Multimedia Co-Processor Broadcom
Videocone IV
Size 65x56 mm 85x56mm
Memory 256 MB 512 MB SDRAM @ 400MHZ 1GB 1GB
SDRAM @ SDRAM @ LPDDR2 @
400MHZ 400MHZ 900MHZ
Storage Micro SD Card SD Card Micro SD Card Micro SD Card Micro SD Card
GPIO 40 26 40
USB 2.0 1 2 4
Ethernet None 10/100 MB Ethernet RJ45 Jack
Wireless None 2.4 GHz
802.11n
wireless
Bluetooth None Bluetooth
4.1 Classic,
Bluetooth low

18 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

Energy
Audio Multi-Channel HD Audio over HDMI, Analog Stream from 3.5mm Headphone Jack
Operating Raspbian RaspBMC, Arch Linux, Rise OS, OpenEl EC Pidora
System
Video Output HDMI Composite RCA
Supported 640x480 to 1920X1200, including 1080p, PAL & NTSC standards
Resolutions
Power Source Micro USB

Exploring the Raspberry Learning Board

Processor
The Broadcom BCM2835 SoC used in the first generation Raspberry Pi includes a
700 MHz ARM1176JZF-S processor, VideoCore IV graphics processing unit (GPU),and RAM. It has a
level 1 (L1) cache of 16 KiB and a level 2 (L2) cache of 128 KiB. The level 2 cache is used primarily
by the GPU. The SoC is stacked underneath the RAM chip, so only its edge is visible. The
ARM1176JZ(F)-S is the same CPU used in the original iPhone,although at a higher clock rate, and
mated with a much faster GPU.
The earlier V1.1 model of the Raspberry Pi 2 used a Broadcom BCM2836 SoC with a
900 MHz 32-bit, quad-core ARM Cortex-A7 processor, with 256 KiB shared L2 cache.
The Raspberry Pi 3 Model B uses a Broadcom BCM2837 SoC with a 1.2 GHz 64-bit quad-core ARM
Cortex-A53 processor, with 512 KiB shared L2 cache. The Model A+ and B+ are 1.4 GHz.
The Raspberry Pi 4 uses a Broadcom BCM2711 SoC with a 1.5 GHz 64-bit quad-core ARM
Cortex-A72 processor, with 1 MiB shared L2 cache.Unlike previous models, which all used a
custom interrupt controller poorly suited for virtualization, the interrupt controller on this SoC is
compatible with the ARM Generic Interrupt Controller (GIC) architecture 2.0, providing hardware
support for interrupt distribution when using ARM virtualization capabilities.

19 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

Power Source
Recommended and easiest way to power the Raspberry Pi is via the Micro USB port on the
side of the unit. The recommended input voltage is 5V, and the recommended input current is 2A.
The Raspberry Pi can function on lower current power supplies e.g. 5V @ 1A. However, any
excessive use of the USB ports or even heavy CPU/GPU loading can cause the voltage to drop, and
instability during use. he latest versions of the Raspberry Pi B+/A+/2 have a ―low voltage indicator
icon‖ to notify the user if there is a problem with the power. Most ―standard‖ 5V Micro-USB mobile
phone, tablet, and digital camera chargers should work with the Raspberry Pi, although we (of
course) would recommend that you utilise a high quality dedicated Raspberry Pi power supply to
get the best results!.

SD Card
Raspberry Pi does not have any locally available storage accessible. The working
framework is stacked on a SD card which is embedded on the SD card space on the Raspberry Pi.

GPIO (stands for General Purpose Input Output)


The Raspberry Pi has two rows of GPIO pins, which are connections between the Raspberry Pi, and
the real world.
Output pins are like switches that the Raspberry Pi can turn on or off (like turning on/off a LED
light). But it can also send a signal to another device.
Input pins are like switches that you can turn on or off from the outside world (like a on/off
light switch). But it can also be a data from a sensor, or a signal from another device.
There are two ways of numbering the IO pins on a Raspberry Pi within RPi.GPIO. The first is
using the BOARD numbering system. This refers to the pin numbers on the P1 header of the
Raspberry Pi board. The advantage of using this numbering system is that your hardware will
always work, regardless of the board revision of the RPi. You will not need to rewire your
connector or change your code.
The second numbering system is the BCM numbers. This is a lower level way of working - it
refers to the channel numbers on the Broadcom SOC. You have to always work with a diagram of
which channel number goes to which pin on the RPi board. Your script could break between
revisions of Raspberry Pi boards.
GPIO.setmode(GPIO.BOARD)
# or
GPIO.setmode(GPIO.BCM)

DSI Display X
The Raspberry Pi connector S2 is a display serial interface (DSI) for connecting a liquid
crystal display (LCD) panel using a 15-pin ribbon cable. The mobile industry processor
interface (MIPI) inside the Broadcom BCM2835 IC feeds graphics data directly to the display panel
through this connector. This article looks at the connector pinout, and some of the display panels
compatible with the port.

Audio Jack
A standard 3.5 mm TSR connector is accessible on the RPi for stereo sound. Any earphone or
3.5 sound link can be associated straightforwardly.

Status LEDs
The Model B has five status LEDs labelled ―OK‖, ―PWR‖, ―FDX‖, ―LNK‖ and ―10M‖.
The LEDs have the following meanings :
OK/ACT Green SD card activity
PWR Red Power
FDX Green Full Duplex (LAN) connected
LNK Green Link/Activity (LAN)
10M/100 Yellow 100Mbit (LAN) connected

20 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

The LEDs have the following meanings:


 ACT – D5 (Green) – SD Card Access
 PWR – D6 (Red) – 3.3 V Power is present
 FDX – D7 (Green) – Full Duplex (LAN) connected
 LNK – D8(Green) – Link/Activity (LAN)
 100 – D9(Yellow) – 100Mbit (LAN) connected

Ethernet Port
Ethernet port is accessible on Model B and B+. The Ethernet ports are controlled by
Microchip LAN9512 LAN controller chip.

CSI Connector (CSI)


Pi Camera module is a camera which can be used to take pictures and high definition video.
Raspberry Pi Board has CSI (Camera Serial Interface) interface to which we can attach PiCamera
module directly.This Pi Camera module can attach to the Raspberry Pi‘s CSI port using 15-pin
ribbon cable.

JTAG header
Joint Test Action Group, also known as JTAG, is the common name for IEEE standard 1149.1.
This standard defines a particular method for testing board-level interconnects, which is also called
Boundary Scan. In short, JTAG was created as a way to test for common problems, but lately has
become a way of configuring devices.

HDMI
Raspberry Pi can now be used to capture an HDMI audio video input.

Description of System on Chip (SoC)


A system on a chip (SoC) is an integrated circuit (also known as a "chip") that integrates all
or most components of a computer or other electronic system. These components almost always
include a central processing unit (CPU), memory, input/output ports and secondary storage – all on
a single substrate or microchip, the size of a coin.[1] It must contain digital, analog, mixed-signal,
and often radio frequency signal processing functions, otherwise it will only be considered as an
"Application Processor". As they are integrated on a single substrate, SoCs consume much less
power and take up much less area than multi-chip designs with equivalent functionality.
An SoC usually contains various components such as:
Operating system
Utility software applications
Voltage regulators and power management circuits
Timing sources such as phase lock loop control systems or oscillators
A microprocessor, microcontroller or digital signal processor
Peripherals such as real-time clocks, counter timers and power-on-reset generators
External interfaces such as USB, FireWire, Ethernet, universal asynchronous receiver-
transmitter or serial peripheral interface bus
Analog interfaces such as digital-to-analog converters and analog-to-digital converters
RAM and ROM memory

Accessories
Gertboard – A Raspberry Pi Foundation sanctioned device, designed for educational
purposes, that expands the Raspberry Pi's GPIO pins to allow interface with and control of LEDs,
switches, analogue signals, sensors and other devices. It also includes an
optional Arduino compatible controller to interface with the Pi.
Camera – On 14 May 2013, the foundation and the distributors RS Components & Premier
Farnell/Element 14 launched the Raspberry Pi camera board alongside a firmware update to
accommodate it The camera board is shipped with a flexible flat cable that plugs into
the CSI connector which is located between the Ethernet and HDMI ports. In Raspbian, the user must
enable the use of the camera board by running Raspi-config and selecting the camera option. The
camera module costs €20 in Europe (9 September 2013). It can

21 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

produce 1080p, 720p and 640x480p video. The dimensions are 25 mm × 20 mm × 9 mm. In May 2016,
v2 of the camera came out, and is an 8 megapixel camera.
USB Hub-The 7-Port USB Hub for Raspberry Pi is a hub designed for Raspberry Pi. It extends
one USB port on Raspberry Pi to 7 usable USB ports, which allows you to connect much
more USB devices to your Raspberry Pi.

Raspberry Pi interface
The Serial Peripheral Interface (SPI) is a communication protocol used to transfer data
between micro-computers like the Raspberry Pi and peripheral devices. These peripheral devices
may be either sensors or actuators.
The Raspberry Pi SPI is an interface consisting of five pins.
- MISO (Master In Slave Out): Master Line for sending data to the peripherals.
- MOSI (Master out Slave In): Slave line for sending data to the master.
- SCK (Serial Clock): Clock generated by mater to synchronize data transmissions.
- CEO (Chip Enable 0): To enable or disable devices.
- CE0 (Chip Enable 1): To enable or disable devices.

I2C:
I2C is a multi-device bus used to connect low-speed peripherals to computers and
embedded systems. The Raspberry Pi supports this interface on its GPIO header and it is a great
way to connect sensors and devices. Once configured you can connect more than one device
without using up additional pins on the header.

Raspberry Pi Operating System:


The Raspberry Pi Foundation provides Raspbian, a Debian-based (32-bit) Linux
distribution for download, as well as third-party Ubuntu, Windows 10 IoT Core, RISC OS, and
specialised media centre distributions. It promotes Python and Scratch as the main programming
languages, with support for many other languages. The default firmware is closed source, while an
unofficial open source is available. Many other operating systems can also run on the Raspberry Pi.
Third-party operating systems available via the official website include Ubuntu MATE, Windows
10 IoT Core, RISC OS and specialised distributions for the Kodi media centre and classroom
management. The formally verified microkernel seL4 is also supported.
Other operating systems (not Linux-based)

 Broadcom VCOS – Proprietary operating system which includes an abstraction layer designed
to integrate with existing kernels, such as ThreadX (which is used on the VideoCore4
processor), providing drivers and middleware for application development. In case of
Raspberry Pi this includes an application to start the ARM processor(s) and provide the publicly
documented API over a mailbox interface, serving as its firmware. An incomplete source of
a Linux port of VCOS is available as part of the reference graphics driver published by
Broadcom.
 RISC OS Pi (a special cut down version RISC OS Pico, for 16 MiB cards and larger for all models
of Pi 1 & 2, has also been made available.)
 FreeBSD
 NetBSD
 OpenBSD (only on 64-bit platforms, such as Raspberry Pi 3)
 Plan 9 from Bell Labs and Inferno (in beta)
 Windows 10 IoT Core – a zero-price edition of Windows 10 offered by Microsoft that runs
natively on the Raspberry Pi 2.
 Haiku – an open source BeOS clone that has been compiled for the Raspberry Pi and several
other ARM boards. Work on Pi 1 began in 2011, but only the Pi 2 will be supported.
 HelenOS – a portable microkernel-based multiserver operating system; has basic Raspberry Pi
support since version 0.6.0

22 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

Other operating systems (Linux-based)

 Android Things – an embedded version of the Android operating system designed


for IoT device development.
 Arch Linux ARM – a port of Arch Linux for ARM processors.
 openSUSE
 SUSE Linux Enterprise Server 12 SP2
 SUSE Linux Enterprise Server 12 SP3 (Commercial support)
 Gentoo Linux
 Lubuntu
 Xubuntu
 Devuan
 CentOS for Raspberry Pi 2 and later
 RedSleeve (a RHEL port) for Raspberry Pi 1
 Slackware ARM – version 13.37 and later runs on the Raspberry Pi without modification. The
128–496 MiB of available memory on the Raspberry Pi is at least twice the minimum
requirement of 64 MiB needed to run Slackware Linux on an ARM or i386 system. (Whereas the
majority of Linux systems boot into a graphical user interface, Slackware's default user
environment is the textual shell / command line interface.) The Fluxbox window manager
running under the X Window System requires an additional 48 MiB of RAM.
 Kali Linux – a Debian-derived distro designed for digital forensics and penetration testing.
 SolydXK – a light Debian-derived distro with Xfce.
 Ark OS – designed for website and email self-hosting.
 Sailfish OS with Raspberry Pi 2 (due to use ARM Cortex-A7 CPU; Raspberry Pi 1 uses different
ARMv6 architecture and Sailfish requires ARMv7.)
 Tiny Core Linux – a minimal Linux operating system focused on providing a base system
using BusyBox and FLTK. Designed to run primarily in RAM.
 Alpine Linux – a Linux distribution based on musl and BusyBox, primarily designed for "power
users who appreciate security, simplicity and resource efficiency".
 postmarketOS - distribution based on Alpine Linux, primarily developed for smartphones.
 Void Linux – a rolling release Linux distribution which was designed and implemented from
scratch, provides images based on musl or glibc.
 Fedora – supports Pi 2 and later since Fedora 25 (Pi 1 is supported by some unofficial
derivatives, e.g. listed here.).
 OpenWrt – a highly extensible Linux distribution for embedded devices (typically wireless
routers). It supports Pi 1, 2, 3, 4 and Zero W.

Configuring RaspberryPi
To get started with Raspberry Pi, you need an operating system. NOOBS (New Out Of Box
Software) is an easy operating system install manager for the Raspberry Pi.
How to get and install NOOBS
Buy preinstalled SD card
SD cards with NOOBS preinstalled are available from many of our distributors and
independent retailers, such as Pimoroni, Adafruit and The Pi Hut. For older models of Raspberry Pi,
you‘ll need a full-size SD card; for the Raspberry Pi Zero, Zero W, A+, B+, Raspberry Pi 2,
Raspberry Pi 3, 3B+ and Raspberry Pi 4 you‘ll need a micro SD card.

Download
We recommend using an SD card with a minimum capacity of 16GB.
1. Using a computer with an SD card reader, visit the Downloads page.
2. Click on NOOBS, then click on the Download ZIP button under ‗NOOBS (offline and network
install)‘, and select a folder to save it to.
3. Extract the files from the zip.

Format your SD card


23 Dept. of CSE MIT Mysore
Internet of Thins -15CS81 2020

It is best to format your SD card before copying the NOOBS files onto it. To do this:
1. Visit the SD Association‘s website and download SD Formatter 4.0 for either Windows or Mac.
2. Follow the instructions to install the software.
3. Insert your SD card into the computer or laptop‘s SD card reader and make a note of the drive
letter allocated to it, e.g. G:/
4. In SD Formatter, select the drive letter for your SD card and format it.

Drag and drop NOOBS files


1. Once your SD card has been formatted, drag all the files in the extracted NOOBS folder and
drop them onto the SD card drive.
2. The necessary files will then be transferred to your SD card.
3. When this process has finished, safely remove the SD card and insert it into your Raspberry Pi.

First boot
1. Plug in your keyboard, mouse, and monitor cables.
2. Now plug the USB power cable into your Raspberry Pi.
3. Your Raspberry Pi will boot, and a window will appear with a list of different operating systems
that you can install. We recommend that you use Raspbian – tick the box next to Raspbian and
click on Install.
4. Raspbian will then run through its installation process. Note that this can take a while.
5. When the install process has completed, the Raspberry Pi configuration menu (raspi-config) will
load. Here you are able to set the time and date for your region, enable a Raspberry Pi camera
board, or even create users. You can exit this menu by using Tab on your keyboard to move
to Finish.

Programming RaspberryPI with Python:


The Raspberry Pi is a fully-fledged mini computer, capable of doing whatever you might do
with a computer. It comes with 4x USB, HDMI, LAN, built-in Bluetooth/WiFi support, 1GB RAM,
1.2GHz quad-core ARM CPU, 40 GPIO (General Purpose Input Output) pins, audio and composite
video output, and more.
RespberryPi can be interfaced with variety of sensors, actuators using GPIO pins
and also SPI, I2C and serial interfaces. Input from the Raspberry Pi can be processed and actions
can be taken, for instance, and sending data to server, sending an email, triggering a relay switch.

Simple Interfacing program on Raspberry Pi print ―Hello world‖


Key Points:
1. Find your customized Raspberry Pi.
2. Mount the SD card
3. Plug in the HDMI cable into the Pi and the monitor
4. Plug in the keyboard into the USB port
5. Plug in the mouse into the USB port
6. Plug in the power cable
7. Type in user name ―Pi‖
8. Type in password ―raspberry‖
9. Double click on ―Terminal‖
10. This will load the ―terminal‖
11. Type the following commands
 Change the directory by the command $ cd Desktop
 Create a new directory $ mkdir python_code
 Change the directory to python_code $ cd python_code
 Create new file helloworld.py
 Now enter the code given in the box below
 Run the python code ―sudo python helloworld.py‖
 You will see it print ―Hello World!‖ to the screen
Program:
#Access the python working environment
#!/usr/bin/python
#Print a message Hello world on the terminal
24 Dept. of CSE MIT Mysore
Internet of Thins -15CS81 2020

print(―Hello World!‖)

Blinking an LED
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.
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.

To find the pin number refer to this diagram showing the physical pin numbers on the Raspberry
Pi.

Python code to initialization GPIO ports and Turn the LED on and off in 1 second intervals
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

Push button for physical input

25 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

Push Button is simplest of devices and it is the basic input device that can be connected to
any controller or processor like Arduino or Raspberry Pi.
A push button in its simplest form consists of four terminals. In that, terminals 1 and 2 are
internally connected with each other and so are terminals 3 and 4. So, even though you have four
terminals, technically, you have only two terminals to use.
When a GPIO pin is declared as Input, it must be connected to VCC or GND with the help of
either a Pull-up resistor or a Pull-down resistor.

The following images show the circuit diagram of the Raspberry Pi Push Button Interface.

Components Required
 Raspberry Pi
 Push Button
 5mm LED
 100Ω Resistor (1/4 Watt)
 Mini Breadboard
 Connecting Wires
 Power Supply

A 5mm LED is used as an output device. The anode of the LED (long lead) is connected to Physical
Pin 18 (GPIO24) of Raspberry Pi. The cathode of the LED (short lead) is connected to one terminal
of a 100Ω Resistor.

Code
import RPi.GPIO as GPIO
import time
button = 16
led = 18

def setup():
GPIO.setmode(GPIO.BOARD)
GPIO.setup(button, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(led, GPIO.OUT)

def loop():
while True:
button_state = GPIO.input(button)
if button_state == False:
GPIO.output(led, True)
print('Button Pressed...')
while GPIO.input(button) == False:
time.sleep(0.2)
else:
26 Dept. of CSE MIT Mysore
Internet of Thins -15CS81 2020

GPIO.output(led, False)

def endprogram():
GPIO.output(led, False)
GPIO.cleanup()

if __name__ == '__main__':
setup()
try:
loop()
except KeyboardInterrupt:
print 'keyboard interrupt detected'
endprogram()

Buzzer
A buzzer or beeper is an audio signalling device, which may be mechanical,
electromechanical, or piezoelectric (piezo for short). Typical uses of buzzers and beepers include
alarm devices, timers, and confirmation of user input such as a mouse click or keystroke.
Components Required:
Raspberry Pi + SD Card
Keyboard + Mouse
Monitor + HDMI Cable
Power Supply
Breadboard
1x Red LED
1x Blue LED
2x 330? Resistor
2x M/M Jumper Wire
5x M/F Jumper Wire
1x Button
1x Buzzer

Code:
#!/usr/bin/python

27 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

import os
from time import sleep
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(22,GPIO.OUT)
loop_count = 0
# define a function called morsecode
def morsecode ():

#Dot Dot Dot


GPIO.output(22,GPIO.HIGH)
sleep(.1)

GPIO.output(22,GPIO.LOW)
sleep(.1)
GPIO.output(22,GPIO.HIGH)
sleep(.1)
GPIO.output(22,GPIO.LOW)
sleep(.1)
GPIO.output(22,GPIO.HIGH)
sleep(.1)

#Dash Dash Dash


GPIO.output(22,GPIO.LOW)
sleep(.2)
GPIO.output(22,GPIO.HIGH)
sleep(.2)
GPIO.output(22,GPIO.LOW)
sleep(.2)
GPIO.output(22,GPIO.HIGH)
sleep(.2)
GPIO.output(22,GPIO.LOW)
sleep(.2)
GPIO.output(22,GPIO.HIGH)
sleep(.2)
GPIO.output(22,GPIO.LOW)
sleep(.2)

#Dot Dot Dot


GPIO.output(22,GPIO.HIGH)
sleep(.1)
GPIO.output(22,GPIO.LOW)
sleep(.1)
GPIO.output(22,GPIO.HIGH)
sleep(.1)
GPIO.output(22,GPIO.LOW)
sleep(.1)
GPIO.output(22,GPIO.HIGH)
sleep(.1)
GPIO.output(22,GPIO.LOW)
sleep(.7)

os.system('clear')
print "Morse Code"

loop_count = input("How many times would you like SOS to loop?: ")
while loop_count > 0:
loop_count = loop_count - 1

28 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

morsecode ()

WIRELESS TEMPERATURE MONITOR WITH ESP8266 AND RASPBERRY PI


Monitoring temperatures around your house can be done fairly easily and there is a range
of commercial products out there.
In this section, we describe how to build a simple wireless temperature monitor with
ESP8266 and Raspberry Pi using WiFi and UDP protocols.

PARTS LIST
 ESP8266 (ESP-07 used here)
 FT232 converter to program the ESP
 Raspberry Pi zero W (Used for it‘s built-in WiFi capability)
 ili9341 SPI LCD to display temperature
 DS18B20 sensor
 4.7 k resistor
 IoTbear ESP breakout board (Optional)
 A router to which both the Pi and the ESP will be connected to.

The idea is that a DS18b20 sensor is connected to the ESP8266 and the temperature readings are
sent to a Raspberry Pi using UDP through WiFi. The Raspberry Pi then processes that temperature
data and displays it on an TFT LCD screen. Of course, both, the ESP8266 and the Raspberry Pi are
connected to the same router or are on the same network. It is also possible to send data across
network/over the internet if you configure your DNS properly to make the devices visible to each
other. In this post, they are simply connected to the same router.

29 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

CONNECTING DS18B20 TO THE ESP8266


To keep thing simple, we are going to use the Arduino environment and the One Wire library to
program the ESP8266.
The wiring of the DS18d20 is as follows, with the DS18d20 wired to GPIO 0:

UPLOADING CODE TO THE ESP8266

// Including the ESP8266 WiFi library


#include <ESP8266WiFi.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <WiFiUDP.h>
// Replace with your network details
const char* ssid = "Your_Router_SSID";
const char* password = "Your_Router_Password";
boolean wifiConnected = false;
// Data wire is plugged into pin D1 on the ESP8266 12-E - GPIO 0
#define ONE_WIRE_BUS 0
IPAddress broadcastIp(192,168,1,255);
// UDP variables
unsigned int localPort = 8888;
WiFiUDP UDP;
boolean udpConnected = false;
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,
// Setup a oneWire instance to communicate with any OneWire devices (not just
Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature DS18B20(&oneWire);
char temperatureCString[6];
char temperatureFString[6];
// Web Server on port 80
WiFiServer server(80);
// only runs once on boot
void setup() {
// Initializing serial port for debugging purposes
Serial.begin(115200);
delay(10);
// Initialise wifi connection
wifiConnected = connectWifi();

30 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

// only proceed if wifi connection successful


if(wifiConnected){
udpConnected = connectUDP();
if (udpConnected){

}
}
DS18B20.begin(); // IC Default 9 bit. If you have troubles consider upping it 12. Ups
the delay giving the IC more time to process the temperature measurement

}
// runs over and over again
void loop() {
getTemperature();
//Serial.println(temperatureCString);

// check if the WiFi and UDP connections were successful


if(wifiConnected){
if(udpConnected){
getUDP();
//Start broadcast of Temperature
if(String(packetBuffer) == "BehindTheSciences.com") //If start packet is received
{
while(String(packetBuffer) != "STOP") //Stops transmitting Temperature Data if //
"STOP" is received on UDP
{
getTemperature();
memset(packetBuffer, 0, sizeof(packetBuffer));
UDP.beginPacket(broadcastIp, 64123);
UDP.write(temperatureCString);
UDP.endPacket();
delay(5000);
getUDP();
Serial.println(String(packetBuffer));
}
}
}
delay(10);
}
}
//Get UDP Data
void getUDP(){
int packetSize = UDP.parsePacket();
if(packetSize)
{
Serial.println("");
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remote = UDP.remoteIP();

31 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

for (int i =0; i < 4; i++)


{
Serial.print(remote[i], DEC);
if (i < 3)
{
Serial.print(".");
}
}
Serial.print(", port ");
Serial.println(UDP.remotePort());
// read the packet into packetBufffer
UDP.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);
Serial.println("Contents:");
Serial.print(packetBuffer);
}
}
// connect to UDP – returns true if successful or false if not
boolean connectUDP()
{
boolean state = false;
Serial.println("");
Serial.println("Connecting to UDP");
if(UDP.begin(localPort) == 1)
{
Serial.println("Connection successful");
state = true;
}
else
{
Serial.println("Connection failed");
}
return state;
}
// connect to wifi – returns true if successful or false if not
boolean connectWifi()
{
boolean state = true;
int i = 0;
WiFi.begin(ssid, password);
Serial.println("");
Serial.println("Connecting to WiFi");
// Wait for connection
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
if (i > 10)
{
state = false;

32 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

break;
}
i++;
}
if (state)
{
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
else
{
Serial.println("");
Serial.println("Connection failed.");
}
return state;
}

//Get Temperature of 18D20


void getTemperature()
{
float tempC;
float tempF;
do
{
DS18B20.requestTemperatures();
tempC = DS18B20.getTempCByIndex(0);
dtostrf(tempC, 2, 2, temperatureCString);
tempF = DS18B20.getTempFByIndex(0);
dtostrf(tempF, 3, 2, temperatureFString);
delay(100);
} while (tempC == 85.0 || tempC == (-127.0));
}

DS18B20 Temperature Sensor


Digital temperature sensors like the DS18B20 differ from analog thermistors in several
important ways. In thermistors, changes in temperature cause changes in the resistance of a
ceramic or polymer semiconducting material. Usually, the thermistor is set up in a voltage divider,
and the voltage is measured between the thermistor and a known resistor. The voltage
measurement is converted to resistance and then converted to a temperature value by the
microcontroller.
Digital temperature sensors are typically silicon based integrated circuits. Most contain the
temperature sensor, an analog to digital converter (ADC), memory to temporarily store the
temperature readings, and an interface that allows communication between the sensor and a
microcontroller.

About DS18B20
The DS18B20 communicates with the ―One-Wire‖ communication protocol, a proprietary
serial communication protocol that uses only one wire to transmit the temperature readings to the
microcontroller.
33 Dept. of CSE MIT Mysore
Internet of Thins -15CS81 2020

The DS18B20 can be operated in what is known as parasite power mode. Normally the
DS18B20 needs three wires for operation: the Vcc, ground, and data wires. In parasite mode, only
the ground and data lines are used, and power is supplied through the data line.

The DS18B20 also has an alarm function that can be configured to output a signal when the
temperature crosses a high or low threshold that‘s set by the user.

A 64 bit ROM stores the device‘s unique serial code. This 64 bit address allows a
microcontroller to receive temperature data from a virtually unlimited number of sensors at the
same pin. The address tells the microcontroller which sensor a particular temperature value is
coming from.

TECHNICAL SPECIFICATIONS
 -55°C to 125°C range
 3.0V to 5.0V operating voltage
 750 ms sampling
 0.5°C (9 bit); 0.25°C (10 bit); 0.125°C (11 bit); 0.0625°C (12 bit) resolution
 64 bit unique address
 One-Wire communication protocol

CONNECT THE DS18B20 TO THE RASPBERRY PI


The DS18B20 has three separate pins for ground, data, and Vcc:

WIRING FOR SSH TERMINAL OUTPUT


Follow this wiring diagram to output the temperature to an SSH terminal:

R1: 4.7K Ohm or 10K Ohm resistor

WIRING FOR LCD OUTPUT


Follow this diagram to output the temperature readings to an LCD:

34 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

R1: 4.7K Ohm or 10K Ohm resistor


For more information about using an LCD on the Raspberry Pi, check out our tutorial Raspberry Pi
LCD Set Up and Programming in Python.

ENABLE THE ONE-WIRE INTERFACE


We‘ll need to enable the One-Wire interface before the Pi can receive data from the
sensor. Once you‘ve connected the DS18B20, power up your Pi and log in, then follow these steps
to enable the One-Wire interface:
1. At the command prompt, enter: sudo nano /boot/config.txt, then add this to the bottom of the
file:
dtoverlay=w1–gpio
2. Exit Nano, and reboot the Pi (sudo reboot)
3. Log in to the Pi again, and at the command prompt enter sudo modprobe w1–gpio
4. Then enter sudo modprobe w1-therm
5. Change directories to the /sys/bus/w1/devices directory by
entering: cd /sys/bus/w1/devices
6. Now enter ls to list the devices:

28-000006637696 w1_bus_master1 is displayed in my case.


7. Now enter cd 28-XXXXXXXXXXXX (change the X‘s to your own address)
For example, in my case I would enter: cd 28-000006637696
8. Enter cat w1_slave which will show the raw temperature reading output by the sensor:

35 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

Here the temperature reading is t=28625, which means a temperature of 28.625 degrees Celsius.
9. Enter cd to return to the root directory
That‘s all that‘s required to set up the one wire interface. Now you can run one of the programs
below to output the temperature to an SSH terminal or to an LCD…
PROGRAMMING THE TEMPERATURE SENSOR
The examples below are written in Python. If this is your first time running a Python
program, check out our tutorial How to Write and Run a Python Program on the Raspberry Pi to see
how to save and run Python files.

TEMPERATURE OUTPUT TO SSH TERMINAL


This is a basic Python program that will output the temperature readings in Fahrenheit and Celsius
to your SSH terminal:
import os
import glob
import time

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

def read_temp_raw():
f = open(device_file, 'r')
lines = f.readlines()
f.close()
return lines

def read_temp():
lines = read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
temp_f = temp_c * 9.0 / 5.0 + 32.0
return temp_c, temp_f

while True:
print(read_temp())

36 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

time.sleep(1)

TEMPERATURE OUTPUT TO AN LCD


We‘ll be using a Python library called RPLCD to drive the LCD. The RPLCD library can be
installed from the Python Package Index, or PIP. PIP might already be installed on your Pi, but if
not, enter this at the command prompt to install it:
sudo apt-get install python-pip
After you get PIP installed, install the RPLCD library by entering:
sudo pip install RPLCD
Once you have the library installed, you can run this program to output the temperature to an LCD
display:

import os
import glob
import time
from RPLCD import CharLCD

lcd = CharLCD(cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23])

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

def read_temp_raw():
f = open(device_file, 'r')
lines = f.readlines()
f.close()
return lines

#CELSIUS CALCULATION
def read_temp_c():
lines = read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = int(temp_string) / 1000.0 # TEMP_STRING IS THE SENSOR OUTPUT, MAKE
SURE IT'S AN INTEGER TO DO THE MATH
37 Dept. of CSE MIT Mysore
Internet of Thins -15CS81 2020

temp_c = str(round(temp_c, 1)) # ROUND THE RESULT TO 1 PLACE AFTER THE


DECIMAL, THEN CONVERT IT TO A STRING
return temp_c

#FAHRENHEIT CALCULATION
def read_temp_f():
lines = read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_f = (int(temp_string) / 1000.0) * 9.0 / 5.0 + 32.0 # TEMP_STRING IS THE SENSOR
OUTPUT, MAKE SURE IT'S AN INTEGER TO DO THE MATH
temp_f = str(round(temp_f, 1)) # ROUND THE RESULT TO 1 PLACE AFTER THE
DECIMAL, THEN CONVERT IT TO A STRING
return temp_f

while True:
lcd.cursor_pos = (0, 0)
lcd.write_string("Temp: " + read_temp_c() + unichr(223) + "C")
lcd.cursor_pos = (1, 0)
lcd.write_string("Temp: " + read_temp_f() + unichr(223) + "F")

Accessing Temperature from DS18B20 sensors


Python Code to accessing the temperature
def read_temp():
lines = read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
temp_f = temp_c * 9.0 / 5.0 + 32.0
return temp_c, temp_f

while True:
print(read_temp())
time.sleep(1)

Connecting Raspberry Pi via SSH


You can access the command line of a Raspberry Pi remotely from another computer or
device on the same network using SSH.

The Raspberry Pi will act as a remote device: you can connect to it using a client on another
machine.

You only have access to the command line, not the full desktop environment.
1. Set up your local network and wireless connectivity
Make sure your Raspberry Pi is properly set up and connected. If you are using wireless
networking, this can be enabled via the desktop's user interface, or using the command line.

If you are not using wireless connectivity, plug your Raspberry Pi directly into the router.
38 Dept. of CSE MIT Mysore
Internet of Thins -15CS81 2020

Using the ifconfig command will display information about the current network status, including
the IP address, or you can use hostname -I to display the IP addresses associated with the device.

2. Enable SSH
Raspbian has the SSH server disabled by default. It can be enabled manually from the desktop:

1. Launch Raspberry Pi Configuration from the Preferences menu


2. Navigate to the Interfaces tab
3. Select Enabled next to SSH
4. Click OK

Alternatively, raspi-config can be used in the terminal:

Enter sudo raspi-config in a terminal window


Select Interfacing Options
Navigate to and select SSH
Choose Yes
Select Ok
Choose Finish
Alternatively, use systemctl to start the service

sudo systemctl enable ssh


sudo systemctl start ssh

3. Enable SSH on a headless Raspberry Pi (add file to SD card on another machine)


For headless setup, SSH can be enabled by placing a file named ssh, without any extension, onto
the boot partition of the SD card from another computer. When the Pi boots, it looks for the ssh file.
If it is found, SSH is enabled and the file is deleted. The content of the file does not matter; it could
contain text, or nothing at all.

If you have loaded Raspbian onto a blank SD card, you will have two partitions. The first one, which
is the smaller one, is the boot partition. Place the file into this one.

4. Set up your client


SSH is built into Linux distributions and Mac OS, and is an optional feature in Windows 10.

Smart and ConnectedCities


An IoT Strategy for Smarter Cities
Managing a city bears some resemblance to managing a corporate enterprise. As the need
for efficiency increases, new tools help increase operational efficiency. For cities, just as for
businesses, digitization transforms the perspective on operations. New ideas emerge, bringing
different approaches to solving management issues. Scalable solutions utilizing information and
communications technology (ICT) can alleviate many issues urban centers face today by increasing
efficiency, which reduces costs and enhances quality of life.

Vertical IoT Needs for Smarter Cities


There are many differing approaches and solutions for city management. All these solutions
typically start at the street level, with sensors that capture data on everything from parking space
availability to water purity. Data analytics is also used extensively, for example, to reduce crime or
improve traffic flows. Citizens can use tools to leverage their smart mobile devices, such as to report
problems and make recommendations for improving urban life or locate available parking spaces.
These connections create vast amounts of data, some of which has never been accessible
before. When this data is analyzed and used intelligently, the possibilities to correlate, analyze,
and optimize services and processes that deliver a better quality of life for people are practically

39 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

endless. However, the growth of IoT applications for urban centers not only delivers unique
benefits for each issue it solves but also enhances a city‘s ability to develop efficient services.
Cities are expected to generate almost two-thirds (63%) of IoT‘s overall civilian benefits
worldwide over the next decade. To maximize value, smart cities can combine use cases through a
shared-revenue business model together with special partners to monetize city location services for
retail and tourism, as well as city planning, parking, and water management.
A recent Cisco study, as illustrated in Figure below, expects IoT to have the following economic
impact over a 10-year period:
■ Smart buildings: Smart buildings have the potential to save $100 billion by lowering operating
costs by reducing energy consumption through the efficient integration of heating, ventilation, and
air-conditioning (HVAC) and other building infrastructure systems.
■ Gas monitoring: Monitoring gas could save $69 billion by reducing meter-reading costs and
increasing the accuracy of readings for citizens and municipal utility agencies. There are also very
important advantages in terms of safety, regardless of who operates the utility. In cases of sudden
consumption increase, a timely alert could lead to emergency response teams being dispatched
sooner, thus increasing the safety of the urban environment.
■ Smart parking: Smart parking could create $41 billion by providing real-time visibility into
parking space availability across a city. Residents can identify and reserve the closest available
space, traffic wardens can identify noncompliant usage, and municipalities can introduce demand-
based pricing.
■ Water management: Smart water management could save $39 billion by connecting household
water meters over an IP network to provide remote usage and status information. The benefit is
obvious, with features such as real-time consumption visibility and leak detection. A gate or a pump
can be opened and closed remotely and automatically in real time, based on a variety of flow input
and output analytics data. Vibrations can be measured to detect and predict potential equipment
failures.
■ Road pricing: Cities could create $18 billion in new revenues by implementing automatic
payments as vehicles enter busy city zones while improving overall traffic conditions. Real-time
traffic condition data is very valuable and actionable information that can also be used to proactively
reroute public transportation services or private users.

Figure: Key Use Cases for Smart Cities

Global vs. Siloed Strategies


The main obstacle in implementing smart solutions in today‘s traditional infrastructure is the
complexity of how cities are operated, financed, regulated, and planned. Cities attempting to
upgrade their infrastructure to match the growing needs of the citizen population often invest in
40 Dept. of CSE MIT Mysore
Internet of Thins -15CS81 2020

one problem at a time, and they do it independently. Even cities using IoT technology break up city
assets and service management into silos that are typically unable to communicate or rely on each
other.

The independent investment model results in the following problems:


■ Isolation of infrastructure and IT resources
■ No sharing of intelligence and information, such as video feeds and data from sensors.
■ Waste and duplication in investment and effort
■ Difficulty scaling infrastructure management

This fragmented approach is not scalable, efficient, or economically viable, and it does not
benefit from cross-functional sharing of data and services.

Cities need to begin with a solution that can extend systems across vendors, technologies,
and data types, and they should approach their infrastructure investment with a horizontal solution
that addresses their issues cohesively.

City issues are typically large-scale. They require collection of large amounts of diverse
data sets in real time. For instance, managing traffic flows and congestion in a city involves
understanding patterns of traffic in real time. This means that data from traffic sensors, traffic
cameras, parking sensors, and more has to be collected and analyzed in real time so that decision
making can be optimized around signal timing, rerouting, and so on.

All these requirements pose technological challenges, including the following:


■ How do you collect the data? What are the various sources of data, including hardware endpoints
and software?
■ How do you make sure that any data collection devices, such as sensors, can be maintained
without high costs?
■ Where do you analyze the data? What data do you carry back to the cloud, and what data do you
analyze locally?
■ What kind of network connectivity is best suited for each type of data to c ollect?
■ What kind of power availability and other infrastructure, such as storage, is required?
■ How do you aggregate data from different sources to create a unified view?
■ How do you publish the data and make it available for applications to consume?
■ How do you make the end analysis available to specialized smart city personnel, such as traffic
operators, parking enforcement officers, street lighting operators, and so on at their logical
decision points?
■ How do you present the long-term analysis to city planners?

Smart City IoT Architecture


A smart city IoT infrastructure is a four-layered architecture, as shown in Figure below. Data
flows from devices at the street layer to the city network layer and connect to the data center layer,
where the data is aggregated, normalized, and virtualized. The data center layer provides
information to the services layer, which consists of the applications that provide services to the city.

41 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

Figure: Smart Cities Layered Architecture

In smart cities, multiple services may use IoT solutions for many different purposes. These
services may use different IoT solutions, with different protocols and different application
languages. Therefore, data flow from sensor to application involves a translation process into a
normalized language that can be exposed through APIs for other service application consumption.
This translation ensures a single language for all devices in the cloud.

Street Layer
The street layer is composed of devices and sensors that collect data and take action
based on instructions from the overall solution, as well as the networking components needed to
aggregate and collect data.
A sensor is a data source that generates data required to understand the physical world.
Sensor devices are able to detect and measure events in the physical world. ICT connectivity
solutions rely on sensors to collect the data from the world around them so that it can be analyzed
and used to operationalize use cases for cities.

A variety of sensors are used at the street layer for a variety of smart city use cases. Here is a short
representative list:
■ A magnetic sensor can detect a parking event by analyzing changes in the surrounding magnetic
field when a heavy metal object, such as a car or a truck, comes close to it (or on top of it).
■ A lighting controller can dim and brighten a light based on a combination of time-based and
ambient conditions.
■ Video cameras combined with video analytics can detect vehicles, faces, and traffic conditions
for various traffic and security use cases.
■ An air quality sensor can detect and measure gas and particulate matter concentrations to give a
hyper-localized perspective on pollution in a given area.
■ Device counters give an estimate of the number of devices in the area, which provides a rough
idea of the number of vehicles moving or parked in a street or a public parking area, of pedestrians
on a sidewalk, or even of birds in public parks or on public monuments—for cities where bird
control has become an issue.

For each type of data to collect, there are a variety of solutions and possible approaches.
The choice of sensor technology depends on the exact nature of the problem, the accuracy and cost
trade-offs appropriate for it, and any installation limitations posed by the physical environment.
Another consideration is the requirement to interact with other IoT systems in the same physical
space.

42 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

One of the key aspects to consider when choosing a sensing device is its lifetime
maintenance costs. Some sensors are mounted on city infrastructure, such as light poles. These
sensors can benefit from the power, and possibly the network connectivity, of their mounting
location.

Another key aspect to consider when choosing the right technology for a smart city is edge
analytics. The many sensors and their data must be managed through the network in a way that
securely processes data with minimal delay—and often in real time.

Finally, for sensor characteristics, storage is a key consideration that depends on the
method, location, and length of time the data has to be archived. Data collection and storage also
have an important impact on privacy.

Regardless of the type of system chosen, sensor data is transported and processed by the
IoT system. Although IoT systems use common APIs and normalized language in the cloud, they
may use different network protocols.

Another issue that network planning must take into account is the required level of
agnosticism of smart city networks. LoRaWAN is growing as a major protocol for smart city sensors,
across multiple verticals. LoRaWAN is well adapted to the type of ranges required in an urban
environment and the types of data exchanges that most smart city sensors need.

City Layer
This layer aggregates all data collected by sensors and the end-node network into a single
transport network.
The city layer may appear to be a simple transport layer between the edge devices and the
data center or the Internet. However, one key consideration of the city layer is that it needs to
transport multiple types of protocols, for multiple types of IoT applications. Figure below shows a
Street Layer Resiliency.

Figure: Street Layer Resiliency

Data Center Layer


Data collected from the sensors is sent to a data center, where it can be processed and
correlated. Based on this processing of data, meaningful information and trends can be derived,
and information can be provided back. For example, an application in a data center can provide a

43 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

global view of the city traffic and help authorities decide on the need for more or less common
transport vehicles.

The key technology in creating any comprehensive smart solution with services is the cloud.
With a cloud infrastructure, data is not stored in a data center owned directly or indirectly by city
authorities.

The cloud model is the chief means of delivering storage, virtualization, adaptability, and
the analytics know-how that city governments require for the technological mashup and synergy of
information embodied in a smart city.

Figure below shows the vision of utilizing the cloud in smart solutions for cities. The cloud
provides a scalable, secure, and reliable data processing engine that can handle the immense
amount of data passing through it.

Figure: The Role of the Cloud for Smart City Applications


Smart city issues require not just efficient use of infrastructure, which the cloud helps
enable, they also require new data processing and management models. For example, cloud
services allow for Software as a Service (SaaS) models that create cyclical returns on investment.

Services Layer
The true value of ICT connectivity comes from the services that the measured data can
provide to different users operating within a city. Smart city applications can provide value to and
visibility for a variety of user types, including city operators, citizens, and law enforcement. The
collected data should be visualized according to the specific needs of each consumer of that data
and the particular user experience requirements and individual use cases.
For example, parking data indicating which spots are and aren‘t currently occupied can
drive a citizen parking app with a map of available spots, as well as an enforcement officer‘s
understanding of the state (utilization and payment) of the public parking space, while at the same
time helping the city operator‘s perspective on parking problem areas in the city at any given time.

Smart City Use-Case Examples


There are multiple ways a smart city can improve its efficiency and the lives of its citizens.
Some of the applications commonly used as starting points to implement IoT in smart cities:
connected street lighting, smart parking, smart traffic control, and connected environment.

Connected Street Lighting


Of all urban utilities, street lighting comprises one of the largest expenses in a
municipality‘s utility bill, accounting for up to 40% of the total.
Maintenance of street lights is an operational challenge, given the large number of lights
and their vast geographic distribution.
44 Dept. of CSE MIT Mysore
Internet of Thins -15CS81 2020

Connected Street Lighting Solution


Cities commonly look for solutions to help reduce lighting expenses and at the same time
improve operating efficiencies while minimizing upfront investment. The installation of a smart
street lighting solution can provide significant energy savings and can also be leveraged to
provide additional services.

In this regard, light-emitting diode (LED) technology leads the transition from traditional
street lighting to smart street lighting:
■ LEDs require less energy to produce more light than legacy lights, and they have a much longer
life span and a longer maintenance cycle.
■ A leading lighting company estimates that a complete switch to LED technology can reduce
individual light bills by up to 70%.
■ LEDs are well suited to smart solution use cases. For example, LED color or light intensity can be
adapted to site requirements.

Street Lighting Architecture


Connected lighting uses a light management application to manage street lights remotely
by connecting to the smart city‘s infrastructure. This application attaches to LED lights, monitors
their management and maintenance, and allows you to view the operational status of each light. In
most cases, a sensor gateway acts as an intermediate system between the application and the lights
(light control nodes).

The gateway relays instructions from the application to the lights and stores the local lights‘
events for the application‘s consumption. The controller and LED lights use the cloud to connect to
the smart city‘s infrastructure, as shown in Figure below.

Figure: Connected Lighting Architecture


A human or automated operator can use a cloud application to perform automated
scheduling for lights and even get light sensors to perform automated dimming or brightening, as
needed. The schedule can also impact the light intensity level and possibly the color, depending
on environmental conditions, weather, time of year, time of day, location within the city, and so on.

Lighting nodes vary widely in the industry, especially with respect to elements such as what
communication protocol they use (for example, Wi-Fi, cellular, ZigBee, 802.15.4g [Wi-SUN],
LoRaWAN), level of ruggedization, and on-board sensor capabilities. These features are optimized
for different circumstances and conditions; no single lighting node can support all environments
ideally.

45 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

Smart Parking
Parking is a universal challenge for cities around the globe. According to urban planning
researchers, up to 30% of cars driving in congested downtown traffic are searching for parking
spaces. Ineffective parking access and administration make parking in urban areas a constant
struggle and affect cities in many ways.

Smart Parking Use Cases


Added traffic congestion is one consequence of drivers looking for parking space, and it has
several consequences:
■ Contributes to pollution: Tons of extra carbon emissions are released into the city‘s
environment due to cars driving around searching for parking spots when they could be parked.
■ Causes motorist frustration: In most cities, parking spot scarcity causes drivers to lose patience
and waste time, leading to road rage, inattention, and other stress factors.
■ Increases traffic incidents: Drivers searching for parking spots cause increased congestion in
the streets and that, in turn, causes increased accidents and other traffic incidents.

` Revenue loss is another consequence of drivers looking unsuccessfully for parking space, and it
also has various negative side effects:
■ Cities often lose revenue: As a result of inadequate parking meter enforcement and no-parking,
no-standing, and loading-zone violations, cities lose revenue.
■ Parking administration employee productivity suffers: Employees waste time roaming the
streets, attempting to detect parking rules offenders.
■ Parking availability affects income: Local shops and businesses lose customers because of the
decreased accessibility caused by parking space shortages.

Smart Parking Architecture


A variety of parking sensors are available on the market, and they take different approaches
to sensing occupancy for parking spots. Examples include in-ground magnetic sensors, which use
embedded sensors to create a magnetic detection field in a parking spot; video-based sensors,
which detect events based on video computing (vehicle movements or presence); and radar
sensors that sense the presence of vehicles (volumetric detection). Figure below shows the
Connected Parking Architecture.

Figure: Connected Parking Architecture.

Technology innovations are happening all the time, making the holistic ICT connectivity
architecture even more important. For example, new detection technologies rely on sensing the
radio emissions (Bluetooth and others) coming from a vehicle. The adoption of such new
46 Dept. of CSE MIT Mysore
Internet of Thins -15CS81 2020

technologies implies that the communication architecture is open enough to accommodate the
needs of these new systems.
Combining these technologies in innovative ways also expands the possibilities of the
services IoT systems can deliver; this certainly holds true for smart parking.

Regardless of the technology used, parking sensors are typically event-driven objects. A
sensor detects an event and identifies it based on time or analysis. The event is transmitted through
the device‘s communication protocol to an access point or gateway, which forwards the event data
through the city layer.

The following are some potential user experiences for these three user types:
■ City operators: These users might want a high-level map of parking in the city to maintain
perspective on the city‘s ongoing parking situation. They would also need information on historical
parking data patterns to understand congestion and pain points in order to be able to effectively
influence urban planning.
■ Parking enforcement officers: These users might require real-time updates on parking changes
in a certain area to be able to take immediate action on enforcement activities, such as issuing
tickets or sending warnings to citizens whose time is nearing expiration.
■ Citizens: These users might want an application with a map (such as a built-in parking app in
their car) showing available parking spots, reservation capabilities, and online payment. Their
focus would be on minimizing the time to get a parking spot and avoiding parking tickets. The
application could warn when parking duration limits approach, allowing the driver to move the
vehicle before the timer expires or pay a parking timer extension fee without having to go back to
the vehicle.

Smart Traffic Control


Traffic is one the most well-understood pain points for any city. It is the leading cause of
accidental death globally, causes immense frustration, and heavily contributes to pollution around
the globe. A smart city traffic solution would combine crowd counts, transit information, vehicle
counts, and so on and send events regarding incidents on the road so that other controllers on the
street could take action.

Smart Traffic Control Architecture


In the architecture shown in Figure below, a video analytics sensor computes traffic events
based on a video feed and only pushes events (the car count, or metadata, not the individual
images) through the network. These events go through the architectural layers and reach the
applications that can drive traffic services. These services include traffic light coordination and also
license plate identification for toll roads. Some sensors can also recognize abnormal patterns, such
as vehicles moving in the wrong direction or a reserved lane. In that case, the video feed itself may
be uploaded to traffic enforcement agencies.

Other types of sensors that are part of traffic control solutions include Bluetooth vehicle
counters, real-time speed and vehicle counters, and lighting control systems. These sensors
provide a real-time perspective while also offering data collection services for historical data
trending and correlation purposes.

47 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

Smart Traffic Applications


Traffic applications can be enabled to take immediate action with other sensors to manage
traffic and to reduce pain points. Historical data can be used to develop more efficient urban
planning to reduce the amount of traffic a city experiences.

A well-known remedy for stop-and-go traffic is to regulate the standard flow speed based on
car density. As density increases, car speed is forced down to avoid the wave effect.
An application that measures traffic density in real time can take action by regulating the
street light cycle duration to control the number of cars added to the flow of the main routes, thus
limiting or suppressing the wave effect.
Information can also be shared with drivers.
Understanding a city‘s real-time traffic patterns and being able to effectively mitigate traffic
issues can drive tremendous value for a city.

Connected Environment
As of 2017, 50% of the world‘s population has settled on less than 2% of the earth‘s surface
area. Such densely populated closed spaces can see spikes in dangerous gas molecules at any
given moment. More than 90% of the world‘s urban population breathes in
air with pollutant levels that are much higher than the recommended thresholds, and one out of
every eight deaths worldwide is a result of polluted air.

The Need for a Connected Environment


Most large cities monitor their air quality. Data is often derived from enormous air quality
monitoring stations that are expensive and have been around for decades. These stations are
highly accurate in their measurements but also highly limited in their range, and a city is likely to
have many blind spots in coverage.

To fully address the air quality issues in the short term and the long term, a smart city
would need to understand air quality on a hyper-localized, real-time, distributed basis at any given
moment. To get those measurements, smart cities need to invest in the following:
■ Open-data platforms that provide current air quality measurements from existing air quality
monitoring stations.
■ Sensors that provide similar accuracy to the air quality stations but are available at much lower
prices.
■ Actionable insights and triggers to improve air quality through cross-domain actions.

48 Dept. of CSE MIT Mysore


Internet of Thins -15CS81 2020

■ Visualization of environmental data for consumers and maintenance of historical air quality data
records to track emissions over time.

Connected Environment Architecture


Figure below shows an architecture in which all connected environment elements overlay
on the generalized four-layer smart city IoT architecture.

As shown in Figure, at the street layer there are a variety of multivendor sensor offerings,
using a variety of communication protocols. Connected environment sensors might measure
different gases, depending on a city‘s particular air quality issues, and may include weather and
noise sensors. These sensors may be located in a variety of urban fixtures, such as in street lights,
as explained earlier. They may also be embedded in the ground or in other structures or smart city
infrastructure. Even mobile sources of information can be included through connected wearables
that citizens might choose to purchase and carry with them to understand the air quality around
them at any given moment. Crowdsourcing may make this information available to the global
system.

Communication technologies depend on the location of the sensors. Wearables typically


communicate via a short-range technology (such as Bluetooth) with a nearby collecting device
(such as a phone).

Independent and standalone sensors typically use wireless technologies. In dense urban
environments, ZigBee and Wi-Fi are common. However, Wi-Fi is not very well adapted for
networks where reports are sporadic because Wi-Fi requires an 802.11 connection to be
maintained, which consumes battery resources.

49 Dept. of CSE MIT Mysore

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy