You are on page 1of 90

Introduction to Embedded Systems

The Road Map to Industry 4.0 Revolution

https://www.mdpi.com/1424-8220/18/9/2796

https://www.thesandreckoner.co.uk/model-viewing-internet-things/ 1
The Road Map to Industry 4.0 Revolution

 The integration of current technologies such as Sensors, Robotics, Internet of Things (IoT),
Internet of People, Internet of Services, Cyber Physical Systems (CPS), 3D Printing, AR/VR,
Wireless and Mobile Networks, Cloud Computing Platforms, Big Data Analytics and Mining,
Artificial Intelligence , Deep Learning, Machine Learning, and Information Management
Systems has led to develop Smart Environment such as Smart City.
 New business model that is changing us in the way we behave, conduct ourselves,
interact, produce, transport and consume.
 Impacting all disciplines, economies and industries, and even changing us.
 The changes are historic in terms of their size, speed and scope, velocity, breadth & depth and
systems Impact: across and within, companies, industries, countries and society as a whole.
 All stakeholders of governments, business, industry, academia, and global civil society – have a
responsibility to work together to better understand the emerging trends.

Physical Digital Biological


World World World
‘Domain’ ‘Domain’ ‘Domain’

2
Physical
World
‘Domain’

 There are four main physical manifestations of the technological megatrends,


which are the easiest to see because of their tangible nature: –
 Autonomous vehicles –
 3D printing –
 Advanced robotics –
 New materials
• Like many innovations of the fourth industrial revolution, it is hard to know
where developments in new materials will lead.
• Take advanced nanomaterials such as graphene, which is about 200-times
stronger than steel, a million-times thinner than a human hair, and an efficient
conductor of heat and electricity. When graphene becomes price competitive
(gram for gram, it is one of the most expensive materials on earth, with a
micrometer-sized flake costing more than $1,000), it could significantly disrupt
the manufacturing and infrastructure industries. It could also profoundly affect
countries that are heavily reliant on a particular commodity.

3
Biological
World
‘Domain’
 It took more than 10 years, at a cost of $2.7 billion, to complete the Human Genome Project. Today, a genome can be
sequenced in a few hours and for less than a thousand dollars.

 Synthetic biology is the next step. It will provide us with the ability to customize organisms by writing DNA. Setting
aside the profound ethical issues this raises, these advances will not only have a profound and immediate impact on
medicine but also on agriculture and the production of biofuels.

 The ability to edit biology can be applied to practically any cell type, enabling the creation of genetically modified
plants or animals, as well as modifying the cells of adult organisms including humans.

 3D manufacturing will be combined with gene editing to produce living tissues for the purpose of tissue repair and
regeneration – a process called bioprinting

 To return to the issue of genetic editing, that it is now far easier to manipulate with precision the human genome within
viable embryos means that we are likely to see the advent of designer babies in the future who possess particular traits or
who are resistant to a specific disease.

 Needless to say, discussions about the opportunities and challenges of these capabilities are underway. Notably, in
December 2015, the National Academy of Sciences and National Academy of Medicine of the US, the Chinese
Academy of Sciences and the Royal Society of the UK convened an International Summit on Human Gene Editing.
Despite such deliberations, we are not yet prepared to confront the realities and consequences of the latest genetic
techniques even though they are coming. The social, medical, ethical and psychological challenges that they pose are
considerable and need to be resolved, or at the very least, properly addressed.

4
Digital
World
‘Domain’
Internet of Things (IoT), Internet of People , Internet of Service and Cyber Physical Systems at large
 Integration Sensors and Actuators to Things to collect their status and surrounding environment

 Uploaded through Wireless and Mobile Networks to Fog and Cloud Computing Layer
 Performing Big Data Analytics and Mining using Artificial Intelligence, Deep Learning,
Machine Learning.
 Visualization in terms of dashboards, charts, reports and graphics.
 Communication and Cloud Computing Platforms.
 All have led to develop Smart Environment such as Smart City Applications.

5
I3.0: Semi customize and variant product
Example: 18 product
variations

6
I 4.0 is about fully customized, variant, mass volumes,
data rich, enhanced service and just in time production
Example: 56,000 product variations

7
Industry 4.0 is about fully customized, variant, mass
volumes and just in time production

8
Just-In-Time Manufacturing

Industry 4.0
Industry 3.0 Mass Production AND Customization
Mass production Data Rich Product

9
Smart Street Lighting

10
What are the enabling technologies for industry 4.0

http://dazeinfo.com/2014/01/23/smartphone-users-growth-mobile-internet-2014-2017/

