IoT Modulle 5
IoT Modulle 5
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
Itnhte
erA
neTt m
of e gan2
Thi gs5a6n0d, Aupspelifcualtiw
onhs e(1n5C
ySo8u1r) M
proodujelect5:dIooTesPnh‘ytsifciatsl DinevaicnesUaN
ndOE. ndpoints 158/207
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 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.
• 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.
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:
Then, you should select the right port as show in the figure below.
Figure below shows the layout of Arduino IDE.
The Toolbar buttons and functions of each button are as shown in the below table.
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.
6 (A0 – A5)
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
braces to 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;
}
A + B will
addition + Adds two operands
give 30
A * B will
multiplication * Multiply both operands
give 200
(A & B) will
Binary AND Operator copies a bit to give 12
and &
the result if it exists in both operands. which is
0000 1100
(A | B) will
Binary OR Operator copies a bit if it give 61
or | exists in either operand which is
0011 1101
(A ^ B) will
Binary XOR Operator copies the bit if it give 49
xor ^
is 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'
which is
bits.
1100 0011
A &= 2 is
compound Bitwise AND assignment
&= same as A = A
bitwise and operator
&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
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 , The pinMode() function is used to configure a specific pin
mode); 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
Processor
The Broadcom BCM2835 SoC used in the first generation Raspberry Pi includes a700
MHz ARM1176JZF-S processor, VideoCore IV graphics processing unit (GPU),and RAM. It has alevel
1 (L1) cache of 16 KiB and a level 2 (L2) cache of 128 KiB. The level 2 cache is used primarilyby 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 panelthrough
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
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.
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 muchmore
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 devicesmay 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.
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 ofa 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
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.
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.
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 runat 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.
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)
The following images show the circuit diagram of the Raspberry Pi Push Button Interface.
Push Button
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:
GPIO.output(led, False)
def endprogram():
GPIO.output(led, False)
GPIO.cleanup()
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 ()
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.
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:
}
// runs over and over again
void loop() {
getTemperature();
//Serial.println(temperatureCString);
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.
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, onlythe 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
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)
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
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
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")
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.
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.
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.
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 analyzedand 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 conditionsfor
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 totransport
multiple types of protocols, for multiple types of IoT applications. Figure below shows a Street Layer
Resiliency.
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, andthe
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 dataand 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.
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.
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 newtechnologies
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. Theapplication could warn
when parking duration limits approach, allowing the driver to move thevehicle before the timer
expires or pay a parking timer extension fee without having to go back tothe 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 ofevery
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 andnoise 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. Copy