15CS81 IoT Module 5
15CS81 IoT Module 5
15CS81 IoT Module 5
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?
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.
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.
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.
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.
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.
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.
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.
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
Then, you should select the right port as show in the figure below.
Serial Port
COM3 (Arduino/Genuine)
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.
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
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.
Operating Voltage 5V
SRAM 2 KB (ATmega328P)
EEPROM 1 KB (ATmega328P)
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
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;
}
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
A + B will
addition + Adds two operands
give 30
A * B will
multiplication * Multiply both operands
give 200
B / A will
division / Divide numerator by denominator
give 2
(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
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
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
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
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
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
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.
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.
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
Ethernet Port
Ethernet port is accessible on Model B and B+. The Ethernet ports are controlled by
Microchip LAN9512 LAN controller chip.
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.
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
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.
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
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.
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.
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.
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)
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
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 ():
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)
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
morsecode ()
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.
}
}
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);
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;
}
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
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.
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())
time.sleep(1)
import os
import glob
import time
from RPLCD import CharLCD
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
#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")
while True:
print(read_temp())
time.sleep(1)
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:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
` 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.
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.
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.
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.
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.
■ Visualization of environmental data for consumers and maintenance of historical air quality data
records to track emissions over time.
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.
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.