11
CISCO Concept

12
Example Smart Cereal Flakes Factory

10 grams Banana Chips, 8 grams Corn Flakes,


7 grams Raisin, 6 grams Chocolate Chips

Enhance Data Product will talk to Machines

13
Smart Cereal Flakes Factory

10 grams Banana Chips, 8 g Corn Flakes, 7 g, Raisin, 6 g Chocolate Chips

The Product will talk to Machines

14
The Fourth Industrial Revolution
Comparison between Industry 3.0 and Industry 4.0 Revolutions
Three Biggest Market Revenues Employees
Companies1 Capitalization
Detroit-1990s $36 billion $250 billion 1.2 million
Silicon Valley -2010s $1.09 trillion $247 billion 137,000

100 Yrs. 23 Yrs. 19 Yrs. 41 Yrs.


$136B rev (’16) $136B rev (’16) $90B rev (’16) $214B rev (’16)
Telephone vs. ‘Pokemon Go’
For evidence of how quickly technological change is spreading, Krieger pointed to the
adoption of the telephone. It took 75 years for 100 million people to get access to the
telephone; the gaming app “Pokemon Go” hooked that many users in less than one month
in 2016.
1. Klaus Schwab, the four industrial revelation, 2016. 2. https://www.youtube.com/watch?v=XM4DlLjsL0g
3. http://www.datacenterknowledge.com/archives/2017/03/16/google-data-center-faq 15
Are we losing or gaining Jobs in I4.0?
 ” McKinsey projects the overall creation of 555 to 890 million new jobs by
2030, declaring that “this job growth could more than offset the jobs lost to
automation.”
 McKinsey estimates 75 to 375 million people will have to switch occupations
and learn new skills by 2030, “implying substantial workplace transformations
and changes for all workers.
 According to the WEF report I4.0: 133 million new roles may emerge as
companies shake up their division of labor between humans and machines:
translating to 75 million jobs displaced and 58 million net new jobs being
created by 2022.
 “It is critical that businesses take an active role in supporting their existing
workforces through reskilling and upskilling, that individuals take a proactive
approach to their own lifelong learning, and that governments create an
enabling environment, rapidly and creatively, to assist in these effort.

https://www.cnbc.com/2019/01/16/fourth-industrial-revolution-explained-davos-2019.html
PUBLISHEDTHU, JAN 17 2019  1:17 AM ESTUPDATED TUE, JAN 22 2019  3:39 PM EST, Elizabeth Schulze@ESCHULZE9
16
https://www.futurithmic.com/2019/02/13/industry-4-0-could-create-millions-new-jobs/
Uber Revenue and Usage Statistics (2019)
Mansoor Iqbal, Updated: May 10, 2019

Users 700B

Drivers 30M

Revenue 50B

Valuation 200B

http://www.businessofapps.com/data/uber-statistics/#4 17
[1 Most Prone(loss job) 0.01 Least Prone (keep job)]

The Fourth Industrial Revolution, Klaus Schwab, 2016-2017


18
[1 Most Prone(loss job) 0.01 Least Prone (keep job)]

The Fourth Industrial Revolution, Klaus Schwab, 2016-2017


19
Same Theme Different Brands

https://www.sciencedirect.com/science/article/pii/S0040162517311514?via%3Dihub20
Regardless of Their Brand Name…
They all are providing new applications to make our cities smarter:

https://www.mdpi.com/1999-5903/12/10/163
21
Smart Transportations
Much of the silicon content in cars comprises microcontrollers (MCUs), often several dozen per vehicle, that control
various aspects of the car's operating systems as well as safety equipment, comfort controls, location devices and
entertainment

A modern car contains several dozen subsystems that use MCUs with embedded non-volatile memory for firmware storage
and other purposes. (courtesy Xilinx)
23
24
25
What is an Embedded System?
•Tough question, really. There is no one answer. I asked at least a half dozen
industry experts and got as many answers.

•An embedded system is device used to control, monitor and/or assist the
operation of equipment, machinery or plant.

•An embedded system is combination of computer hardware, software,


mechanical and/or electrical components to perform a specific function.

•An embedded system is designed to perform a specific function. The software


within such application is called embedded since it determines to a large extent
functionality of the product: the software and the rest of the product have no
meaning without each other.

•Sensors continuously gather information from the environment while the


embedded system processes the information to signal actuators in accordance
with mechanics of controlled process.
26
Sensors continuously gather information from the environment while the
embedded processor processes the information to signal actuators in
accordance with mechanics of controlled process.

Application-specific
integrated circuit

27
Photon Cyber Enable Micro-Server

Headers Dimensions in inches (mm) Weight


With 1.44 x 0.8 x 0.27 (36.58 x 20.32 x 6.86) 5 grams
Without 1.44 x 0.8 x 0.17 (36.58 x 20.32 x 4.32) 3.7 grams
29
ESP32 SOC Wi-Fi-and-Bluetooth combo chip microcontroller

•Processors:
•Main processor: Tensilica Xtensa 32-bit LX6
microprocessor
•Cores: 2 or 1 (depending on variation)
All chips in the ESP32 series are dual-core except for ESP32-
S0WD, which is single-core.
•Clock frequency: up to 240 MHz
•Performance: up to 600 DMIPS
•Ultra low power co-processor: allows you to do
ADC conversions, computation, and level thresholds
while in deep sleep.
•Wireless connectivity:
•Wi-Fi: 802.11 b/g/n/e/i (802.11n @ 2.4 GHz up to
150 Mbit/s)
•Bluetooth: v4.2 BR/EDR and Bluetooth Low
Energy (BLE)
•Peripheral input/output: Rich peripheral interface with
DMA that includes capacitive touch, ADCs (analog-to-
digital converter), DACs (digital-to-analog converter), I²C
(Inter-Integrated Circuit), UART (universal asynchronous
receiver/transmitter), CAN 2.0 (Controller Area Network),
SPI (Serial Peripheral Interface), I²S (Integrated Inter-IC Dimensions in inches (mm) Weight
Sound), PWM (pulse width modulation), and more…. 0.71 x 0.98 x 0.11 (18x25.5x2.8) 3.63 grams
Price: $4
30
http://esp32.net/
Recent Computing Elements for Embedded Systems
RASPBERRY PI 3: It is credit card size computer
RASPBERRY PI 3 : The revolutionary $35 mini-PC
Faster, better, harder, stronger
SoC: Broadcom BCM2837 64-bit system-on-chip with :
CPU: 4X ARM Cortex-A53, 1.2GHz
GPU: Broadcom Video-Core IV
RAM: 1GB LPDDR2 (900MHz)
Networking: 10/100 Ethernet, 2.4GHz 802.11n wireless
Bluetooth: Bluetooth 4.1 Classic, Bluetooth Low Energy
Storage: microSD upto 32Gbytes
GPIO: 40-pin header, populated
Ports: HDMI, 3.5mm analogue audio-video jack, 4X USB 2.0,
Ethernet, Camera Serial Interface (CSI),
Display Serial Interface (DSI)
Addons:
 8-Channels ATD.
 Real-time clock

Cyber Physical System:


Physical environment, sensors & actuators,
•Integrated computing power
•And communications.
31
•Embedded software
Raspberry Pi Introduction

32
Technical Specifications System On Chip (SoC) processor, Introduced in March 2016
 It is credit card size computer
 SoC: Broadcom BCM2837 64-bit system-on-chip with four
ARM Cortex-A53 CPU cores clocked 1.2GHz
 CPU: 4X ARM Cortex-A53, 1.2GHz HDMI
 GPU: Broadcom Video-Core IV
 RAM: 1GB LPDDR2 (900MHz)
 Networking: 10/100 Ethernet,
2.4GHz 802.11n wireless
 Bluetooth: Bluetooth 4.1 Classic,
Bluetooth Low Energy
 Ethernet 10/100 LAN Port

https://www.raspberrypi.org/products/raspberry-pi-3-model-b/
 Storage: microSD: The SD card bundled with the Raspbian
OS, which is a Linux based OS. It must be inserted into PS: 5VDC/2.5Amps
the SD Card slot.
 For display, RPI can be connected to the LCD TVs or
desktop monitor that supports HDMI.
 GPIO: 40-pin header, populated.
 Analogue audio-video jack, 4X USB 2.0, Camera Serial
Interface (CSI),
Display Serial Interface (DSI),
 The USB ports can be easily utilized for connecting USB
mouse and a USB keyboard.
 8-Channels ATD.
 Real-time clock (Once turned ON and WiFi is On, it will
get the systems real-time clock.

The board needs to be connected to a power equipment which


is a mini USB connector and draws current of 2.5 Amps at 5
volts. Can use a micro USB power supply or power it up
from the CPU.

Raspberry Pi 3 [3] Board layout.


33
Raspberry Pi 4
Released on June 2019. Completely upgraded hardware.
Faster and more powerful than previous versions

● https://www.raspberrypi.org/products/raspberry-pi-4-model-b/specifications/
● http://socialcompare.com/en/comparison/raspberrypi-models-comparison 34
• When the Pi was designed, they used a figure of 3mA per
GPIO pin in determining if the regulator could supply enough
current.
• 17 pins at a time at 3 mA each means the power regulator is
only rated for 50 mA
• Each 50 mA / 17 =~ 3 mA
• This doesn’t mean that the maximum current per GPIO is
3mA. The author of the same blog suggest that 16 mA be the
maximum pulled from any 1 pin, and that 50 mA as the
maximum from all pins.
35
Raspberry Pi Zero W: $10.00

Technical Specifications
The Raspberry Pi Zero W extends the Pi Zero
family. Launched at the end of February
2017, the Pi Zero W has all the functionality
of the original Pi Zero, but comes with added
connectivity, consisting of:

802.11 b/g/n wireless LAN


Bluetooth 4.1 = 70meter
Bluetooth Low Energy (BLE) =100meter
Like the Pi Zero, it also has:
1GHz, single-core CPU
512MB RAM
Mini HDMI and USB On-The-Go ports
Micro USB power
HAT-compatible 40-pin header
Composite video and reset headers
CSI camera connector

36
Operating System in Raspberry Pi 3
• The Raspberry Pi uses Linux kernel-based operating system. 
• Raspbian, a Debian-based free operating system optimized for the
Raspberry Pi hardware is the official OS for raspberry pi.
• The easiest and quickest way to get started with Raspberry Pi.
Recommended for first time Pi users, the 32GB MicroSD card
comes pre-loaded with the official Raspberry Pi New Out of Box
Software (NOOBS) package featuring a choice of seven
recommended Raspberry Pi Operating Systems including:
• Raspbian
• Open ELEC
• OSMC (short for Open Source Media Center: is a Linux
distribution based on Debian 
• Windows 10 IoT Core
• Arch Linux
• Pidora
32GB NOOBS Micro SD card
• RISC OS
• Multiple languages can be used to program in Raspberry Pi. Python, C, C+
+, Java, Scratch, and Ruby all come installed by default on the Raspberry Pi.
• Python is the official programming language of the Raspberry Pi, a Python
Integrated Development Environment (IDE) will be used for writing codes
in python.

37
Preparing the SD Card for OS setup in Pi3

• If the SD card is already bundled with the


NOOBS package, directly insert it into the
Raspberry Pi and power it up.
• 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.
• Wait for it to finish not long time seconds to few
minutes.
• However, if the SD card is not pre-installed with
an Operating Systems or NOOBS, then we have
to prepare the SD card and install an Operating
system to use Raspberry Pi.
• We choose Raspbian OS as it is officially
supported and has a big community of users.
For more information visit:
• https://www.raspberrypi.org/documentation/installation/installing-
images/

38
Desktop Computer LibreOffice
You might not think it's really fair to compare the free LibreOffice and the paid Microsoft Office, but the two are a lot
closer in features than you might think. For one, LibreOffice is compatible with a lot more systems, including Windows,
OS X, and Linux, while Microsoft Office's newest version is restricted to just Windows 7 and Windows 8. Besides: it’s
not about which one is “better” or “more feature filled.” It’s about whether your work requires what Microsoft has to offer,
or if you can get by with something free and save a bit of money. Now, with LibreOffice reaching 4.1, we've decided it's
time to give it an in-depth comparison with Microsoft Office.

39
LAB Work
Python Programming Tutorial

• There are two ways of executing python code in Raspberry Pi:


1) Using the Terminal Window
2) Using Python IDLE 3,
A Python Integrated Development Environment (IDE) that serves as a
GUI to write and execute python code
• We will be using Python IDLE 3.x in lab for a simpler user interactive
experience.
• For programming using the terminal window, you should be familiar
with basic Linux commands.
40
Raspberry Pi Screen after boot up
Terminal Window

Python 3 IDE

41
Python using IDLE
• Python is an interpreted, object-oriented,
high-level programming language with
dynamic semantics.
• Python has no compilation step and the edit-
test-debug cycle is incredibly fast.
• Python is used domains ranging from Desktop
application development to scientific and
numeric computing
• We will use Python IDLE 3 to program
python applications
• Python IDLE 2 and Python IDLE 3 come pre-
installed on Raspbian. If needed on any other
OS, type the following command in terminal
window:
– sudo apt-get install python3 or sudo apt-
get install python
 
42
Open IDLE 3
and click File -> New File

On clicking F5
the output is shown

43
Output:

Output:

44
Output:

Output: 45
While Loops: Used as a repeating if statement
Output:
46
For Loops: Typically used when number of iterations are known is
known before entering the loop

Output:

47
• Useful Functions
• X= input (“String to be displayed to user”) used to prompt the user to
enter inputs
• print (“ { } “. format (X )) used to output data to the terminal

Output:

48
Python Exercises

49
https://docs.python.org/2/library/math.html
Raspberry Pi
Digital I/O in Raspberry Pi

50
Raspberry Pi GPIOs
• Pins in Raspberry Pi, as shown in Figure below, are
used to perform digital input/output operations.
• Raspberry Pi 3 Model B has 40 pins. Of these 40 pins,
26 are GPIO pins and the others are power or ground
pins.
• These pins are a physical interface between the Pi and
the outside world. At the simplest level, you can think
of them as switches that you can turn on or off (input)
or that the Pi can turn on or off (output).
• 3maps outsourcing current/ Total Pins 50mamps at a
time. Power supply 5V max 2.5amps.

51
Raspberry Pi 3 model B : GPIO
Board mode Board mode

52
GPIOs Layout

• Some GPIOs have multiplexed functions


such as UART, I2C, SPI bus.

• The following communication protocols can


be used with GPIOs when not being used in
their bus modes:
UART, I2C, and SPI Bus

• 2 Pins for I2C, 2 Pins for UART and 5 pins


for SPI

• I2C and SPI can be used to interface ATD or


DAC convertor, & oscillators

• UART can be used for serial data input and


output

• Two voltages on GPIO: 3V3 and 5.0 V

53
RPi.GPIO Installation

GPIO library installation from terminal window using the linux


commands:-

• $sudo apt-get install python-dev


// python-dev is a library that contains header files to build Python
extensions

• $sudo apt-get install python-rpi.gpio


//rpi.gpio library is required for interfacing the pins

• $sudo apt-get update


// to get the most recent update for all applications such Raspbian
OS, Libre office (word, excel, ppt.)

If you are using the most popular Raspbian OS, the RPi.GPIO
library is already included in it and there is no need to install it.

54
Programming the RPi

•RPi.GPIO:
A module (library) for GPIO access to control
Raspberry Pi GPIO channels, allows you to
easily configure and read (input) –write
(output) pins on the Pi’s GPIO header within a
Python script.

•Wiring Pi :
A module (library) for GPIO access to control
Raspberry Pi GPIO channels, allows you to
easily configure and read (input) –write
(output) pins on the Pi’s GPIO header within a
shell script writing in C language Similar to
Arduino style programming.

•We will be working with RPi.GPIO library in the


lab.

55
Setting up Rpi.GPIO API

BCM mode Board mode

To Use RPi.GPIO throughout the


rest of your Python script, you need
to put the following statement at
the top of your file:

import RPi.GPIO as GPIO


#This statement imports the RPi.GPIO
library in the python script to enable
using the GPIOs

56
Pin Numbering Declaration

For the GPIO Pins to be usable, pin mode has to be configured first.
There are two modes of operation-
• GPIO.BOARD mode:- Board numbering scheme. It refers to the
pin numbers on header and the number goes from 1-40. Pin 22
in BOARD mode corresponds
Example “Pin 05” board mode
• GPIO.BCM mode :- Broadcom chip-specific pin numbers.
These are the numbers after "GPIO“
Example GPIO3 in BCM i.e.
“Pin 05” board mode = “GPIO3” in BCM
•The BOARD numbering system stays the same between board
revisions.
•It is recommended to use Board numbering to make the script more
meaningful and avoid revision checking.

57
Setting up pins as Input or Output

• In Python script, declare a “pin mode” before you can use a


pin as either an input or output. To set a pin mode, use the:

Input
GPIO.setup (PIN Num, GPIO.IN) GPIO.setup (PIN Num, GPIO.OUT)
Example: Example:
GPIO.setup (19, GPIO.IN) GPIO.setup (18, GPIO.OUT)

58
Setting up Pin Mode
More Examples:
To configure pin 7 (Board) as output and GPIO14 (BCM) as input

59
How to Read an Input:
• If a pin is configured as an input, GPIO.setup (18, GPIO.IN), you can use
the GPIO.input(pin) function to read its value (status) in BOARD Mode.
• The input() function will return either a True or False indicating whether the
pin is HIGH (ON) or LOW (OFF). You can use an if statement to test this.
• for example, the code to connect a switch to pin 17 and check if the switch is
ON or OFF:

import RPi.GPIO as GPIO # importing the GPIO library to configure GPIOs


GPIO.setmode(GPIO.BOARD) # set the operation mode of GPIO to BOARD or BCM
GPIO.setup(17,input) # set pin 17 as an input (switch is connected to
# pin 17 to Raspberry pi)
if (GPIO.input(17) == 1) # check (read) the status of the input() function
# it returns true(1) or false(0)
print (“pin 17 is high, switch ON”)
else
print(“pin 17 is low, Switch OFF”)

NOTE: Make sure you indent your code properly using TAB rather than spaces

60
Digital Outputs:

• To write to a digital output pin high or low, use the function:


GPIO.output(pin, GPIO.LOW)
GPIO.output(pin, GPIO.HIGH)
For example,
if you want to set pin 18 high, write:
GPIO.output(18,GPIO.HIGH)
GPIO.output(18,True)

• GPIO.HIGH will drive it to 3.3V, and GPIO.LOW will set it to 0V.


• Another alternative to GPIO.HIGH and GPIO.LOW, is to use
either 1/True, 
or 0/False to set a pin value.

61
Delays

• If you need to slow your Python script down, you can add delays. To
incorporate delays into your script, you’ll need to include another module: time
include time# to import the Time library

• Use time.sleep([seconds]) to give your script a rest. For example, to delay 250


milliseconds, write:
time.sleep(0.25) # calling the sleep function
• The argument is in seconds and it can be a int or a floating point
numberAnother useful function available with time library is:
time.ctime() # display the current and time/date
# in the following format : day month date
# time year

62
Example of using time.ctime and time.sleep method:

Output:

63
Time.ctime() Method- To access the current date and time

• The Raspberry Pi does not come with a real-time clock, so the OS


uses a network time server during raspberry bootup time to get
access to time and date.
• However, a real-time clock (such as the DS1307) with battery
backup can be added via the I2C interface on Raspi GPIO.
• The function time.tcime() returns the current system time in ticks
since 12:00am, January 1, 1970. It counts the number of ticks since
1970:01:01 00:00:00. There are 10 million ticks per second.
• An internet connection is required to call the time.ctime() function.

PiFace Real Time Clock

64
GPIO Output Basic Summary

import RPi.GPIO as GPIO # Import GPIO module


import time # Import time module

GPIO.setmode(GPIO.BOARD) # Taking Pin number from the board

GPIO.setup(12,GPIO.OUT) # Setting 12th pin as OUTPUT


while True: # Similar to while(1)
GPIO.output(12,GPIO.HIGH) # Setting 12th pin high
time.sleep(1) # 1 sec delay
GPIO.output(12,GPIO.LOW) # Setting 12th pin low
time.sleep(1) # 1 sec delay

65
Digital Buttons/Switches
• Types of digital inputs: A Single Pole
Single Throw (SPST) switch, DIP
switches, push buttons.

• By attaching a button/switch between


the 5V voltage source and the input
pin on microcontroller/Raspberry pi ,
we detect the status of the
switch/button.
Fig 1: (a). SPST Switch (b). SPST button

• When switch is pressed a connection


is made between the two terminals
and current will flow. The Raspberry
will see +5V(or 1) on its input pin. If
flipped off, the Raspberry will see 0V
(or 0) on it.

• We need a pull down resister on its


input pin so that it really sees the
ground when the switch is not pressed.
To input (GPIOs on Raspberry pi)
Fig 2 : DIP Switches 66
Practice Example #1 (Output)
• Write a python program to flash one LED with an interval of 1 second:
• Assume the LED is connected to PIN7. You must use a current limiting resistor.

67
Practice Example #2 (Input/Output)

68
• Write a python program to flash 1
LED 3 times with an interval of 1
second: Assume the LED is
connected to PIN 11. You must use a
for loop

PIN 11 PIN 12 PIN 13

Output: 1 (3.3V)
(GND) 6

16 11
12
13

69
• Write a python program to consecutively turn ON/OFF 3 LEDs connected to PIN 11,12,13
five times with an interval of 1 second.

As mentioned before
True or 1
False or 0

Output:

70
Write a program in C to turn ON/OFF an LED
for 0.5 seconds connected to PIN 11 (on BOARD mode)

71
Pulse Width Modulation: PWM (analog output as well)

To create a PWM instance:


p = GPIO.PWM(channel, frequency)

To start PWM:
p.start(dc)
# where dc is the duty cycle (0.0 <= dc <= 100.0)

To change the frequency:


p.ChangeFrequency(freq)
# where freq is the new frequency in Hz

To change the duty cycle:


p.ChangeDutyCycle(dc)
# where 0.0 <= dc <= 100.0
To stop PWM:
p.stop()
If Vref=3.3V calculate Vmean for PWM
with D=0.25, D=0.5, D=0.75?
72
GPIO PWM Examples
Blink LED connected to GPIO 12 once each two seconds:

Output:
Pulse each 2 seconds

73
GPIO PWM Examples
Frequency= 50Hz with incrementing/decrementing duty cycle
Brighten/dim an LED:

74
Passive Buzzer

To drive a passive buzzer


you will need to use square GND
VCC
waves to drive it.  You can
change the wave frequency
to alter the beeping sound.

https://www.sunfounder.com/learn/se
nsor-kit-v2-0-for-raspberry-pi-b- Pin 17
plus/lesson-10-buzzer-module-
sensor-kit-v2-0-for-b-plus.html 75
Understanding Sensors
What is an ultrasonic sensor?
An ultrasonic sensor is an instrument that measures the distance to an object using ultrasonic sound
waves.
An ultrasonic sensor uses a transducer to send and receive ultrasonic pulses that relay back information
about an object’s proximity.  
High-frequency sound waves reflect from boundaries to produce distinct echo patterns.  

How Ultrasonic Sensors Work?


Ultrasonic sound vibrates at a frequency above the range of human hearing.  
Transducers are the microphones used to receive and send the ultrasonic sound.
Our ultrasonic sensors, like many others, use a single transducer to send a pulse and to receive the echo.  The
sensor determines the distance to a target by measuring time lapses between the sending and receiving of the
ultrasonic pulse.  

Why use an ultrasonic sensor?


Ultrasound is reliable in any lighting environment and can be used inside or outside.  Ultrasonic sensors can
handle collision avoidance for a robot, and being moved often, as long as it isn’t too fast.  
Ultrasonics are so widely used, they can be reliably implemented in grain bin sensing applications, water
level sensing, drone applications and sensing cars at your local drive-thru restaurant or bank.
Ultrasonic rangefinders are commonly used as devices to detect a collision.  

76
In order to generate the ultrasound you need to set the Trig on a High State for 10 µs. That will send out
an 8 cycle sonic burst which will travel at the speed sound and it will be received in the Echo pin. The
Echo pin will output the time in microseconds the sound wave traveled.

Trig

Echo

77
Ultrasonic Ranging Module

78
https://www.sunfounder.com/learn/sensor-kit-v2-0-for-raspberry-pi-b-plus/lesson-25-ultrasonic-ranging-module-sensor-
kit-v2-0-for-b-plus.html
Ultrasonic Ranging Module
while True:
import Rpi.GPIO as GPIO TRIG = OUT =19         dis = distance() #read the distance
import time ECHO= IN = 20         print (“distance = %2.2f cm” %dis)
GPIO.setmode(GPIO.BCM)
TRIG = 19 #set ultrasonic sensor trig pin
GPIO.setup(TRIG, GPIO.OUT)
ECHO = 20 #set ultrasonic sensor echo pin
GPIO.setup(ECHO, GPIO.IN)

# ultrasonic reading function


def distance():
        GPIO.output(TRIG, 0) #make it low Read the Echoed Single
        time.sleep(0.000002)
#set trig pin high for 10us
        GPIO.output(TRIG, 1) #Gen Pulse of 10sµ
time.sleep(0.00001)
        GPIO.output(TRIG, 0)
#read the echo pin signal and calculate the distance in cm
     while GPIO.input(ECHO) == 0:
      a=0 #dummy time1 time2

     time1 = time.time() #Capture time 1


     while GPIO.input(ECHO) == 1:
      a=0 #dummy        
time2 = time.time() #Capture time 2
    duration = time2 - time1
    return duration*1000000/58 #sensor equation

79
General Overview of interrupts
Regardless of the Processor in Being Used: HC12, PIC, Raspberry Pi, Arduino , Photon
Exceptions and Interrupt are used interchangeably.
To be more precise, you could say interrupts are subset of exceptions.
Exceptions: is an event, which occurs during the program execution:
 It is any event that can alter the normal CPU Instruction execution flow.
 Then, an internal event that handles abnormality during program executions.
 Examples:
- Invalid instruction such divide by zero, single step execution (tracing),
- Illegal bus access such go to address that may not be the beginning of instruction address or
data address.
$2000 Jump $2010
- It is software trigger event
$2003 Jump $5000
$2010 Data storage area
$5000 Memory is not installed

 Interrupt: is an event that can be triggered by external hardware which leads to stop the
program executing sequence and jump to and interrupt handler ( Interrupt Service Routine -
ISR). Such ISR can be system-ISR or user-ISR:
 Examples:
- System-ISR; Hardware Interrupts Triggered by external signal: Reset, Printer is out off papers,
Print screen (Print Screen).

- User-ISR: Hardware Interrupts Triggered by GPIO: an action on an input of GPIO Pin will
cause the CPU to jump to ISR is defined and written by the user (Read ADC, Flash an output
GPIO….).

 Errors are handled more smoothly.


 CPU utilization is improved.

80
Exceptions and Interrupt
Overall Process Sequence
 In both Types, once an expectation or an interrupt occurs, the normal
program execution sequence is suspended,

 Identifying the cause of interrupt,

 the CPU status registers, the program counters and other registers are
saved the stack area,

 The address of the ISR handler is loaded to the program counter


(instruction pointer),

 Execution of the ISR starts.


Example: a user defined ISR (IRS is a set of instructions like
read ADC, turn OFF a specific
GIPO, display hello message.

 At the end of the ISR, restoring the CPU status registers and the
program counter from the stack,

 Resuming the interrupted program normal execution from the next


instruction where it was interrupted, inter the and jump to execute

81
Exceptions and Interrupt Overall Process Sequence

82
Raspberry PI Interrupt Handling
1. Polling forever 2.Polling for limited time 3.Interrupt without Polling
1. Polling a specific input 2. Interrupt every now and then: 3. Interrupt with no Polling:
until condition is met. Periodic Polling for limited time, Keep executing the program.
Once met, then go to the If an interrupt occurs, go for it, Once an interrupt occurs,
next instruction .i.e. hang in Else keep executing the program go for the Interrupt Service Routine
there until condition is met and check for an interrupt (ISR), execute and return to
after a specific time say x msec. where the program was interrupt .

Main Main
Main
Program Program
Program

Check Yes ISR


4 Int. Do Something
Once X time
expired Go
to next Inst.

Check Yes ISR


4 Int. Do Something

83
GPIO Polling
Previously, you have used if statements and while loops to check for the status of the
Rpi GPIO inputs. Then execute certain statement or make an action on an output in
case any of these inputs change its status.
This is called polling techniques. An example of such programs is shown below:

if GPIO.input(channel):
print('Input was HIGH')
else:
print('Input was LOW')
#OR
while (GPIO.input(channel)):
print('Input was HIGH')

84
85
86
GPIO Interrupts
Each GPIO pin, when configured as a general-purpose input, can be configured as an interrupt driven
event. Interrupt can be activated as follows:
•Synchronous Rising/Falling edge:
The normal rising/falling edge detection has a small amount of synchronization built into
the detection. Every system clock cycle, the pin is sampled with the criteria for generation
of an interrupt being a stable transition within a 3-cycle window, i.e. a record of "1 0 0" for
falling or "0 1 1“ for rising.
•Asynchronous Rising/Falling edge:
Asynchronous detection bypasses this synchronization to enable the detection
of very narrow events.
Once an interrupt edge is detected, The CPU will start executing the related interrupt service routine
(function).

Asyn. Asyn.
Falling Edge Rising Edge

87
Syn. Falling Edge Syn. Rising Edge
GPIO.add_event_detect(channel, GPIO.Edge, callback=my_callback, bouncetime=x)
Where:
Channel is the GPIO input,
Edge can be RISINF or FALLING, or Both,
my_callback is the name of ISR function
x is the time needed to overcome the denounce effect in milliseconds.

GPIO. add_event_detect (18, GPIO.FALLING, callback=action , bouncetime=1000)

88
Interrupt Driven Program

89
 PIR Sensors Application
A PIR sensor is a digital sensor used to detect motion; the sensor radiates IR and reflects
the signals back to the senor using a set of special lenses. Based on the deference
between the signals read back from each lens it can detect whether an object is moving
in its range. As a result simple to use the sensor it should be powered up and then wait
1-2 seconds for the sensor to get a snapshot of the still room. If anything moves after
that period, the ‘alarm’ pin will go low. Connecting the pin to a digital I/O of a
microcontroller one can write programs to detect motion in the surrounding
environment. The alarm pin is an open collector meaning you will need a pull up
resistor on the alarm pin.

R = Power

W = Ground

B = Output
Phototransistor IR LED

90

You might also like