Embedded System Design
Embedded System Design
DESIGN
[ELC - 241]
For
S.Y.B.Sc. (Computer Science) Semester - IV
Electronics - (Paper - I)
New Syllabus as per CBCS Pattern Credit - 2
June 2020
Price ` 140.00
N5546
Embedded System Design ISBN 978-93-90506-47-7
First Edition : January 2021
© : Authors
The text of this publication, or any part thereof, should not be reproduced or transmitted in any form or stored in any computer
storage system or device for distribution including photocopy, recording, taping or information retrieval system or reproduced on any disc,
tape, perforated media or other information storage device etc., without the written permission of Authors with whom the rights are
reserved. Breach of this condition is liable for legal action.
Every effort has been made to avoid errors or omissions in this publication. In spite of this, errors may have crept in. Any mistake, error
or discrepancy so noted and shall be brought to our notice shall be taken care of in the next edition. It is notified that neither the publisher
nor the authors or seller shall be responsible for any damage or loss of action to any one, of any kind, in any manner, therefrom.
Published By : Polyplate Printed By :
NIRALI PRAKASHAN YOGIRAJ PRINTERS AND BINDERS
Abhyudaya Pragati, 1312, Shivaji Nagar, Works: Sr. No. 10\1,Ghule Industrial Estate,
Off J.M. Road, PUNE – 411005 Nanded Village Road,
Tel - (020) 25512336/37/39, Fax - (020) 25511379 TAL-HAVELI, DIT-PUNE 411041.
Email : [email protected] Mobile - 9850046517, 9404225254
☞ DISTRIBUTION CENTRES
PUNE
Nirali Prakashan : 119, Budhwar Peth, Jogeshwari Mandir Lane, Pune 411002, Maharashtra
(For orders within Pune) Tel : (020) 2445 2044, 66022708, Fax : (020) 2445 1538; Mobile : 9657703145
Email : [email protected], [email protected]
Nirali Prakashan : S. No. 28/27, Dhyari, Near Pari Company, Pune 411041
(For orders outside Pune) Tel : (020) 24690204 Fax : (020) 24690316; Mobile : 9657703143
Email : [email protected], [email protected]
MUMBAI
Nirali Prakashan : 385, S.V.P. Road, Rasdhara Co-op. Hsg. Society Ltd.,
Girgaum, Mumbai 400004, Maharashtra; Mobile : 9320129587
Tel : (022) 2385 6339 / 2386 9976, Fax : (022) 2386 9976
Email : [email protected]
☞ DISTRIBUTION BRANCHES
JALGAON
Nirali Prakashan : 34, V. V. Golani Market, Navi Peth, Jalgaon 425001,
Maharashtra, Tel : (0257) 222 0395, Mob : 94234 91860
KOLHAPUR
Nirali Prakashan : New Mahadvar Road, Kedar Plaza, 1st Floor Opp. IDBI Bank, Kolhapur 416 012,
Maharashtra. Mob : 9850046155; Email : [email protected]
NAGPUR
Nirali Prakashan : Above Maratha Mandir, Shop No. 3, First Floor,
Rani Jhanshi Square, Sitabuldi, Nagpur 440012, Maharashtra
Tel : (0712) 254 7129; Email : [email protected]
DELHI
Nirali Prakashan : Room. No. 2 Ground Floor, 4575/15 Omkar Tower,
Agarwal Road, Darya Ganj, New Delhi - 110002.
Mob : 9555778814 / 9818561840 - Email : [email protected]
BENGALURU
Nirali Prakashan : Maitri Ground Floor, Jaya Apartments, No. 99, 6th Cross, 6th Main,
Malleswaram, Bangaluru 560 003, Karnataka. Mob : +91 9449043034
Email: [email protected]
Other Branches : Hyderabad, Chennai
Note: Every possible effort has been made to avoid errors or omissions in this book. In spite this, errors may have crept in. Any type of error
or mistake so noted, and shall be brought to our notice, shall be taken care of in the next edition. It is notified that neither the publisher, nor
the author or book seller shall be responsible for any damage or loss of action to any one of any kind, in any manner, therefrom. The reader
must cross check all the facts and contents with original Government notification or publications.
[email protected] | www.pragationline.com
Also find us on www.facebook.com/niralibooks
Preface …
We have great pleasure to present this book on ‘Embedded System Design’ which is
written as per the revised syllabus of Savitribai Phule Pune University for S.Y.B.Sc. (Computer
Science) in the subject of Electronics. The authors have sincerely put their efforts to give
complete information of the subject as prescribed in the syllabus in a simple manner.
Electronics and computer science go hand in hand. In fact, electronics is a backbone for
understanding computer operations. As the technology is changing day by day, yesterday’s
technology becomes old today. Keeping this in mind, SPPU has introduced latest
programming languages and technology in the syllabus.
This text book has been prepared as per the need of subject and syllabus specified by
SPPU.
The First Chapter introduces the concept of Single Board Computer (SBC) and the
fundamentals of Embedded System. The advantages/disadvantages of both are discussed in
this chapter.
In Second Chapter the architecture of System on Chip (SoC) and the details of Raspberry
Pi were thoroughly described. Raspberry Pi CPU, its architecture, internal blocks and their
functions are also discussed.
Third Chapter is based on Python. The structure of Python code, variables, data types,
functions, modules, packages used in Python were discussed in detail. Also few arithmetic
programs in Python were explained in this chapter.
Fourth Chapter describe the interfacing of input output devices to Raspberry Pi. Their
Python codes were also explained in this chapter.
After studying all this, student will get an idea of Raspberry Pi board and use of Python
programming and also they will understand the concept of SBC and SoC.
To give something extra to think and to explore the topic, ‘Think Over It’ element is
added in this book.
We are thankful to the publishers Shri Dineshbhai Furia and Shri Jignesh Furia and the
staff of Nirali Prakashan specially Mr. Ilyas Shaikh, Mrs. Manasi Pingle, Ms. Chaitali Takle, Mr
Ravindra Walodare for the great efforts they have taken to publish this book in time.
All valuable suggestions from the readers of this book are always welcome.
PUNE AUTHORS
JANUARY 2021
✍✍✍
Syllabus …
1. Introduction to Embedded Systems Using
Single Board Computers (SBC) (08 Lectures)
Single boards computer block diagram, Types, Comparison of SBC models, Specifications,
I/O devices (Storage, display, keyboard and mouse), Network access devices.
2. Architecture of System on Chip (SOC) (08 Lectures)
Architecture of SoC, Basic version Broad Coprocessor, Pin Description of Raspberry Pi,
Architectural features: CPU Overview, CPU Pipeline stages, CPU Cache Organization,
Branch Prediction and Folding (Concept), GPU Overview.
3. Programming Using Python (10 Lectures)
Overview of Rasberian OS (Operating System), Installation, different types of Operating
Systems
Basic Python Programming (Script programming): Variable and data types, Flow control
structures, Conditional statements (If … Then … else),
Functions: I/O function (GPIO, Digital), Time functions, Library functions.
Basic Arithmetic Programs: Addition, Subtraction, Multiplication, Division.
4. Interfacing of Devices Using Python Programming (10 Lectures)
Basic interfacing: LED, Switch, LCD.
Internal Advanced: Bluetooth, Wi-Fi, Ethernet.
External advanced: Camera, Serial communication GSM, Ultrasonic Sensor, PIR, Finger
Print reader.
✍✍✍
Contents …
1. Introduction to Embedded Systems Using
Single Board Computers (SBC) 1.1 – 1.18
✍✍✍
Unit 1…
Introduction to Embedded Systems
Using Single Board Computers (SBC)
Charles Stark "Doc" Draper was an American scientist and engineer,
known as the "father of inertial navigation". He was the founder and
director of the Massachusetts Institute of Technology's
Instrumentation Laboratory, later renamed the Charles Stark Draper
Laboratory, which made the Apollo Moon landings possible through
the Apollo Guidance Computer it designed for NASA. Draper was one
of the pioneers of inertial navigation, a technology used in aircraft,
space vehicles, and submarines that enables such vehicles to navigate
by sensing changes in direction and speed, using gyroscopes, and
Charles Stark Draper accelerometers.
A pioneering figure in aerospace engineering, he contributed to the Apollo space program with
his knowledge of guidance systems. One of the first recognizably modern embedded systems
was the Apollo Guidance Computer, developed ca. 1965 by Charles Stark Draper at the MIT
Instrumentation Laboratory. He was born on 2 October 1901,Windsor, Missouri, United States
and died on 25 July 1987, Cambridge, Massachusetts, United States. He was awarded with
National Medal of Science for Behavioral and Social Science, National Medal of Science for
Engineering.
Introduction
The 8051 microcontroller, its architecture, instruction set, programming in assembly language,
in ‘C’ language and interfacings of various input/output device were thoroughly studied in last
semester. This semester, we have to study embedded system, its block diagram, its architecture,
programming using Python and interfacing of devices using Python programming.
This chapter includes the details of embedded systems, its definition, block diagram,
comparison of SBC models, Specifications, I/O devices (Storage, display, keyboard and mouse),
Network access devices.
1.1 Embedded System
• An embedded system is a computer system which can perform many tasks such as to access,
to process, to store, to control the data in various electronic systems.
• Embedded system is a combination of hardware and software.
• Software is usually known as firmware that is embedded into the hardware.
• Embedded systems are application specific, organized hardware which can be controlled by
specific software.
(1.1)
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 1-2 Introduction to Embedded ….
• One of the important features of the embedded systems is that it gives the output within the
specified time limits.
• Embedded systems are used in many appliances which are used in our daily life. It is used in
microwave, calculators, TV, remote control, home security systems, traffic control system etc.
• The hardware of embedded system mainly consists of power source,
microcontroller/microprocessor, timers, memory, I/O devises etc.
• The software consists of compliers, integrated development environment (IDE), assembler,
simulators etc.
• Usually, embedded C, embedded C++, embedded JAVA, assembly language are used in
embedded system programming.
• The block diagram of embedded systems is shown in Fig. 1.1.
• As shown in Fig. 1.1, embedded system consists of processor, program memory, data
memory, processor, power supply, parallel ports, serial communication ports, I/O interfacing
devices and application specific circuits.
Input devices
interfacing / Driver circuits
Program
Processor memory and data
memory
Output interfacing
/ Driver circuits
Memory
• As shown in Fig. 1.2, embedded system is consists of sensor, ADC (Analog to Digital
Converter), processor, DAC (Digital to analog Converter), actuators, memory etc.
• Sensor measures the physical quantity and converts it into an electrical signal. The output of a
sensor is usually in analog form.
• ADC converts this analog output received by sensor into digital signal.
• Processor processes the data, calculates the output and stores it in memory.
• As this data has to be transmitted for further process or action, it has to be converted in to
analog form again.
• DAC converts this digital output into analog form.
• Actuator compares the data with the expected output which is stored in memory and then
further action is taken by the actuator.
Characteristics of Embedded Systems
• Embedded system usually performs a specialized operation.
• Embedded system must be of size to fit on a single chip.
• It must perform fast enough to process the data in real time.
• It has consumed less power to extent battery life.
• It has to monitor the data without any delay to give real time outputs.
• Microprocessor or microcontroller is used as a processor in embedded system.
• Memory has to be sufficient to store its software.
• It should contain peripherals to connect input/output devices.
• Software must be flexible and secure with more features.
Advantages of Embedded System:
• Low power consumption.
• Low cost.
• Small size.
• Enhanced real time performance.
• Easily customizable for a specific application .
Disadvantages of Embedded System
• High development cost.
• Time consuming design process.
• As its application specific, less market available.
composite video/audio output, power supply, status LEDs etc. As per the application, the slots can
vary.
Ethernet port
USB slot for
Memory
power supply
microSD
slot
GPIO pins Processor Single board
computer
External
HDMI Composite USB ports
connector video/audio out
Status
LEDs
• The BeagleBoard and BeagleBone were also developed to help, educate and promote the
benefits and usage of open source hardware/software in embedded computing.
• Specifications of SBCs vary as per the application. Some of the SBCs come with I/O
interfaces required for audio applications, networking applications or wireless
applications. Some of the SBC contains expansion slots for PCI, ISA, VGA etc.
• SBC uses various types of processors such as ARM, Intel, other power architectures. Each
processor family has its own attributes that appeal to a specific application. ARM
processor is based on RISC (Reduced Instruction Set Computer) architecture has digital
signal processing capabilities. ARM processor is very popular for its low power
consumption. Intel processor is mainly used in defense and aerospace applications. Power
architecture is based on RISC which supports legacy upgrades.
• Most of the SBCs use Linux operating system.
• Popular examples of SBCs are Raspberry Pi, BeagleBoard, BeagleBone, PandaBoard,
Cubieboard, Marsboard, Hackberry, Udoo, APC 8750, Intel Thin etc.
• Important Factors considered while selecting SBC are power, form factor, backward pin
compatibility, processor type, memory, operating system, I/O devices, overall
performance.
1.2.3 Comparison of SBC Models
• Single Board Computers are used in most of the electronic gadgets such as smart phones,
tablets.
• Some notable SBCs are available in the market for the development of hardware and
software such as Raspberry Pi, Beagles (BeagleBoard, BeagleBoardxM, BeagleBone,
BeagleBone Black), PandaBoard, MK802, MK808, Cubieboard, MarsBoard, Hackberry,
Udoo, DragonBoard. Intel Joule, nVidia Jetson etc. Recently, Intel has introduced Atom
processor based on MinnowBoard.
• However, out of all these types, Raspberry Pi and The Beagles/BeagleBone Black are most
cost effective and small sized SBCs.
• Below section describes the specifications and details of I/O devices of these SBCs.
Features of few SBCs are given below:
1. BCM5871X
• The BCM5871X is a series of quad-core 64-bit ARM processor specifically designed for
networking applications and NFV applications, control panel processing for Ethernet
switches.
• Network attached storage (NAS) etc. The BMC5871X has advanced computing,
networking and virtualization functions on a single SoC (System-on chip) with good
performance and power efficiency.
Features:
o Quad-core ARM Cortex.
o Hardware virtualization support.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 1-7 Introduction to Embedded ….
5. Snapdragon 410
• Snapdragon 410 is 64 bit ARM Cortex A53 SoC mostly used in mobile phones.
• It is quad core processor and has Adreno 306 graphics card, memory controller,
Bluetooth, UMT/LTE radio etc.
The comparison of above SBCs is given in below table.
Table 2.1 : Comparison of SBCs
Processor Broadcom TI AM3358 based Intel Atom T5700 nVidia Qualcomm
BCM2837 based on ARM Cortex- 4-plus-1 based Snapdragon 410C
on ARM Cortex- A8 on ARM based on ARM
A53 Cortex-A15 Cortex-A53
Architecture 64 bit RISC 32 bit RISC 64 bit x86 32 bit RISC 64 bit RISC
Cores Quad cores Single core Quad core Quad core Quad core
Clock Speed 1.2 GHz 1 GHz 1.7 GHz burst to 2.3 GHz 1.2 GHz
2.4 GHz
GPU Broadcom Power VR Intel HD nVidia Aualcomm Adreno
VideoCore IV SGX530 Kepler GPU 306
Memory Type LPDDR2 DDR3 LPDDR4 DDR3L LPDDR3
Memory 1 GH 512 MB 4 GB 2 GB 1 GB
Onboard Storage No 4 GB 16 GB 16 GB 8 GB
eMMC Flash eMMC Flash eMMC Flash eMMC Flash
Supported Android, Various Android, Various Ubuntu Desktop/ Linux 4 Tegra Android, Various
Operating Linux Distributions, Linux Core, (Ubuntu), Linux Distributions
Systems Windows 10 IoT Distributions Ostro/Yocto Android Windows 10 IoT
Core Linux, Windows Core
10 IoT Core
Wifi facility Yes No Yes No Yes
Bluetooth facility Yes No Yes No Yes
GPIO 40 possible with 69 possible with 8 Dedicated/ 48 8 Dedicated 12
remapping remapping when remapping
interface pins
GPIO Voltage 3.3 V 3.3 V 1.8 V 1.8 V 1.8 V
PWM 2 8 4 4 0
USB 4 × Type A 1 × Type A-mini 1 × Type C 3.1, 1 × Type A- 1 × Type A-micro,
Client, 1 × Type A 3.0 Micro, 2 × Type A 2.0
1 × Type A Host 1 × Type A 3.0
… (Contd.)
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 1-9 Introduction to Embedded ….
Memory
Primary Secondary
Masked
SRAM DRAM NVRAM Flash EEPROM EPROM PROM
ROM
• Usually embedded system consists of tiny memory chips from 128 MB or 32MB. SBCs
usually contain flash memory from 2 GB to 32 GB. Some of them have memory expansion
slots.
1.3.2 Keyboard and Mouse
• This is one of the input devices. A keyboard is an array of switches which can include
some internal logic circuit to interface the embedded systems.
• There are various types of keyboards used in embedded systems.
• The keyboards can be interfaced to SBC through USB port or on backplane. Some of
them are discussed below.
(i) Membrane Keyboard:
o In membrane keyboard, the keys are cushioned with rubber or silicone shell. These keys
are very sensitive to the pressure applied on it.
o Membrane keyboard consists of three layers such as a top membrane layer, an inner
middle layer and a bottom membrane layer.
o A conductive which is in between these two layers gets activated when a pressure is
applied on it. This type of keyboard can work better with high speed of typing.
o Membrane keyboards are available at reasonable cost. However, if keys are not hit
properly with sufficient pressure then keys are not registered. This is the major issue of
membrane keyboard.
o Another problem is due to rubber dome membrane. There is a rubber dome membrane
which supports all the keys. This membrane is designed to resist depression. However,
due to this membrane, the keys may not resume their original position after user
withdraws his finger from the key.
(ii) Mechanical Keyboards:
o Mechanical keyboards are very popular due to its durability and responsiveness
(accuracy). They are expensive compared with membrane keyboards.
o Key switches are used in mechanical keyboards by which keys hit a keystroke and
physically trigger a switch that sends a signal to register the key press.
o Working mechanism of mechanical keyboards and membrane keyboard is similar.
o Mechanical keyboard also resists keystroke that is the keys return to their initial position
once a user removes their fingers. In these types of keyboards, it uses springs instead of
rubber membrane. Springs result in smoother and more accurate keystrokes. This feature
makes mechanical keyboard more superior and popular.
o It also supports high typing speed with long durability. However, mechanical keyboards
produce more noise during use as compared with membrane keyboards.
(iii) Wireless Keyboards:
o The main benefit of wireless keyboards is that it reduces wiring and can be operated from
a distance.
o Two main technologies are used in wireless keyboards, Bluetooth and radio-frequency
(RF).
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 1-12 Introduction to Embedded ….
o Bluetooth is the most popular technology used to interface the keyboard to SBC. It has
limited range of communication. Radio- frequency keyboards utilize a broadcast
technique similar to Wi-fi and can be interfaced to SBC. Through USB dongle these
keyboards can be attached with SBC.
o Wireless keyboards need recharging periodically, modern keyboards usually can work for
months.
(iv) Rollup USB Keyboards:
o Nowadays, rollup USB wired keyboards are available in market. These keyboards can
blend easily and further can be rolled.
o They are small in size and light in weight. Due to its compact structure, they are
becoming popular in travelling professionals.
o Rollup keyboards are similar to the basic keyboard, only their manufacturing is little bit
different than the basic keyboard.
o Rollup keyboards are generally waterproof. They are designed to resist spills and
immersion in water. This keyboard produces very low noise which can be barely detected.
(v) Projection Keyboards:
o Projection keyboards are also known as Optical Virtual keyboard. They are latest
innovation in the keyboard technology.
o They usually use lasers to display a visible virtual keyboard onto a surface.
o When a user selects a key on the virtual keyboard, then optical sensor or camera senses
the finger movement which is translated it into actions. Then Computer software
identifies the key and further the character pressed by the user is recognized.
(vi) TouchScreen:
o Touchscreen is an input/output device. It can be used as keyboard and also as a display.
o The touchscreen registers the position of a touch on its surface and accordingly displays
the information on the screen.
o Two types of touchscreens resistive and capacitive are usually used in SBC.
o A resistive touchscreen uses a two dimensional voltmeter to sense the position on the
screen. It consists of two conductive sheets separated by spacer balls. The top conductive
sheet is flexible so that it can touch the bottom sheet. A voltage is applied across the
sheet whose resistance causes a voltage gradient to appear across the sheet. An analog
to digital converter is used to measure the voltage and resulting position. The resistive
touchscreen is usually used in industrial applications and can be suitable for roughest
surroundings. Resistive touchscreen are also operable with gloves and touchscreen
pencils.
o Capacitive touchscreen displays are mostly used at places where a very high light
transmission is needed. The coating of SiO2 makes the surface of capacitive touchscreen
very scratch resistance. So they are usually used for applications at public places.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 1-13 Introduction to Embedded ….
• These are the few types of keyboards which are commonly used in embedded systems or
in SBCs. The keyboards which are used in PCs are more expensive and use a
microprocessor to identify the key press. The major advantage of using microprocessor is
that it can provide debouncing of the keys.
1.3.3 Display
Display is an output device. Usually, monitors are used as a display device in Personal
Computers.
(i) LCD :
• In SBC or in embedded systems usually LCD is used as a display which can be interfaced
through a slot. Size of LCD display is selected as per the application.
• Liquid Crystal Display (LCD) consists of several layers, polarized panel filters and
electrodes. The rod shaped tiny molecules are sandwiched between a flat piece of glass
and an opaque substrate. When electric charge is applied to it, these rod shaped
molecules align into two different physical positions. When electric charge is applied they
align to block the light entering thorough them and if charge is not applied then they
become transparent. When light passes through it, the desired image appears on it. LCD
is thin, flat and consumes very less energy as compared with LED displays of CRTs
(Cathode Ray Tubes).
• Types of LCD are based on displayed data such as Segment LCD, Graphical LCD, Colour
LCD etc. Segment LCD displays numbers, letters and fixed symbol. They are usually used
in industrial panels. Graphical LCD has pixels in rows and columns. By energizing a
particular set of pixels, any character can be displayed. Color LCD has two types such as
Passive Matrix and Active Matrix. Passive color LCD is simple to implement as compared
with Active color LCD. Active color LCD is sharp and has better viewing angle.
• Main specifications of LCD are resolution, viewable size, response time, refresh rate,
matrix type, viewing angle, contrast angle, aspect ratio etc.
• LCDs are used in SBC or in embedded systems as they consumes very less power, they are
small in size, low weight, flat, portable, no flicker, less screen glare which reduces
eyestrain. However, LCDs cannot display multiple resolution images. The contrast ratio for
LCD images is lesser than CRT and plasma display.
• LCD has longer response time because of which ghost images can appear or images can
be mixed.
• LCD also has narrow viewing angle which can reduce image quality. But for most of the
industrial applications LCDs are used as a display.
(ii) LED :
• Light Emitting Diode (LED) display consists of array of LEDs to emit red, green and blue
light which forms color images. LED display mainly used for outdoor big screens, traffic
lights, in TVs etc.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 1-14 Introduction to Embedded ….
(iii) Plasma :
• Plasma display is also flat display. Plasma display emits light by itself. Each pixel of plasma
display is illuminated by a tiny bit of plasma or charged gas. The mercury vapor is
inserted into vacuum glass tube. When voltage is applied, the gas generates the effect of
plasma and emits ultraviolet light which excites the phosphor to generate visible light.
Each pixel is generated by three different colors (Red, Green, Blue) which creates color
image.
1.4 Network Access Devices
• Single Board Computers and embedded systems use various network access devices for
the wired and wireless communication. Three types of embedded networking devices
which are widely used are discussed in this section.
(i) Ethernet:
• Ethernet is the standard networking device used to connect computers on a network
using wired connection.
• It is simple interface and also used to connect SBC to other devices.
• A single router and a few Ethernet cables can create a Local Area Network (LAN) which
connects devices to communicate to each other.
• Ethernet can operate in a small area such as a room, office or cabin.
• Ethernet is a network protocol that controls data transmission of LAN. When any device
connected in the network wanted to send the data to another device, it senses the carrier
on the connecting wires. If it is free, then it sends the data packet on the network. Other
device check the packet, if it is the expected receiver then it receives data.
• Ethernet connects any computer or any electronic device to its network through Ethernet
adapter or network card.
• A network interface card either integrated into the motherboard of computer or on SBC
or separately installed in the device. For Ethernet networking, a router, hub, switch or
gateway is required. A hub is a device that acts as a connecting point between devices on
a network. Cable is unshielded twisted pair (UTP) cables used in Ethernet LAN. These
cables are similar to the cables which are used for landline telephone. Ethernet can be
managed on Windows, Linex or macOS.
• Most Ethernet devices are backward compatible and can be used with lower speed
Ethernet cables and devices.
• Ethernet is still the standard for wired networking. However, today it has been replaced
by wireless networks such as Wi-fi, Bluetooth etc.
(ii) CAN Bus :
• The Control Area Network (CAN) protocol is specially developed for automotive industry.
• CAN is a serial network which can be used to establish local connections between
microcontroller in a motor vehicle.
• CAN bus protocol is a two-wire, half duplex system which is suitable for high speed
transfer of short messages.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 1-15 Introduction to Embedded ….
• CAN was basically developed to reduce cable wiring and separate electronic control units
inside the vehicle can communicate to each other.
• CAN is low cost and durable network. The major advantage of CAN is that electronic
control unit can have single CAN interface rather than having multiple analog /digital
inputs to every device. Thus, CAN reduce overall cost and weight of a system in
automobiles.
• In CAN, all the devices have CAN controller chip and so all devices can see all transmitted
messages. Each device can decide whether the message is relevant or should be filtered.
Devices can be added in CAN without any modification in the network.
• Every message in CAN has a priority. So if two devices try to send message
simultaneously, the one with highest priority can only transmit the message.
• CAN also include Cyclic Redundancy Check (CRC) code for error checking of all received
messages. Frames or messages with errors are disregarded by all the nodes or devices
and error frame can be transmitted to indicate the error in the network.
• CAN is mostly used in automobile industry. However, because of various advantages,
today CAN is used in various applications such as streetcars, light railways, long distance
trains, navigation systems, medical equipments, automatic doors etc.
(iii) I2C :
• I2C is a two wire, half duplex serial communication protocol with multi-master, multi-
slave architecture.
• I2C is used to interface low speed devices like microcontrollers, EEPROMs, A/D, D/A, I/O
peripheral or in similar embedded devices. It was invented by Philips.
• I2C bus is popular because it is simple and can have more than one master. Each slave
device has a unique address. Communication between master and slave is serial. So data
can be transferred bit by bit.
• I2C is used for single boards and also used to connect various components which are
linked via cable. I2C requires only two bus lines for communication.
• I2C can work with any baud rate. Simple master-slave relationship exists between all
components in I2C. Each device has a unique address. I2C also include collision detection
and provide arbitration.
• There are various other network devices used in SBC or in embedded systems. Most
popular and widely used network access devices and protocols are discussed in this
section.
Think Over It
Points to Remember
• An embedded system is a computer system which can perform many tasks such as to access,
to process, to store, to control the data in various electronic systems.
• Embedded system is a combination of hardware and software.
• One of the important features of the embedded systems is that it gives the output within the
specified time limits.
• The hardware of embedded system mainly consists of power source,
microcontroller/microprocessor, timers, memory, I/O devises etc.
• A single board computer or SBC is a whole computer constructed on a single circuit board
having memory, microprocessor, I/O devices and other features which are required for a
functional computer.
• SBC usually use static RAM, low cost 8 bit microprocessor and few I/O/ devices.
• There are two basic broad categories of SBCs; those which contain passive backplane and
other are standalone SBCs.
• Backplane SBC has the advantage of a standard interface for expansion cards such as ISA, PCI
etc.
• Standalone SBCs also has expansion cards which are less standardized. Backplane SBCs works
with various architectures including Intel architecture.
• Popular examples of SBCs are Raspberry Pi, BeagleBoard, BeagleBone, PandaBoard,
Cubieboard, Marsboard, Hackberry, Udoo, APC 8750, Intel Thin etc.
• Raspberry Pi is a Single Board computer developed in United Kingdom by Raspberry Pi
Foundation. It is specially developed for educational purpose. It is high performance
computer with low cost.
• BeagleBone is a low cost, community supported development platform for all learners.
• Liquid Crystal Display (LCD) consists of several layers, polarized panel filters and electrodes.
• Main specifications of LCD are resolution, viewable size, response time, refresh rate, matrix
type, viewing angle, contrast angle, aspect ratio etc.
• Light Emitting Diode (LED) display consists of array of LEDs to emit red, green and blue light
which forms color images.
• Plasma display emits light by itself. Each pixel of plasma display is illuminated by a tiny bit of
plasma or charged gas.
• Ethernet is the standard networking device used to connect computers on a network using
wired connection.
• Most Ethernet devices are backward compatible and can be used with lower speed Ethernet
cables and devices.
• The Control Area Network (CAN) protocol is specially developed for automotive industry.
• CAN bus protocol is a two-wire, half duplex system which is suitable for high speed transfer
of short messages.
• I2C is a two wire, half duplex serial communication protocol with multi-master, multi-slave
architecture.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 1-17 Introduction to Embedded ….
Exercises
[A] True or False :
1. A single board computer or SBC is a whole computer constructed on a single circuit
board having memory, microprocessor, I/O devices and other features which are required
for a functional computer.
2. The Control Area Network (CAN) protocol is specially developed for chemical industry.
3. Mechanical keyboard has more durability compared with other type of keyboards.
4. BeagleBone is a low cost, community supported development platform for all learners.
5. Usually ARM processors are used in SBC.
[B] Multiple Choice Questions :
1. Which of the following is NOT a disadvantage of embedded systems?
(a) High development cost (b) Time consuming design process
(c) Less market available (d) Small size
2. Ethernet port is provided to connect other devices to SBC. True or False?
(a) True (b) False
3. Which of the following is a type of SBC?
(a) Toshiba (b) BeagleBone
(c) Intel (d) Sony
4. LED consumes more energy than LCD. True or False?
(a) True (b) False
5. CAN protocol is specifically designed for _________ industry.
(a) Pharmaceutical (b) Home automation
(c) Automobiles (d) Farming
[C] Fill in the Blanks:
1. Embedded system is a combination of _____ and _____.
2. The disadvantage of embedded system is _____ development cost.
3. HDMI port provides digital ____ and _____ output.
4. ____ slots are given on SBC to increase the available memory.
5. Most of the SBCs use _____ operating system.
6. BeagleBone Black is a type of ____ .
[D] Short Answer Questions:
1. What is an embedded system?
2. What is SBC?
3. State any two characteristics of embedded system.
4. State any two features of SBC.
5. State any two advantages and disadvantages of embedded system.
6. Define SBC.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 1-18 Introduction to Embedded ….
Answers
[A] True or False :
(1) True (2) False (3) True
(4) True (5) True
[B] Multiple Choice Questions :
1. (d) 2. (a) 3. (b) 4. (b) 5. (c)
[C] Fill in the Blanks :
(1) Hardware and Software (2) High (3) Video and Audio
(4) MicroSD (5) Linux (6) SBC
✍✍✍
Unit 2…
Architecture of System on Chip (SOC)
th
Eben Christopher Upton is born on 5 April 1978 and is a British
technical director and ASIC architect for Broadcom. He is also a
founder and former trustee of the Raspberry Pi Foundation, and now
CEO of Raspberry Pi (Trading) Ltd.
He has completed a Bachelor of Arts degree in Physics and
Engineering in 1999 at the University of Cambridge . Then he went on
to do the Cambridge Diploma in Computer Science graduating in
2001.
After his diploma, Upton was a research student in the Computer
Laboratory, University of Cambridge. After finishing his Ph.D. he took
a Master of Business Administration (MBA) at the Cambridge Judge
Eben Christopher Upton Business School while working in industry.
Upton was Director of Studies in Computer Science at St John's College, Cambridge, with
responsibility for undergraduate admissions. During his academic career, he co-authored papers
on mobile services, Human–computer interaction (HCI), Bluetooth and data dependency graphs.
He has been a visiting Researcher at Intel Corporation, Founder and Chief Technology Officer at
Idea works 3D and a software engineer at IBM.
Introduction
• A System-on-chip (SoC) is an integrated circuits (IC) which has most of the components of a
computer or any electronic system. These components include CPU (Central Processing Unit),
memory, I/O devices, graphical processing unit (GPU) etc.
• SoC is a complete electronic system which may contain analog, digital or radio frequency
functions. SoC is specially designed to meet the standards of required electronic circuits of
various computer components onto a single substrate or chip. Thus, instead of assembling
several chips and components onto a circuit board, the SoC fabricates all required circuits into
one unit.
• Unlike the motherboard based PC architecture which has various components on a circuit
board, SoC integrates all these components on a single chip.
• As SoC is an IC which contains both hardware /software, it consumes less power and has
better performance. It has small size and it is more reliable than multi chip systems.
• Best examples of SoC are smart phones, Internet of Things, embedded systems, tablets,
mobile computing, edge computing etc.
• There are some issues with SoC such as higher prototyping and architecture costs, it is more
complex to debug. It is not cost effective and requires more time to manufacture.
Advantages of SoC:
The basic purpose of using SoC is to have all components on a single chip with minimum
components.
(2.1)
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 2-2 Architecture of System on Chip (SOC)
• Basic architecture of SoC is shown in Fig. 2.1. Processor is the heart of SoC. Usually, SoC
has multiple core processors. It can be a microcontroller, a microprocessor or digital
signal processor or an application specific instruction set processor.
• SoC contains memory for storage. It may have RAM, ROM, EEPROM or flash memory.
• SoC include external interfaces such as USB, Ethernet, HDMI or can have Wi-fi and
Bluetooth which help to meet the industry standard communication protocol.
• SoC also has GPU (Graphical Processing Unit) to visualize the interface.
• Voltage regulators, oscillators, clocks, ADC/DAC are also part of SoC.
• Universal Asynchronous Receiver Transmitter (UART) is included which is used to transmit
or receive serial data.
• SoC has internal interface bus or network to connect all the individual blocks on SoC.
As mentioned earlier, SoC is a silicon chip having all the components fabricated on it which
makes its size very small and also reduces wiring. Nowadays, SoCs are becoming popular because
of its application, small size and low power consumption.
Ethernet port
Micro SD card
(Underneath) USB ports
• USB ports: This is a common port available for various peripherals such as mouse,
keyboard or any other I/O device. With the help of USB port, the system can be expanded
by connecting more peripherals.
• SD card: SD card slot is available on Raspberry Pi. An SD card with an operating system
(OS) installed is required for booting the device.
• Ethernet: Ethernet connector allows access to wired network. It is available only on the
Model B of Raspberry Pi.
• Power supply: Micro USB power connector is available onto which a 5V Power supply
can be connected.
• Camera module: Camera Serial Interface (CSI) connects Broadcom processor to Pi
camera.
• Display: Display Serial Interface (DSI) is used for connecting LCD to Raspberry Pi using 15
pin ribbon cable. DSI provides high resolution display interface which is specifically used
for sending video data.
2.2.2 Pin Description of Raspberry Pi
A row of GPIO (General Purpose Input Output) pins is available on Raspberry Pi. A 40 pin
header is provided on Raspberry Pi as shown in below Fig. 2.4.
GPIO 27 13 14 Ground
GPIO 22 15 16 GPIO 23
GPIO 5 29 30 Ground
• Any of GPIO pins can be used as an input or output pin if they are designated in the
software. The output pin can be set to high (3.3 V) or low (0 V). GPIO pin designated as an
input pin can be read as high (3.3 V) or low (0 V).
• Two 5 V (pin no. 2 & 4) and two 3.3 V (pin no. 1 & 17) pins are available on the Raspberry
Pi board. Also a number of ground pins (pin no. 6, 9, 14, 20, 25, 30, 34, 39) are available.
Remaining pins are all general purpose 3.3 V pins, that is outputs are set to 3.3 V and
inputs are 3.3 V tolerant.
• GPIO 2 and GPIO 3 pins (pin no. 3 & 5 ) : SDA (I2C1 & 2) are pins of the I2C on the Pi.
SDA includes a fixed 1.8 kΩ pull-up to 3.3 V. That is, these pins are not suitable for use as
a general purpose I/O where no pull-up resistor is desired.
• GPIO 14 & GPIO 15: These pins (pin no. 8 & 10) are used as transmit and receive pins for
UART on Pi.
• GPIO 0 & GPIO 1: These pins (pin no. 27 & 28) are generally kept reserved for I2C
communication with an EEPROM.
• GPIO 7 & GPIO 8: These pins (pin no. 24 & 26) are used as Special Peripheral Interface
(SPI) to communicate with other peripherals.
• GPIO 12 & GPIO 13: Hardware Pulse Width Modulation (PWM) are available on these
pins (pin no. 32 & 33).
• GPIO 19: Pin number 35 is used by PCM to provide a frame-sync signal to an external
audio device such as DAC.
• GPIO 20: Pin number 38 is used by PCM as data input from audio device such as an I2C
microphone.
• GPIO 21: Pin number 40 is used by PCM to provide a data output signal to an external
audio device such as DAC.
The brief description of all the pins of Raspberry Pi is tabulated in below table:
Table 2.1 : Pin Description of Raspberry Pi
Samsung K4P2G324ED
2G-bit DRAM ARM1176JZF-S
Stacked BGA ARM Processor Core
OpenGL-ES1.1/2.0
VideoCore GPU
HD Video Encoder / Decoder LCD
1080p MIPI LCD
I/O USB
CSI
H264, MPEG2, JPEG PAL / TV
I/O SPI Encoder / Decoder NTSC
1080p HDTV
Graphics Accelerator HDMI
I/O GPIO
Codec
I/O I2C
VideoCore 1 VideoCore 2
L
I/O UART0
Audio
Camera MIPI R
PLLs SDIO
CSI / ISP
Crystal
20 MegaPixel SD memory
@ 220MP/Sec
• It also contains advanced Image Sensor Pipeline (ISP) for connecting 20 MP camera.
• It contains Timers, Interrupt controller, GPIO, USB, PCM, I2C, DMA controller, I2C/SPI
slave, SPIO, PWM, UART0, UART1.
• The BCM 2835 has 3 Auxiliary peripherals; one mini UART and two SPI masters. They
share same area in the peripheral and have common interrupts. They are controlled by
auxiliary enable register.
• Two auxiliary registers controls interrupt status register, auxiliary enable register.
• Mini UART has to be enabled before use. Mini UART has following features as:
o 7 or 8-bit operation.
o One start bit and one stop bit.
o No parities.
o Break generation.
o 8 symbols deep FIFOs for receive and transmit data.
o Auto flow control with programmable FIFO level.
o 16550 registers.
o Baud rate derived from system clock.
• However, as it is mini UART, it does not have following:
o Break detection.
o Framing error detection.
o Parity bit.
o Receive time-out interrupt.
o DSR (Data Set Ready), DTR (Data Terminal Ready), RI (ring Indicator) signals.
• Two SPIs (Special Peripheral Interface) have to be enabled before use. They have
following features:
o Single bit length between 1 and 32-bit.
o Multi beat infinite bit length.
o Three independent chip select per master.
o 32 bit wide transmit and receive FIFOs.
o Wide clocking range.
o Programmable data out hold time.
o Shift in-out MS or LS bit first.
o Clock inversion (idle high or idle low).
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 2-11 Architecture of System on Chip (SOC)
However, there are some issues with SPI. There is no SPI standard in any form. Some SPI
interfaces are widely used with memory devices, so their rules are followed. The universal SPI has
been developed to work with the non-standard SPI devices.
• The BroadCom Serial controller (BSC) is a master, fast mode (400 kb/s) BSC controller.
BSC is compatible to I2C bus.
• Majority of the hardware pipelines and peripherals of BCM2835 are bus master which
manages their own data.
• DMA (Direct Memory Access) controllers are directly connected to the peripherals. The
BCM2835 DMA controller provides 16 DMA channels.
• There are 54 general purpose I/O (GPIO) lines split into two banks. All GPIO have at least
two alternative functions. The GPIO peripherals have three dedicated interrupt lines.
These lines are triggered by the setting of bits in the event detect status register.
• The ARM has two types of interrupt sources; interrupt coming from the GPU peripherals,
interrupt coming from local ARM control peripherals and special events interrupts. For
each interrupt source (ARM or GPU) there is an interrupt enable bit (read/write) and an
interrupt pending bit (read only).
• The PCM audio interface provides high quality serial audio streams. It supports many
classic PCM formats including I2S.
• Pulse Width Modulator (PWM) controller have features as: (a) two independent output bit
streams, clocked at a fixed frequency (b) bit streams configured individually to output of
PWM or to serialized version of 32-bit word (c) PWM output have variable input and
output resolutions.
• Serial Interface Peripherals (SPI) have features as: (a) implement three wire aerial protocol
SPI or SSP (Synchronous Serial Protocol) (b) provide supports for polled interrupt or DMA
operation (c) implements LoSSI Master (Low Speed Serial Interface).
• The BCM2835 has two UARTs (Universal Asynchronous Receiver/Transmitter). The UART
performs serial to parallel conversion of data characters received from external peripheral
devices or modem. The UART provides separate 16 × 8 transmit and 16 × 12 receive FIFO
memory. The UART contains standard asynchronous communication bits (start, stop,
parity). However, DSR, DTR and RI are not supported.
BCM2835 uses ARM16JZF-S processor as CPU. The architecture, explanation of each block
and its features are discussed in next section.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 2-12 Architecture of System on Chip (SOC)
POWERED
Instruction ARM Data
cache TM cache
TrustZone
TCRAM 0 enabled TCRAM 0
TM
TCRAM 1 ARM 11 core TCRAM 1
Memory management
ARM1176JZF-S
o Instruction and data Memory Management Units (MMUs), managed using MicroTLB
structures backed by Main TLB.
o Virtually indexed and physically addressed caches.
o 64-bit interface to both caches.
o Tightly-Coupled Memory (TCM) which can be used as local RAM with DMA.
o External coprocessor support, trace support.
o JTAG-based debug.
o ARM1176JZF-S processor includes Vector Floating Point (VFP) coprocessor whereas
ARM1176JZ-S does not include VFP. Other features of both the processors are same.
o The ARM1176JZ-S processor has three instruction sets as : 32-bit ARM instruction set
used in ARM state with media instructions, 16-bit Thumb instruction set used in
Thumb state and 8-bit JAVA bytecodes used in Jazelle state.
Components of the ARM1176JZ-S Processor:
The block diagram of ARM1176JZ-S processor is shown in Fig. 2.7.
ARM1176JZF-S
JTAG ETM Coprocessor
interface interface interface VIC interface
Vector
floating point
coprocessor
System
metrics
(iv) Modes and exceptions: The ARM1176JZ-S processor provides a set of operating modes
to support complex operating systems, user applications and real-time demands. There are 8
operating modes out of which 6 are exception processing modes:
• User
• Supervisor
• Fast interrupt
• Normal interrupt
• Abort
• System
• Undefined
• Secure monitor.
(v) Thumb instruction set: The Thumb instruction set contains a subset of the 32-bit ARM
instruction encoded into 16-bit wide opcodes. This reduces the amount of memory required for
instruction storage.
(vi) DSP instructions: The DSP extensions to the ARM instruction set provide:
• 16-bit data operations.
• Saturating arithmetic.
• MAC operations.
The processor executes multiply instructions using a single cycle 32 × 16 implementation. The
processor can perform 32 × 32, 32 × 16 and 16 × 16 multiply instructions (MAC).
(vii) Media extension: The ARMv6 instruction set provides media instruction to complement
the DSP instructions. There are 4 media instruction groups:
• Multiplication instructions for handling 16-bit and 32-bit data, including dual-
multiplication instructions that operate on both 16-bit halves of their source registers.
This group includes an instruction that improves the performance and size of code for
multi-word unsigned multiplications.
• Single Instruction Multiple Data (SIMD) instructions to perform operations on pairs of 16-
bit values held in a single register, or on sets of four 8-bit values held in a single register.
The main operations supplied are addition and subtraction, selection, pack, and
saturation.
• Instructions to extract bytes and halfwords from registers, and zero-extend or sign-extend
them. These include a parallel extraction of two bytes followed by extension of each byte
to a halfword.
• Unsigned Sum-of-Absolute-Differences (SAD) instructions. These are used in MPEG motion
estimation.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 2-16 Architecture of System on Chip (SOC)
(viii) Datapath: The Datapath consists of 3 pipelines: (a) ALU, shift and Sat pipeline, (b) MAC
pipeline, (c) Load/store pipeline
(a) ALU, Shift and Sat pipeline:
The ALU, Shift and Sat pipeline executes most of the ALU operations, and includes a 32-bit
barrel shifter. It consists of three pipeline stages:
ALU: The ALU stage performs all arithmetic and logic operations and generates the condition
codes for instructions that set these flags. The ALU stage consists of a logic unit, an arithmetic
unit and a flag generator. The pipeline logic evaluates the flag settings in parallel with the main
adder in the ALU. The flag generator is enabled only on flag-setting operations. The ALU stage
separates the carry chains of the main adder for 8-bit and 16-bit SIMD instructions.
Shift: The shift stage contains the full barrel shifter. Shift stage performs all shifts, including
those required by the LSU. The shift stage implements saturating left shift that doubles the value
of an operand and saturates it.
Sat: The Sat stage implements the saturation logic required by the various classes of DSP
instructions.
(b) MAC pipeline: The MAC pipeline executes all of the enhanced multiply and multiply-
accumulate instructions.
The MAC unit consists of a 32 × 16 multiplier and an accumulate unit that is configured to
calculate the sum of two 16 × 16 multiplies. The accumulate unit has its own dedicated single
register read port for the accumulate operand. To minimize power consumption, the processor
only clocks each of the MAC and ALU stages when required.
(c) Load/store pipeline: Load/store pipeline is a part of the Load/Store Unit (LSU). LSU
encompasses the entire L1 data side memory system and the integer load/store pipeline. This
includes:
• the L1 data cache.
• the data side TLB.
• the integer store buffer.
• the NEON store buffer.
• the integer load data alignment and formatting.
• the integer store data alignment and formatting.
The pipeline accepts one load or store per cycle that can be present in either pipeline 0 or
pipeline 1. This gives the processor flexibility when scheduling load and store instructions.
(ix) Branch prediction: The Integer Core uses both static and dynamic branch prediction. All
branches are predicted where the target address is an immediate address or fixed-offset PC-
relative address.
The first level of branch prediction is dynamic through a 128-entry Branch Target Address
Cache (BTAC). If the PC of a branch matches an entry in the BTAC, the processor uses the branch
history and the target address to fetch the new instruction stream.
The processor might remove dynamically predicted branches from the instruction stream and
might execute such branches in zero cycles.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 2-17 Architecture of System on Chip (SOC)
If the address mappings are changed then the BTAC must be flushed. A BTAC flush instruction
is provided in the CP15 coprocessor.
The processor uses static branch prediction to manage branches not matched in the BTAC.
The static branch predictor makes a prediction based on the direction of the branches.
(x) Return stack: The processor includes a three-entry return stack to accelerate returns
from procedure calls.
For each procedure call, the processor pushes the return address onto a hardware stack.
When the processor recognizes a procedure return, the processor pops the address held in the
return stack that the prefetch unit uses as the predicted return address.
2. Load Store Unit (LSU):
• The Load/Store Unit (LSU) manages all load and store operations. The load/store pipeline
decouples loads and stores from the MAC and ALU pipelines. When the processor issues
LDM and STM instructions to the LSU pipeline, other instructions run concurrently subject
to the requirements of supporting precise exceptions.
3. Prefetch Unit:
• The main purpose of Prefetch Unit (PFU) is to perform speculative fetch of instructions
ahead of the DPU by predicting the outcome of branch instructions and to format
instruction data in a way that aids the DPU in efficient execution.
• The PFU fetches instructions from the memory system under the control of the DPU and
the internal coprocessors CP14 and CP15.
• In ARM state, the memory system can supply up to two instructions per cycle.
• In Thumb state, the memory system can supply up to four instructions per cycle.
• The PFU buffers up to three instruction data fetches in its FIFO. There is an additional
FIFO between the PFU and the DPU that can normally buffer up to eight instructions. This
reduces or eliminates stall cycles after a branch instruction. This increases the
performance of the processor.
Program flow prediction occurs in the PFU by:
• Predicting the outcome of conditional branches using the branch predictor and for direct
branches, by calculating their destination address using the offset encoded in the
instruction.
• Predicting the destination of procedure returns using the return stack.
• The DPU resolves the program flow predictions that the PFU makes.
• The PFU fetches the instruction stream as dictated by:
o The program counter.
o The branch predictor.
o Procedure returns signaled by the return stack.
o Exceptions including aborts and interrupts signaled by the DPU.
o Correction of mispredicted branches as indicated by the DPU.
• The PFU starts instruction fetches at a rate that is determined dynamically using a
prediction scheme which aims to ensure that the pipeline is kept fed with instructions
without over-fetching instructions that are not used.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 2-18 Architecture of System on Chip (SOC)
• Fetching of unused instructions consumes extra power and can impact performance.
• The prefetch unit fetches instructions from the instruction cache, Instruction TCM, or from
external memory and predicts the outcome of branches in the instruction stream.
4. Memory System:
The memory system provides the core with following:
• Separate instruction and data caches.
• Separate instruction and data tightly-coupled memories.
• 64-bit datapaths throughout the memory system.
• Virtually indexed, physically tagged caches.
• Memory access controls and virtual memory management.
• Support for four sizes of memory page.
• Two-channel DMA into TCMs.
• I-fetch, D-read/write interface, compatible with multi-layer AMBA AXI.
• 32-bit dedicated peripheral interface.
• Export of memory attributes for second-level memory system.
Sections in Memory System:
The memory system consists of following sections:
(i) Instruction and data caches.
(ii) Cache power management.
(iii) Instruction and data TCM.
(iv) TCM DMA engine.
(v) DMA features.
(vi) Memory management unit.
These sections are described in details as follows:
(i) Instruction and data caches:
The core provides separate instruction and data caches. The cache has the following features:
• Independent configuration of the instruction and data cache during synthesis to sizes
between 4 kB and 64 kB.
• 4-way set-associative instruction and data caches. Each can be locked independently.
• Pseudo-random or round-robin replacement.
• Eight word cache line length.
• The MicroTLB entry determines whether cache lines are write-back or write-through.
• Ability to disable each cache independently, using the system control coprocessor.
• Data cache misses that are non-blocking. The processor supports up to three outstanding
data cache misses.
• Streaming of sequential data from LDM and LDRD operations, and sequential instruction
fetches.
• Critical word first filling of the cache on a cache-miss.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 2-19 Architecture of System on Chip (SOC)
• All the cache RAM blocks and the associated tag and valid RAM blocks can be
implemented using standard ASIC RAM compilers. This ensures optimum area and
performance of the design.
• Each cache line is marked with a Secure or Non-secure tag that defines if the line contains
Secure or Non-secure data.
(ii) Cache power management:
To reduce power consumption, the core uses sequential cache operations to reduce the
number of full cache reads. If a cache read is sequential to the previous cache read and the read is
within the same cache line, only the data RAM set that was previously read is accessed. The core
does not access tag RAM during sequential cache operations.
To reduce unnecessary power consumption additionally, the core only reads the addressed
words within a cache line at any time.
(iii) Instruction and data TCM:
Because some applications might not respond well to caching, configurable memory blocks
are provided for Instruction and Data Tightly Coupled Memories (TCMs). These ensure high-speed
access to code or data.
An Instruction TCM typically holds an interrupt or exception code that the processor must
access at high speed, without any potential delay resulting from a cache miss.
A Data TCM typically holds a block of data for intensive processing, such as audio or video
processing.
Each TCM can be configured to be Secure or Non-secure.
(iv) TCM DMA engine:
The size of the Instruction TCM (ITCM) and the size of the Data TCM (DTCM) can be separately
configured to be 0 kB, 4 kB, 8 kB, 16 kB, 32 kB or 64 kB. For each side (ITCM and DTCM):
• If the TCM size is configured to be 4 kB, we can get one TCM of 4 kB, on this side.
• If the TCM size is configured to be larger than 4 kB, we get two TCMs on this side, each of
half the configured size. So, for example, if an ITCM size of 16 kB is configured, we get
two ITCMs, each of size 8 kB.
Below Table lists all possible TCM configurations.
Table 2.3 : TCM configurations
Configured TCM size Number of TCMs Size of each TCM
0 kB 0 0
4 kB 1 4 kB
8 kB 2 4 kB
16 kB 2 8 kB
32 kB 2 16 kB
64 kB 2 32 kB
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 2-20 Architecture of System on Chip (SOC)
The TCM can be anywhere in the memory map. The INITRAM pin enables booting from the
ITCM.
To support use of the TCMs by data-intensive applications, the core provides two DMA
channels to transfer data to or from the Instruction or Data TCM blocks.
DMA can proceed in parallel with CPU accesses to the TCM blocks. Arbitration is on a cycle-
by-cycle basis.
The DMA channels connect with the System-on-Chip (SoC) backplane through a dedicated
64-bit AMBA AXI port.
The DMA controller is programmed using the CP15 system-control coprocessor. DMA
accesses can only be to or from the TCM, and an external memory. There is no coherency support
with the caches.
Only one of the two DMA channels can be active at any time.
(v) DMA features:
The DMA controller has the following features:
• Runs in background of CPU operations.
• Enables CPU priority access to TCM during DMA.
• Programmed with virtual addresses.
• Controls DMA to either the instruction or data TCM.
• Allocated by a privileged process (OS).
• Software can check and monitor DMA progress.
• Interrupts on DMA event.
• Ability to configure each channel to transfer data between Secure TCM and Secure
external memory.
(vi) Memory Management Unit:
The Memory Management Unit (MMU) has a unified Translation Lookaside Buffer (TLB) for
both instructions and data.
The MMU includes a 4 kB page mapping size to enable a smaller RAM and ROM footprint for
embedded systems and operating systems such as Windows CE that have many small mapped
objects.
The ARM1176JZ-S processor implements the Fast Context Switch Extension (FCSE) and high
vectors extension that are required to run Microsoft Windows CE.
The MMU is responsible for protection checking, address translation, and memory attributes,
and some of these can be passed to an external level two memory system.
The memory translations are cached in MicroTLBs for each of the instruction and data caches,
with a single Main TLB backing the MicroTLBs.
The MMU has the following features:
• Matches Virtual Address, ASID and NSTID.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 2-21 Architecture of System on Chip (SOC)
Multiply
Instruction and W/R
Decode Divide
Fetch and
Register ALU
Read Shift and
Branch
Branch
Branch forwarding
and speculation
ALU branch not forwarded/speculated
LSU branch result
• On a cache read that is sequential to the previous cache read, only the data RAM set that
was previously read is accessed, if the read is within the same cache line.
• The Tag RAM is not accessed at all during this sequential operation.
• Cache line refills can take several cycles. The cache line length is of eight words.
• The control of the level one memory system and the associated functionality, together
with other system wide control attributes are handled through the system control
coprocessor, CP15.
• Below Fig. 2.13 shows the block diagram of the cache subsystem. This Fig. 2.13 does not
show the cache refill paths.
RAMSet base address and size Write buffer data (1-2 words)
Micro
TLB
Way
select
Comparator
• By default, the dynamic branch prediction is used and if there is no information in its
history, the static prediction is used instead.
• Many branch instructions are conditional. For conditional branches, whether the branch
should be taken cannot be determined until the instruction is executed.
• The processor makes a prediction about whether the branch will be taken and fetches
based on the prediction.
• The processor must also be able to detect when it gets the prediction wrong and re-fetch
from the correct location.
• Branch prediction logic is an important factor in achieving high throughput in Cortex-R
series processors.
• If branch prediction is not specified, one has to wait until a conditional branch executes
before you could determine where to fetch the next instruction from.
• It uses a Branch Target Address Cache (BTAC) as the first line of branch prediction that
hold virtual target addresses.
• Prediction history of a branch is stored as a two-bit value in the BTAC. BTAC is a 128-
entry direct-mapped cache structure.
• Two bit values represent the following four states: Strong predict branch taken, Weak
predict branch taken, Strong predict branch not taken and Weak predict branch not
taken.
2.10 Branch Folding
• Branch folding is a technique where the Branch instruction is removed from the pipeline
and is stored in a buffer, which is executed on all dynamic predicted branches.
• It can improve the Branch CPI to under 1.
• Predicted branches that lead directly to another branch.
• Branches that are have been cancelled when fetched.
Branch instructions are removed from the pipeline if the following conditions are met:
• The instruction is not a branch with a link (address is stored in a linked register).
• The instruction does not point to a code sequence that contains a branch in the first two
instructions.
• The instruction is not break-pointed.
• The instruction is not aborted. This method can produce a CPI for branch instructions that
is much lower than 1.
Media 3D 2D
application application application
EGL
Videocore IV GPU
GPL/BSD
BSD licensed
licensed
2.12 Software
• Raspbian has been the most popular among the operating systems due to the boost
provided by the Raspberry Pi foundation.
• It is a Debian based Linux operating system easily available at the foundation website. Some
of the popular operating systems are:
o Raspbian
o CentOS
o Fedora
o Ubuntu MATE
o Kali Linux
o Ubuntu Core
o Windows 10 IoT Core
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 2-37 Architecture of System on Chip (SOC)
o RISC OS
o Slackware
o Debian
o Arch Linux ARM
o Android Things
o SUSE
o FreeBSD
o NetBSD
Think Over It
• Is the iPhone an example of SoC? Is the system saved on a processor in case of iphone?
• Which fabrication technologies are used in SoC?
• Which technology is used in Videon?
• What is the difference between SoC and CPU? ‘Soc will replace CPU in coming years’,
comment.
• What are Nolocal and Global variables used in Python?
Points to Remember
• SoC is a complete electronic system which may contain analog, digital or radio frequency
functions.
• The basic purpose of using SoC is to have all components on a single chip with minimum
components.
• If any component on SoC is not functioning properly, then it cannot be replaced. In that case,
entire SoC has to be replaced.
• Raspberry Pi is a small single board computer (SBC).
• Raspberry Pi is credit size computer which can be plugged into a monitor. It acts as
minicomputer by connecting keyboard, mouse, and display.
• Raspberry Pi uses Broadcom BCM2835 System on Chip which is ARM processor and
Videocore Graphics Processing Unit (GPU). It is the heart of the Raspberry Pi which controls
the operations of all the connected devices and handles all the required computations.
• The first generation of Raspberry Pi used BroadCom2835 SoC. The Raspberry Pi 2 used
BCM2836. The third generation of Raspberry Pi used BCM2837 SoC.
• The BroadCom2835 is a System on Chip (SoC). It contains multimedia capabilities which are
used in mobile phones and portable devices.
• The ARM1176JZ-S processor is an integer core which implements ARM11. It supports Java
bytecodes.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 2-38 Architecture of System on Chip (SOC)
Exercises
[A] True or False :
1. A System-on-chip (SoC) is an integrated circuits (IC) which has most of the components of a
computer or any electronic system.
2. SoC consumes more power.
3. Raspberry Pi is credit size computer which can be plugged into a monitor.
4. High Definition Multimedia Interface is used for transmitting video or digital audio data to
computer monitor or to digital TV.
5. GPIO pins of Raspberry works on 5V.
[B] Fill in the Blanks :
1. SoC has ____, ____, ____ and ____.
2. SoC consumes _____ power.
3. Raspberry Pi is a type of _____ .
4. ______is an official OS provided by Raspberry Pi foundation.
5. HDMI stands for ____ _____ _____ _____
6. Raspberry Pi is a ____ pin SBC.
7. Raspberry Pi uses _______ processor.
[C] Multiple Choice Questions :
1. Raspberry Pi provides on-chip _______ modules.
(a) UART (b) I2C
(c) I2S (d) All of these
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 2-40 Architecture of System on Chip (SOC)
Answers
[A] True or False :
(1) True (2) False (3) True
(4) True (5) False
[B] Fill in the Blanks :
(1) CPU, GPU, Memory and I/O devices (2) Less (3) SBC
(4) Raspbian (5) High Definition Multimedia Interface (6) 40
(7) ARM1176JZF-S
[C] Multiple Choice Questions :
1. (d) 2. (d) 3. (a) 4. (d) 5. (d) 6. (a)
✍✍✍
Unit 3…
Programming Using Python
st
Guido van Rossum a Dutch programmer was born on 31 January
1956. He is known as the creator of the Python programming
language, for which he was the "Benevolent dictator for life" (BDFL)
until he stepped down from the position in July 2018. He is
currently a member of the Python Steering Council, however he has
withdrawn from nominations for the 2020 Python Steering Council.
Van Rossum was born and raised in the Netherlands where he
received a master's degree in mathematics and computer science
from the University of Amsterdam in 1982. He has a brother, Just
Guido van Rossum van Rossum, who is a type designer and programmer who designed
the typeface used in the "Python Powered" logo.
Introduction
• In last chapter, Raspberry Pi and its architecture, the processor used in Raspberry Pi and
pipelining stages were discussed.
• This chapter deals with Operating System used for Raspberry Pi, its installation, and various
types of Operating Systems.
• This chapter will also give details of Python programming, data types, variables used in
Python, conditional statements, functions and few arithmetic programs.
3.1 Overview of Raspbian OS
(Operating System)
• Raspberry Pi OS which is formerly known as Raspbian is a Debian-based operating system for
Raspberry Pi. As Raspberry Pi Foundation has recommended Raspbian as the primary
operating system for Raspberry Pi family, it is widely used for compact single board
computers of Raspberry Pi from 2015.
• Raspberry Pi OS is a free operating system based on Debian which is optimized for the
Raspberry Pi hardware.
• Raspberry Pi OS comes with over 35,000 packages which is precompiled software bundled in
a nice format for easy installation on Raspberry Pi.
• Raspberry Pi OS is a community project under active development, with an emphasis on
improving the stability and performance of as many Debian packages as possible.
• Raspbian is a competent and versatile operating system which is suitable for a PC and it
provides a command line, a browser and tons of other programs.
(3.1)
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 3-2 Programming Using Python
• Raspberry Pi as running Raspbian can be used as a cheap and effective home computer, or it
can be used as a springboard. It can be used in countless other functional devices, from
wireless points to retro gaming machines.
3.2 Installation of Raspbian
• Raspbian is the most popular operating system for Raspberry Pi. The installation process of
Raspbian is same for all models of Raspberry Pi.
• In Raspbian, thousands of pre-built libraries to perform many tasks and optimize the OS are
available.
• Installing Raspbian on Raspberry Pi is very straightforward. Raspbian software has to be
downloaded.
• MicroSD card, a computer slot, Raspberry Pi board with basic peripherals (a mouse, keyboard,
screen and power supply) are required.
• Raspbian can be installed using NOOBS which is an operating system installation manger.
Steps for installing Raspbian are described as below:
Step 1: Downlaod Raspbian:
Download latest version of Raspbian.
Step 2: Unzip the file:
Raspbian OS is compressed, so files should be unzipped. Depending on built-in utilities,
certain programs are used to unzip the files. For Windows users, 7-zip is used. For Mac users, The
Unarchiver and for Linux, Unzip is used to unzip the files.
Step 3: Write the disc image on microSD card:
Downloaded OS require image writer to write into the SD card (microSD card). So download
‘win32 disk imager’ and write the disc image to it. For Windows users, ‘Win32 Disk Imager’ is
required. For Mac users, disk utility is required and for Linux users, Etcher is usually used.
The process of writing image is slightly different for different users. For each of these
programs, destination has to be selected to make sure that microSD card chosen and disc image
that is the unzipped Raspbian file is selected. Then select double-check and hit the button to
write.
Step 4: Put the microSD card in Raspberry Pi and boot up:
Once the disc image has been written to the microSD card, put it in Raspberry Pi board, plug
in the peripherals and provide power supply to it. Raspbian will boot directly to the desktop. The
default credentials for username are pi and password id raspberry.
• After completing above steps, Setup Options window will open, on which few settings have to
be made.
• Below steps have to be followed:
1. Select first option in the list of the setup options window which is ‘Expand File system’
option and press enter key. This will make use of all the space present on the SD card as a
full partition. It will expand the OS to fit the whole space on the SD card which can be
used as the storage memory for the Raspberry Pi.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 3-3 Programming Using Python
2. Select third option in the list of the setup option menu as ‘Enable Boot To
Desktop/Scratch’ window option. The window looks like as below (Fig. 3.1).
Fig. 3.1
• After completing above steps, it may ask to reboot the Raspberry Pi then every time system
has to be rebooted.
• After reboot, if ‘Setup Options’ screen is not visible then follow below command:
o In the ‘choose boot option window’, select the second option as Desktop Log in as user
‘pi’ at the graphical desktop and press the enter key. Once this is done, ‘Setup Options’
page will come, if not select the ‘Ok’ button at the bottom of this window which will go to
previous window. This will boot into the desktop environment which is familiar screen. If
this step is not done then the Raspberry Pi boots into a terminal each time with no GUI
options.
o Once above step is finished, select ‘finish’ button at the bottom of the page which will
reboot automatically.
Step 5: Updating the firmware:
After rebooting, the desktop screen looks like the image below:
Features of DietPi:
o Diet Processing Tool which comes in package helps in determining the installed
programs’ priority level and control schedulers.
o With the help of customization ability, performance of the hardware and software can be
adjusted.
o It uses minimum space in RAM, its size starts at just 400MB.
o It introduces lightweight Whiptail menus that take less time to execute the command line.
o It is suitable for new users and its performance can be bossted by controlling the amount
of logging according to the need using DietPi-Ramlog.
o Installation, updating is made available automatically in DietPi OS. When there is an
update available, no need to write an image for updating the system.
3. LIBREELC:
• LIBREELC is a small open source JEOS. The boot time is faster as compared with
OpenELEC. It offers backbones for backdated hardware. It was launched in 2016 to
generate better multimedia output than OpenELEC.
Features of LIBREELC OS:
o This OS can be installed in less than 20 minutes. It contains clear instruction, an SD creator
app and an installer.
o It boots up within few seconds.
o With the help of Kodi, it offers standard customizations. It contains bunch of add-ons.
o It is managed by a team of developers and provide updates every month.
o It works closely with Kodi and regularly patches while maintaining security.
4. OSMC:
• It works best to manage media content. It is an open source software that has interface
with many features. It is based on KodiOs which provides support virtually to any media
content.
Features of OSMC:
o It has several customizable built-in-images that allow Raspberry to produce high-quality
videos, pictures and other media contents.
o It takes very less time to complete the installation.
o This OS updates automatically. It will update itself automatically once every month.
o It offers Google play store. User can download, install, and start using the required
applications whenever required.
5. RISC OS:
• RISC OS is the best Raspberry OS as it is intended to serve ARM processors. It enhances
the performance and efficiency of the system.
Features of RISC OS:
o Designed by the original inventor of ARM. It is a unique open-source operating system
for Raspberry Pi.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 3-6 Programming Using Python
The steps for installing Python on various platforms are given below:
(I) Unix and Linux Installation:
• Open a Web browser and go to https://www.python.org/ downloads/.
• Follow the link to download zipped source code available for Unix/Linux.
• Download and extract files.
• To customize some options, edit the Modules/Setup file.
• run ./configure script.
• make
• make install
This installs Python at standard location /usr/local/bin and its libraries at
/usr/local/lib/pythonXX where XX is the version of Python.
(II) Windows Installation:
• Open a Web browser and go to https://www.python.org/ downloads/.
• Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version to
install.
• To use this installer python-XYZ.msi, the Windows system must support Microsoft
Installer 2.0. Save the installer file on local machine and then run it and check whether the
machine supports MSI.
• Run the downloaded file. This brings up the Python install wizard, accept the default
settings, wait until the install is finished.
(III) Macintosh Installation:
• Get instructions, for the current version with extra tools to support development on the
Mac from http://www.python.org/ download/mac/.
• For older Mac OS's before Mac OS X 10.3 (released in 2003), MacPython is available.
• Jack Jansen maintains it and access to the entire documentation is available at his website
− http://www.cwi.nl/~jack/ macpython.html. Complete installation details for Mac OS
installation are available on this site.
3.4.3 Python Variable
• Variables are nothing but reserved memory locations to store the values. When a variable
is created, some space is reserved.
• Based on the data type of a variable, the interpreter allocates memory and decides what
can be stored in the reserved memory.
• By assigning different data types to variables, integers, decimals or characters in these
variables can be stored.
• Python is completely object oriented. Variables or their types need not to be declared
before using them. Every variable in Python is an object.
• Python variables do not need explicit declaration to reserve memory space. The
declaration happens automatically when a value to a variable is assigned. The equal sign
(=) is used to assign values to variables.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 3-13 Programming Using Python
• For example :
num = 50 #num is of type int
str = "Chaitanya" #str is of type string
• Variable name is known as identifier. There are few rules that have to follow while naming
the variables in Python as given below:
o The name of the variable must always start with either a letter or an underscore (_).
For example: _str, str, num, _num are all valid names for the variables.
o The name of the variable cannot start with a number. For example: 9num is not a valid
variable name.
o The name of the variable cannot have special characters such as %, $, # etc., they can
only have alphanumeric characters and underscore (A to Z, a to z, 0-9).
o Variable name is case sensitive in Python which means ‘num’ and ‘NUM’ are two
different variables in python.
• Python allows user to assign a single value to several variables simultaneously.
For example: a = b = c = 5
• Here, an integer object is created with the value 5, and all three variables are assigned to
the same memory location.
• Multiple variables can be assigned to multiple objects.
For example: a,b,c = 5,6,"Hello"
• Here, two integer objects with values 5 and 6 are assigned to variables a and b
respectively, and one string object with the value "Hello" is assigned to the variable c.
3.4.4 Python Data Types
• There are many data types available in Python. Python has various standard data types to
define the operations possible on them and the storage method for each of them.
• Python has 5 standard data types as:
1. Numbers
2. String
3. List
4. Tuple
5. Dictionary
1. Python Numbers:
• This data types store numeric values. To number objects, a value is assigned to them.
For example: var1 = 2
var2 = 15
• The reference to a number object can be deleted by using the del statement. The syntax
of the del statement is :
del var1[,var2[,var3[....,varN]]]]
• A single object or multiple objects can be deleted by using the del statement.
For example: del var
del var_a, var_b
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 3-14 Programming Using Python
Process
Normal Code Statement - 1 input and 1 output.
Example would be setting up a variable.
Condition Block - 1 input and 2 or more potential
outputs, makes decision on output based on the
Decision
condition. Condition example would be, is A > B?
Condition
If condition
is true
If condition
is false
Conditional
code
• In Python, compound statement if, elif and else is used which will conditionally execute
blocks of statements.
• The syntax is as follows:
if expression:
statement(s)
elif expression:
statement(s)
elif expression:
statement(s)
...
else:
statement(s)
• The elif and else statements are optional. However, Python does not have a switch
statement. For all conditions, if, elif and else must be used.
if y > 0: print "y is positive"
elif y % 2: print "y is negative and even"
else: print "y is odd and negative"
Or it can be written as
if y > 0:
print "y is positive"
elif y % 2:
print "y is nagetive and even"
else:
print "y is odd and positive"
(ii) While statement
• The while statement in Python is basically for the repeated execution of a statement or
block of statements which are controlled by a conditional expression.
• The syntax for while statement is as below:
while expression:
statement(s)
• A while statement also include as else condition, break and continuous statement
count = 0
while x > 0:
x = x // 2 # truncating division
count += 1
print "The approximate log2 is", count
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 3-19 Programming Using Python
• First loop condition is evaluated. If the condition is false then the While statement ends. If
loop condition is true then the statement or block of statements which are in loop body
are executed.
• When all the statements in the loop finishes executing, the loop condition is evaluated
again to check whether another iteration is required or not.
• This process continues until the loop condition is false, then the While statement ends.
• The loop body should contain statements which can make the loop condition false, or the
loop will never end and it becomes endless loop. If it happens then a break statement is
raised.
• A loop body ends if it has return statement, then whole function ends in this case.
(iii) For statement
• In Python, the for statement is used for repeated execution of a statement or block of
statements which is controlled by an iterable expression.
• The syntax for for statement is as below:
for target in iterable:
statement(s)
• Here, keyword in is a part of syntax of the for statement. The for statement can also
include an else and break and continue statement.
Iterators:
• An iterator is any object i such that i.next() can be called without any arguments.
• i.next() returns the next item of iterator i, or, when iterator i has no more items,
raises a StopIteration exception.
• The for statement implicitly calls iter to get an iterator.
• Python provides built-in functions range and xrange to generate and return integer
sequences. The simplest way to loop n times in Python is:
for i in xrange(n):
statement(s)
• range(x) returns a list whose items are consecutive integers from 0 (included) up
to x (excluded).
• range(x,y) returns a list whose items are consecutive integers from x (included) up
to y (excluded). The result is the empty list if x is greater than or equal to y.
The break Statement
• The break statement can be only used inside a loop body.
• When break executes, the loop terminates. If a loop is nested inside other
loops, break terminates only the innermost nested loop.
• The syntax of loop is as follows:
while True: # this loop can never terminate
naturally
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 3-20 Programming Using Python
x = get_next( )
y = preprocess(x)
if not keep_looping(x,y): break
process(x,y)
The continue Statement
• The continue statement in Python returns the control to the beginning of the while
loop.
• The continue statement rejects all the remaining statements in the current iteration of
the loop and goes back to the top of the loop.
• The continue statement can be used in both while and for loops.
The else Clause on Loop Statements
• Both the while and for statements can use else clause.
• The statement after the else executes when the loop terminates naturally. However, if
the loop terminates prematurely (via break, return, or an exception) then no further
statements are executed.
• If a loop contains one or more break statements, then user has to check whether the
loop terminates naturally or prematurely.
• User can use an else clause on the loop for this purpose:
for y in some_container:
if is_ok(y): break
# item y is satisfactory, terminate loop
else:
print "Warning: no satisfactory item was
found in container"
y = None
The pass Statement
• The body of Python program cannot be empty, it must contain at least one statement.
The pass statement can be used in that case which performs no action. So when a
statement as per syntax is required and nothing is written there then pass statement can
be used.
if condition1(x):
process1(x)
elif x>33 or condition2(x) and x<5:
pass # nothing to be done in this case
elif condition3(x):
process3(x)
else:
process_default(x)
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 3-21 Programming Using Python
• The scope of variable determines accessibility of that variable. The variable can be declared as
Global variables or Local variables.
• Variables which are defined inside the function have local scope and those which are defined
outside the function have global scope.
• Local variables can be accessed only inside the function in which they are declared. Global
variables can be accessed at any location of a program by any function.
3.6.2 Types of Functions
• There are two types of functions: Built-in functions and User-defined functions.
• Built-in functions are built in Python. User-defined functions are defined by the users.
• Built-in functions of Python are listed in below table.
Table 3.2 : Python Built-in Functions
Built-in Functions
abs ( ) delattr ( ) hash ( ) memoryview ( ) set ( )
all ( ) dict ( ) help ( ) min ( ) setattr ( )
any ( ) dir ( ) hex ( ) next ( ) slice ( )
ascii ( ) divmod ( ) id ( ) object ( ) sorted ( )
bin ( ) enumerate ( ) input ( ) oct ( ) staticmethod ( )
bool ( ) eval ( ) int ( ) open ( ) str ( )
breakpoint ( ) exec ( ) isinstance ( ) ord ( ) sum ( )
bytearray ( ) filter ( ) issubclass ( ) pow ( ) super ( )
bytes ( ) float ( ) iter ( ) print ( ) tuple ( )
callable ( ) format ( ) len ( ) property ( ) type ( )
chr ( ) frozenset ( ) list ( ) range ( ) vars ( )
classmethod ( ) getattr ( ) locals ( ) repr ( ) zip ( )
compile ( ) globals ( ) map ( ) reversed ( ) _import_ ( )
complex ( ) hasattr ( ) max ( ) round ( )
[I] I/O Function (GPIO, Digital):
• Python program has to obtain data from user. It can be taken as an input from keyboard. In
Python, the input function is available as input ( ) which can be written on Python prompt. .
For example :
>>> s = input()
Hello
>>> s
‘Hello’
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 3-23 Programming Using Python
while True:
if(GPIO.input(Switch_input)):
GPIO.output(LED,GPIO.LOW)
else:
GPIO.output(LED,GPIO.HIGH)
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 3-25 Programming Using Python
(vii) The timedelta: The timedelta class is useful to find duration such as differences between
two dates or finding the date after adding a period to current date.
It is also used to find the future date or previous dates using timedelta class.
The format of timedelta is:
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0,
minutes=0, hours=0, weeks=0)
Days, seconds and microseconds are only stored internally in the timedelta object. Other
arguments are converted to those units as:
• A millisecond is converted to 100 microseconds.
• A minute is converted to 60 seconds.
• An hour is converted to 3600 seconds.
• A week is converted to 7 days.
Calendar Module
The ‘calendar’ module is used to create calendar of any month or year. It is also used to know
whether the year is a leap year or not by using isleap () function.
For example :
# to test whether leap year or not
from calendar import *
y = int (input (‘entre year: ‘))
if (isleap(y)):
print (y, ‘ is leap year’)
else:
print (y, ‘ is not leap year’)
Function Description
Python bytes() Returns immutable bytes object.
Python chr() Returns a character (a string) from an Integer.
Python compile() Returns a python code object.
Python classmethod() Returns class method for given function.
Python complex() Creates a complex number.
Python delattr() Deletes attribute from the object.
Python dict() Creates a Dictionary.
Python dir() Tries to return attributes of object.
Python divmod() Returns a tuple of quotient and remainder.
Python enumerate() Returns an enumerate object.
Python staticmethod() Transforms a method into a static method.
Python filter() Constructs iterator from elements which are true.
Python eval() Runs python code within program.
Python float() Returns floating point number from number, string.
Python format() Returns formatted representation of a value.
Python frozenset() Returns immutable frozenset object.
Python getattr() Returns value of named attribute of an object.
Python globals() Returns dictionary of current global symbol table.
Python exec() Executes Dynamically Created Program
Python hasattr() Returns whether object has named attribute.
Python help() Invokes the built-in help system.
Python hex() Converts to Integer to Hexadecimal.
Python hash() Returns hash value of an object.
Python input() Reads and returns a line of string.
Python id() Returns Identity of an object.
Python isinstance() Checks if an object is an Instance of Class.
Python int() Returns integer from a number or string.
Python issubclass() Checks if a Class is Subclass of another Class.
Python iter() Returns an iterator.
Python list() Creates a list in Python.
… (Contd.)
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 3-32 Programming Using Python
Function Description
Python locals() Returns dictionary of a current local symbol table.
Python len() Returns length of an object.
Python max() Returns the largest item.
Python min() Returns the smallest value.
Python map() Applies function and returns a list.
Python next() Retrieves next item from the iterator.
Python memoryview() Returns memory view of an argument.
Python object() Creates a featureless object.
Python oct() Returns the octal representation of an integer.
Python ord() Returns an integer of the Unicode character.
Python open() Returns a file object.
Python pow() Returns the power of a number.
Python print() Prints the given object.
Python property() Returns the property attribute.
Python range() Returns sequence of integers between start and stop.
Python repr() Returns a printable representation of the object.
Python reversed() Returns the reversed iterator of a sequence.
Python round() Rounds a number to specified decimals.
Python set() Constructs and returns a set.
Python setattr() Sets the value of an attribute of an object.
Python slice() Returns a slice object.
Python sorted() Returns a sorted list from the given iterable.
Python str() Returns the string version of the object.
Python sum() Adds items of an iterable.
Python tuple() Returns a tuple.
Python type() Returns the type of the object.
Python vars() Returns the __dict__ attribute.
Python zip() Returns an iterator of tuples.
Python __import__() Function called by the import statement.
Python super() Returns a proxy object of the base class.
… (Contd.)
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 3-33 Programming Using Python
Function Description
Python Dictionary clear() Removes all Items.
Python Dictionary copy() Returns shallow copy of a dictionary.
Python Dictionary fromkeys() Creates dictionary from given sequence.
Python Dictionary get() Returns value of the key.
Python Dictionary items() Returns view of dictionary's (key, value) pair.
Python Dictionary keys() Returns view object of all keys.
Python Dictionary popitem() Returns and removes latest element from dictionary.
Python Dictionary setdefault() Inserts key with a value if key is not present.
Python Dictionary pop() Removes and returns element having given key.
Python Dictionary values() Returns view of all values in dictionary.
Python Dictionary update() Updates the dictionary.
Python List append() Adds a single element to the end of the list.
Python List extend() Adds iterable elements to the end of the list.
Python List insert() Insert an element to the list.
Python List remove() Removes item from the list.
Python List index() Returns the index of the element in the list.
Python List count() Returns count of the element in the list.
Python List pop() Removes element at the given index.
Python List reverse() Reverses the list.
Python List sort() Sorts elements of a list.
Python List copy() Returns a shallow copy of the list.
Python List clear() Removes all items from the list.
num1 = 1.5
num2 = 3.5
Output
The sum of 1.5 and 3.5 is 5.0
[II] Python program for subtraction of 2 numbers:
# Python program for subtraction of two numbers
num1 = 5.0
num2 = 3.0
# subtract two numbers
sub = num1 - num2
num1 = 5.0
num2 = 3.0
# multiply two numbers
mul = num1 * num2
num1 = 15.0
num2 = 3.0
# division of two numbers
div = num1/num2
Output
The division of 15.0 and 3.0 is 5.0
[V] Python program for addition, subtraction, multiplication and division using functions :
#Addition function
def add(x,y):
s = x + y
print("Addition is: ",s)
#Subtraction function
def subtract(x,y):
s = x - y
print("Subtraction is: ",s)
#Multiplication function
def multiply(x,y):
s = x*y
print("Multiplication is: ",s)
#Division function
def division(x,y):
s = x/y
print("Division is: ",s)
#Function call
add(x,y)
subtract(x,y)
multiply(x,y)
divide(x,y)
Output:
Enter x: 20
Enter y: 5
Addition is: 25
Subtraction is: 15
Multiplication is: 100
Division is: 4.0
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 3-37 Programming Using Python
Think Over It
Points to Remember
• Raspberry Pi OS which is formerly known as Raspbian is a Debian-based operating system for
Raspberry Pi.
• Raspbian is the most popular operating system for Raspberry Pi. The installation process of
Raspbian is same for all models of Raspberry Pi.
• In Raspbian, thousands of pre built libraries to perform many tasks and optimize the OS are
available.
• Raspbian is the official Raspberry Pi OS, however other OS are also available which can run on
Raspberry Pi.
• Python is a general purpose interpreted, interactive, object-oriented and high-level
programming language.
• It was created by Guido van Rossum during 1985-1990 at the National Research Institute for
Mathematics and Computer Science in the Netherlands.
• Python is copyrighted. Python source code is also available under the GNU General Public
License (GPL).
• Python is designed to be highly readable. It uses English keywords frequently where as other
languages use punctuation and it has fewer syntactical constructions than other languages.
• The documentation of Python is available on heet://www.python.org/doc/. The
documentation is available in HTML, PDF and PostScript formats.
• Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when a value to a variable is assigned.
• Python has 5 standard data types as:
1. Numbers
2. String
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 3-38 Programming Using Python
3. List
4. Tuple
5. Dictionary
• The main difference between list and tuple is Lists are enclosed in brackets ( [ ] ) and their
elements and size can be changed. Tuples are enclosed in parentheses ( ( ) ) and cannot be
updated. Tuples can be thought of as read-only lists.
• The flow of a Python program is controlled by conditional statements, loops and function
calls.
• Conditional statements includes if...then statements. Loops consists of For loop, While loop
etc.
• The body of Python program cannot be empty, it must contain at least one statement. The
pass statement can be used in that case which performs no action.
• A try statement is used to catch exceptions that might be thrown as program executes.
• The try block tries to catch the errors.
• A function is a block of code which only runs when it is called.
• Functions are important as they can process data and can be called as and when required in
main program.
• Function block begin with the keyword def followed by function name and parentheses (()).
Any input parameter should be put in these parentheses.
• The return statement exit from the function.
• The scope of variable determines accessibility of that variable. The variable can be declared as
Global variables or Local variables.
• Local variables can be accessed only inside the function in which they are declared. Global
variables can be accessed at any location of a program by any function.
• Python provides three modules: datetime, time and calendar which helps user to deal with
dates, time, duration and calendars.
• The ‘epoch’ is the point where the time starts.
• Python consists of a function named ‘time’ to handle time related tasks. For this, first the time
module has to be imported by using – import time.
• The ‘calendar’ module is used to create calendar of any month or year.
• The perf_counter() and process_time() functions of ‘time’ module are used to measure the
time difference between two points in a program.
• The standard library of Python is very extensive. It offers a wide range of functions.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 3-39 Programming Using Python
Exercises
[A] True or False :
6. The main difference between list and tuple is Lists are enclosed in brackets ( [ ] ) and Tuples
are enclosed in parentheses ( ( ) ).
4. Function block begin with the keyword _____ followed by function name and parentheses (()).
5. Python provides three modules: _____, ______ and ______which helps user to deal with dates,
time, duration and calendars.
6. The ‘______’ is the point where the time starts in ‘time’ module used in Python program.
2. What is Raspbian?
5. What is Python?
3. List various types of operating systems used for Raspberry Pi. Give features of at two OS.
12. What is the use of functions? Give at least 3 examples of functions used in Python.
21. Write a Python program for the addition of two numbers. Write output of the program.
22. Write a Python program for the subtraction of two numbers. Write output of the program.
23. Write a Python program for the multiplication of two numbers. Write output of the program.
24. Write a Python program for the division of two numbers. Write output of the program.
Answers
[A] True or False :
(1) True (2) False (3) True
(4) False (5) True (6) True
[B] Multiple Choice Questions :
1. (d) 2. (a) 3. (d) 4. (d) 5. (c)
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 3-42 Programming Using Python
3. try 4. def
6. epoch
✍✍✍
Unit 4…
Interfacing of Devices Using Python
Programming
Introduction
• In previous chapters, the details of Raspberry Pi board, its pin configuration, function of
each pin were discussed. Also the introduction of Python scripting language, functions
used in Python and Python programs for addition, subtraction, multiplication and division
were discussed.
• Raspberry Pi has General Purpose Input/output (GPIO) pins which can be used to
interface many input output devices. The devices like LEDs, Sensors, display, camera etc.
can be interfaced through these GPIO pins.
• Raspberry Pi can be programmed using Python scripting language and various I/O
devices can be controlled by programming Raspberry Pi.
• In this chapter, interfacing of LED, switch, LCD, camera, serial communication GSM,
ultrasonic sensor, PIR and finger print reader are discussed. The Python programs for all
these I/O devices are also given in this chapter.
• Raspberry Pi has 40 pins GPIO connector. The latest version of the Raspberry Pi series,
Raspberry Pi Model B, has 40 GPIO pins which include power pins and ground pins.
• As discussed in chapter 3, the GPIO pin number and physical pin number of Raspberry Pi
are different.
• In GPIO numbering, pin number refers to number on Broadcom SoC and in physical
numbering, pin number refers to the pin 40-pin header on Raspberry Pi board. So, the
GPIO pins of Raspberry Pi have to be defined.
• As shown in Fig. 4.1, the numbers in the centre which are circled are the physical pins of
Raspberry Pi. These pins are known as Board Pins or numbers. The GPIO numbers such as
Physical Pin 3 is GPIO 2 which is seen by the processor. These numbering is called as GPIO
numbering or BCM numbering. So, while programming Raspberry Pi, user has to take care
about these numbering and decide which type of numbering is used in programming.
(4.1)
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 4-2 Interfacing of Devices Using Python Programming
5 V power
5 V power
GPIO 14
GPIO 15
GPIO 18
GPIO 23
GPIO 24
GPIO 25
GPIO 12
GPIO 16
GPIO 20
GPIO 21
Ground
Ground
Ground
GPIO 8
GPIO 7
GPIO 1
Ground
Ground
2
4
6
8
10
12
14
16
18
20
22
24
26
28
30
32
34
36
38
40
R
H
P
p
b
d
a
s
e
a
e
r
r
r
i
13
15
17
19
21
23
25
27
29
31
33
35
37
39
11
1
3
5
7
9
3.3 V
GPIO 2
GPIO 3
GPIO 4
Ground
GPIO 17
GPIO 27
GPIO 22
3.3 V
GPIO 10
GPIO 9
GPIO 11
Ground
GPIO 0
GPIO 5
GPIO 6
GPIO 13
GPIO 19
GPIO 26
Ground
• The installation of Python was discussed in previous chapter. Some of the popular
modules useful on the Raspberry Pi are shown in below table 4.1:
Table 4.1: Few Popular Packages Used Particularly for Raspberry Pi
Module Description URL Package name
RPi, GPIO Access to GPIO pins sourceforge.net/ python-rpi.gpio
projects/raspberry-gpio-
python
GPIOzero Simplified access to gpiozero.readthedocs.org python-gpio-zero
GPIO pins
Pygame Gaming framework pygame.org python-pygame
SimpleCV Easy API for Computer simplecv.org No package
Vision
SciPy Scientific computing www.scipy.org python-scipy
NumPy The numerical numpy.scipy.org python-numpy
underpinings of Scipy
Flask Microframework for flask.pocoo.org python-flask
web development
Feedparser Atom and RSS feed pypi.python.org/pypi/ No package
parser feedparser
Requests “HTTP for Humans” docs.python-requests.org python-requests
PIL Image processing www.pythonware.com/ python-imaging
products/pil/
wxPython GUI framework wxpython.org python-wxgtk2.8
pySerial Access to serial port https://github.com/pyserial/ python-serial
pyserial
PyUSB FTDI-USB interface bleyer.org/pyusb No package
• To use one of the packages mentioned in table, first that module has to be downloaded,
configured and installed. For example: numPy module can be installed as follows:
sudo apt-get install python-numpy
4.1.1 Setting Raspberry Pi Module
• The Raspberry Pi is actually minicomputer which is capable of doing many things. The pin
configuration of Raspberry Pi was discussed in chapter 3. Raspberry Pi can be
programmed using Python.
• To write a Python program for Raspberry, first Operating System has to be installed and
then Raspberry has to be configured.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 4-4 Interfacing of Devices Using Python Programming
• Install Raspbian with Desktop and connect keyboard, mouse and monitor to Raspberry Pi.
Windows, macOS or Linux can be used for installing OS.
• If Raspbian Lite is installed then keyboard, mouse and monitor are not required. This will
allow getting a terminal into Raspberry Pi on another computer.
4.1.2 Steps for Booting Raspberry Pi
• Booting Raspberry Pi for the first time include following steps:
o Push the microSD card into the socket on the bottom of the board.
o Plug in a USB keyboard and mouse.
o Plug the HDMI output into TV or monitor. Make sure that, monitor is ON and set to
the correct input.
o Plug in power supply and switch ON the board.
• Once the board is ON, Raspberry Pi logo appears on screen. While configuring the
Raspberry Pi board first time, Raspbian desktop environment appears on screen.
• Few things have to be set with Raspbian Pi Configuration Tool. To open it, click → Menu
Preferences → Raspberry Pi Configuration as shown in below Fig. 4.2.
• A typical laptop or desktop will have additional hardware to set the date and time;
however Raspberry Pi does not have such hardware. Raspbian is configured automatically
and get synchronized its time and date with a network Time Protocol (NTP) server when
plugged into a network.
• To write a Python program for Raspberry Pi, GPIO library is required. In Raspbian,
Python and GPIO library are preinstalled.
4.1.3 First Python Program on Raspberry Pi
• To write first Python program, open Python’s IDEL editor, In Menu →Programming → and
click on Python 3 as shown in below Fig. 4.3.
3.3 V 1 2 5 V power
GPIO 2 3 4 5 V power
GPIO 3 5 6 Ground
GPIO 4 7 8 GPIO 14
Ground 9 10 GPIO 15
R
GPIO 17 11 a 12 GPIO 18
GPIO 27 13 s 14 Ground
p
GPIO 22 15 b 16 GPIO 23
e
3.3 V 17 18 GPIO 24
r
GPIO 10 19 r 20 Ground
y
GPIO 9 21 22 GPIO 25
R1 LED1
LED
GPIO 11 23 P 24 GPIO 8 Green
i 1 kW
Ground 25 26 GPIO 7 RR11
H LED 11kkW
GPIO 0 27 28 GPIO 1
e
GPIO 5 29 a 30 Ground
d
GPIO 6 31 e 32 GPIO 12
GPIO 13 33 r 34 Ground
GPIO 19 35 36 GPIO 16
GPIO 26 37 38 GPIO 20
Ground 39 40 GPIO 21
(a) (b)
Fig. 4.4 : Interfacing LED to Raspberry Pi
• As shown in above Fig. 4.4, the anode of the LED is connected to GPIO25 (physical pin 22)
with a series resistance of 1 kΩ value. The cathode of the LED is connected to GND pin.
The GPIO25 pin has to be configured as an output pin so that Raspberry Pi can drive the
LED.
• If GPIO25 pin made High for some time and LOW for some time and if this process is kept
in a loop then LED will start blinking.
• A Python program is written to make GPIO25 pin high and low.
4.2.1 Algorithm for Blinking LED
• Import the code needed for GPIO control.
• Import the code needed for the sleep function.
• Use the chip’s signal numbers.
• Set pin 25 as an output pin.
• Create an infinite loop consisting the required code.
• Turn the LED ON.
• Wait for one second.
• Turn the LED OFF.
• Wait for one second.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 4-7 Interfacing of Devices Using Python Programming
+5V
10 kW
GPIO_IN GPIO_IN
10 kW
3.3 V 1 2 5V
GPIO 2 3 4 5Vr
GPIO 3 5 6 Ground
GPIO 4 7 8 GPIO 14
Ground 9 10 GPIO 15
R
GPIO 17 11 a 12 GPIO 18
GPIO 27 13 s 14 Ground +5V
p
GPIO 22 15 b 16 GPIO 23
e
3.3 V 17 18 GPIO 24
r
GPIO 10 19 r 20 Ground
y
GPIO 9 21 22 GPIO 25
GPIO 11 23 P 24 GPIO 8
i
Ground 25 26 GPIO 7
H
GPIO 0 27 28 GPIO 1
e
GPIO 5 29 a 30 Ground
d
GPIO 6 31 e 32 GPIO 12
GPIO 13 33 r 34 Ground
GPIO 19 35 36 GPIO 16
GPIO 26 37 38 GPIO 20
Ground 39 40 GPIO 21
• The procedure to run the program is same as explained in LED interfacing section.
• The program will print “Switch is Pressed” message when the push switch is pressed.
The time.sleep(0.5) command will insert necessary delay between two consecutive switch
press.
• The LED or any other device can be connected to see the operation of a switch. If switch is
ON, then that device will turned ON.
4.4 Interfacing LCD to Raspberry Pi
• LCD is used to display the alphanumeric characters. LCD can be connected to GPIO pins
of Raspberry Pi and through program any characters can be displayed on LCD.
• Out of 40 pins of Raspberry Pi, 17 GPIO pins can be used to interface LCD.
• There are +5 V (Pin 2 and 4) and +3.3 V (pin 1 and 17) power output pins are available on
Raspberry Pi board.
• LCD requires +5 V, so provide +5 V to 16 × 2 LCD through +5 V power rail.
• Fig. 4.7 shows the interfacing of LCD to Raspberry Pi.
3.3 V 1 2 5V
GPIO 2 3 4 5V
GPIO 3 5 6 Ground
R +5V
GPIO 4 7 a 8 GPIO 14 R1
Ground 9 s 10 GPIO 15
p 1k 1
GPIO 17 11 b 12 GPIO 18 VSS
2
e VDD
GPIO 27 13 14 Ground 3 VEE
r
GPIO 22 r GPIO 23 4 RS
15 16
y 5
RW
3.3 V 17 18 GPIO 24 6
E
GPIO 10 19 P 20 Ground 7 D0
i 8
GPIO 9 21 22 GPIO 25 D1
9 D2
P 10
GPIO 11 23 24 GPIO 8 D3
i 11
n GPIO 7 D4
Ground 25 26 12 D5
GPIO 1 13 D6
GPIO 0 27 H 28
14
e D7
GPIO 5 29 30 Ground
a
GPIO 6 31 d 32 GPIO 12 16*2 LCD
e
+5V GPIO 13 33 34 Ground
r
GPIO 19 35 36 GPIO 16
GPIO 26 37 38 GPIO 20
Ground 39 40 GPIO 21
C1
1000 u
• As shown in above Fig. 4.7, LCD is interfaced to 10 GPIO pins of Raspberry Pi.
• GPIO pin 21, 20, 16, 12, 25, 24, 23 and 18 are used as ‘BYTE’ and created ‘PORT’ function
to send the data to LCD. GPIO 21 is LSB and GPIO 18 is MSB.
• 16 × 2 LCD module has 16 pins as tabulated in below Table 4.2.
Table 4.2: Pin Configuration of LCD
Category Pin Pin Name Function
No.
Power 1 VSS Ground pin, connected to Ground.
Pins
2 VDD or VCC Voltage pin +5 V.
Contrast 3 V0 or VEE Contrast setting, connected to VCC thorough a variable
Pin resistor.
IO.setup(12,IO.OUT)
IO.setup(25,IO.OUT)
IO.setup(24,IO.OUT)
IO.setup(23,IO.OUT)
IO.setup(18,IO.OUT)
def send_a_command (command): # execute the loop when “sead_a_command” is called
pin=command
PORT(pin); # calling 'PORT' to assign value to data port
IO.output(6,0) # putting 0 in RS to tell LCD we are sending command
IO.output(22,1) # telling LCD to receive command/data at the port by pulling EN
pin high
time.sleep(0.05)
IO.output(22,0) # pulling down EN pin to tell LCD we have sent the data
pin=0
PORT(pin); # pulling down the port to stop transmitting
def send_a_character (character): # execute the loop when “send_a_character” is called
pin=character
PORT(pin);
IO.output(6,1)
IO.output(22,1)
time.sleep(0.05)
IO.output(22,0)
pin=0
PORT(pin);
else:
IO.output(25,0)
if(pin&0×20 == 0×20):
IO.output(24,1)
else:
IO.output(24,0)
if(pin&0×40 == 0×40):
IO.output(23,1)
else:
IO.output(23,0)
if(pin&0×80 == 0×80):
IO.output(18,1) # if bit7 of 8bit 'pin' is true pull PIN18 high
else:
IO.output(18,0) #if bit7 of 8bit 'pin' is false pull PIN18 low
while 1:
send_a_command(0×01); # sending 'all clear' command
send_a_command(0×38); # 16*2 line LCD
send_a_command(0×0E); # screen and cursor ON
send_a_character(0×48); # ASCII code for 'H'
send_a_character(0×45); # ASCII code for 'E'
send_a_character(0×4C); # ASCII code for 'L'
send_a_character(0×4C); # ASCII code for 'L'
send_a_character(0×4F); # ASCII code for 'O'
time.sleep(1)
After running the program, ‘HELLO’ message will be displayed on LCD.
4.5 Setting Bluetooth, WI-FI and Ethernet on Raspberry Pi
• Most of the Raspberry Pi models have on board connectivity options for Wi-Fi and
Bluetooth.
• The Raspberry Pi 3, 3B+, Raspberry Pi Zero w and Raspberry Pi 4 have built-in Wi-Fi and
Bluetooth facility.
• The Raspberry Pi 3 is the first version of the computer to have in-built wireless and
Bluetooth features. Subsequently, all latest models of Raspberry Pi have these features.
• The Raspberry Pi can be easily connected to a Smartphone, TV or any other device
through Wi-Fi or Bluetooth.
4.5.1 Setting Wi-Fi on Raspberry Pi
• The Raspberry Pi can be connected to wireless network using desktop tool. For this, a
keyboard, mouse and monitor/display have to be connected to Raspberry Pi.
• Before setting Wi-Fi on Raspberry Pi, Ethernet connection has to be disconnected.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 4-13 Interfacing of Devices Using Python Programming
• To connect the router, right-click on wireless networking icon on the right corner of the
panel. Select the option ‘Turn on Wi-Fi’, then select the desired network from the menu.
• Input the ‘Pre shared Key’ when asked and then wait for the connection to be established.
• Wireless network can be set up on the command line. This option is used if Raspberry is
accessing using SSH which used for Ethernet.
• To set wireless connection, there are two options; it can be set up through GUI or can be
set up on the command line. Below commands will upgrade the Raspberry Pi.
sudo apt update
sudo apt upgrade
If SSID name is already defined then use it or if it is not defined, use below command;
sudo iwlist wlan0 scan
This will reveal the SSID in the line "ESSID". Next, open wpa_supplicant.conf:
sudo nano /etc/wpa_supplicant/wpa_supplicant.conf
Following code has to be added:
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=India
network={
ssid="SSID"
psk="PASSWORD"
key_mgmt=WPA-PSK
}
Add the SSID and password in the network.
The command Ctrl + X is used to exit and save, Y and Enter used to confirm it. Wireless
connectivity should be established immediately. If it is not established, use below command to
restart wireless:
sudo ifdown wlan0
sudo ifup wlan0
Then enter below command:
sudo reboot
• After rebooting, wireless connection will get established.
• Before booting, Wi-Fi can be set up on Raspberry Pi 3. This is another option to set up
Wi-Fi on Raspberry Pi which is described below:
o Insert the microSD card in Pc’s card reader and enter command- /boot/directory.
o Create a text file wpa_supplicant.conf, then open it and add the details.
o Save it, close the file and eject the microSD card.
• Above steps works only with pre-Raspbian Buster OS and various other operating system.
Raspbian Buster has a Wi-Fi driver which prevents the use of wpa_supplicant.conf file.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 4-14 Interfacing of Devices Using Python Programming
• Wi-Fi can be set up using Graphical Interface or GUI. This process is more effective than
setting Wi-Fi using command line interface which is described in above section.
• Before starting the Wi-Fi setting, make sure that latest version of Raspberry Pi OS is
installed. Follow the below steps:
o On desktop, locate network icon in the right-hand side and click on the icon to see
the list of available Wi-Fi networks.
o Select available Wi-Fi SSID in the drop-down list.
o Enter Wi-Fi password into the text box.
o Click on ‘Ok’. Wi-Fi will get connected to Raspberry Pi.
o Signal strength will be displayed in the upper task bar on the right side.
o Test connection by opening the web browser.
• Thus, Wi-Fi can be connected to Raspberry Pi.
4.5.2 Setting Bluetooth on Raspberry Pi
• Similar to Wi-Fi, Bluetooth is built-in into Raspbian Buster. For older models of Raspberry
Pi, run update and upgrade then use below command:
sudo apt install bluetooth-pi
• Before establishing communication between Raspberry Pi and a Bluetooth enabled
device, both the devices should be paired. Pairing a Bluetooth device on Raspberry is
similar to pairing Bluetooth on Smartphone or Laptop.
• Bluetooth can be activated from the command line as:
bluetoothctl
• Many options are available with this. Type "help" to see them.
• Bluetooth needs to be enabled, discoverable and made capable of discovering devices. It
can be done using below command:
power on
agent on
scan on
• With these commands, Raspberry Pi will detect the device, then add the device. The
connection can be made by entering connect followed by the MAC address. If password is
required on the remote device then enter it when asked.
• Thus, Bluetooth connection will get established.
• For communicating Raspberry Pi and a device via Bluetooth, there are two ways as:
o Bluetooth GUI (Graphical User Interface).
o Command Line Interface.
• Before starting communication using Bluetooth, following packages have to be installed:
Blueman: Blueman is a full featured Bluetooth manager. It provides GUI based setting
panel Bluetooth manager.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 4-15 Interfacing of Devices Using Python Programming
Bluez: Bluez provides the Bluetooth protocol stack and the bluetoothctl utility.
Bluetooth: This package provides all the plugins supported by BluezBluetooth stack.
• Above packages can be installed using following command,
sudo apt-get install bluemanbluez Bluetooth
• Reboot Raspberry Pi after successful installation of above packages.
4.5.3 Setting Ethernet on Raspberry Pi
• A direct Ethernet connection is always much faster than a Wi-Fi connection to access
Internet.
• Raspberry Pi can be directly connected to Ethernet on laptop or desktop with an Ethernet
cable bypassing the local network so that bandwidth is not shared with other computers.
• Ethernet can be set up on Raspberry Pi by following steps:
o Connect Raspberry Pi using PC Ethernet Port using an Ethernet cable.
o Open Windows, click on menu and select icon for settings.
o Click on ‘Network & Internet’. If Ethernet is already plugged, ‘Ethernet’ tab is seen on
the left side. Click on tab, ‘Network and Sharing Center’ can be seen on right side of
‘Related Settings’ section. Click on it.
o Wi-Fi sharing settings can be modified in Wi-Fi status window. On ‘Network and
Sharing Center’, a connection field for Wi-Fi, click the blue text. It will open ‘Wi-Fi
Status’ window where Wi-Fi status can be modified.
o In ‘Wi-Fi Status’ window, click on the ‘Properties’, it will open ‘Wi-Fi Properties’.
o In ‘Wi-Fi Properties’ window, click on ‘Sharing’ tab and check the box for ‘Allow other
network users to connect through this computer’s Internet connection’. In drop-down
menu, select Ethernet connection.
o Check Ethernet connection properties in the ‘Network and Sharing Center’ window.
o Check IPv4 settings in ‘Ethernet Properties’ window. Once ‘Use the following IP
address’ is selected, ‘IP address’, ‘Subnet Mask’ and ‘Default Gateway’ field are in
enabled position. Raspberry Pi can be pinged via its hostname such as:
ping raspberrypi.local.
o After this Ethernet is enabled on Raspberry Pi.
• The Ethernet port of Raspberry Pi can be also configured using Static IP address.
Procedure for setting Ethernet on Raspberry Pi is as follows:
o Review current network settings by typing ‘ifconfig’ command on command prompt
o Backup the current network configuration by using below command.
sudo cp /etc/dhcpcd.conf /etc/dhcdcp.backup
o To change the network setting, edit dhcpcd.conf file to set the static IP address.
o The following command is used to load the file into an editor
sudo nano /etc/dhcpcd.conf
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 4-16 Interfacing of Devices Using Python Programming
Place below lines at the top of the file to set Ethernet IP address:
interface eth0
static ip_address=10.11.44.124/24
static routers=10.11.44.1
static domain_name_servers=172.16.33.85
• Set the IP address , set the routers value to the gateway address. Once the file has been
updated, use ctrl to save and exit.
o Restart the Raspberry Pi by using following command:
sudo reboot
o Test the new network setup by using ‘ping’ command and check whether Ethernet
cable is connected properly, IP address, mask and gateway are correct.
• Once everything is done properly, Ethernet is enabled.
• There are two versions of camera module: standard version which is designed to take
pictures in normal light and NoIR version which can use infrared light source to take
pictures in the dark.
Steps to Connect and Install Camera on Raspberry Pi:
• Turn OFF the Raspberry Pi.
• Locate the camera module port on Raspberry Pi and connect camera to it using cable.
• Turn ON Raspberry Pi board.
• Go to main menu and open Raspberry Pi configuration tool, select Interface tab and
enable the camera interface.
• Reboot Raspberry Pi board.
• Now, camera is connected to Raspberry Pi. To capture an image in jpeg format, type
following command on terminal window:
raspistill-o image.jpg
‘image’ is the name of the captured picture which will be stored in Raspberry Pi.
• To capture 10 second video, type following command:
raspivid-o video.h264 -t 10000
Here, ‘video’ is the name of the captured video and "10000" is the number of
milliseconds.
• Python picamera library control the camera module. In IDE, following code will control the
camera functions:
from picamera import PiCamera
from time import sleep
camera = PiCamera()
camera.start_preview()
sleep(5)
camera.stop_preview()
• Camera preview can be seen if monitor is connected to Raspberry Pi. The preview can be
rotated by following commands :
camera = PiCamera()
camera.rotation = 180
Image can be rotated by 90, 180 or 270 degrees.
• To take capture still pictures use following code :
camera.start_preview()
sleep(5)
camera.capture('/home/pi/Desktop/image.jpg')
camera.stop_preview()
• As camera will take few seconds to sense the light levels, keep camera in sleep mode for
at least two seconds before capturing an image.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 4-18 Interfacing of Devices Using Python Programming
• GSM module can be interfaced to Raspberry Pi and can be used in image, video, audio
processing, automation, surveillance.
• GSM module can be interface to Raspberry Pi in two ways: through USB or through GPIO
interfacing.
• A micro USB cable can be used for connecting Raspberry Pi to GSM module which
provide power and establish a serial communication.
• Below Fig. 4.9 shows interfacing of Raspberry Pi and GSM module through micro USB
cable.
• Run below Python program for sending a message through Raspberry Pi and GSM
module.
• In the program, proper libraries are imported and serial communication is enabled.
Modem is controlled through AT command.
[I] Program for sending message using GSM module
# Code for sending message using GSM module
import RPi.GPIO as GPIO
import os, time
GPIO.setmode(GPIO.BOARD)
# Enable Serial Communication
port = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=1)
# Transmitting AT Commands to the Modem
# '\r\n' indicates the Enter key
port.write('AT'+'\r\n')
rcv = port.read(10)
print rcv
time.sleep(.1)
port.write('ATE0'+'\r\n') # Disable the Echo
rcv = port.read(10)
print rcv
time.sleep(.1)
port.write('AT+CMGF=1'+'\r\n') # Select Message format as Text mode
rcv = port.read(10)
print rcv
time.sleep(.1)
port.write('AT+CNMI=2,1,0,0,0'+'\r\n') # New SMS Message Indications
rcv = port.read(10)
print rcv
time.sleep(.1)
# Sending a message to a particular Number
port.write('AT+CMGS="9422321170"'+'\r\n')
rcv = port.read(10)
print rcv
time.sleep(.1)
port.write('Hello'+'\r\n') # Message
rcv = port.read(10)
print rcv
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 4-21 Interfacing of Devices Using Python Programming
time.sleep(1)
ck=1
while ck==1:
rcv = port.read(10)
print rcv
fd=rcv
if len(rcv)>3: # check if any data received
ck=12
for i in range(5):
rcv = port.read(10)
print rcv
fd=fd+rcv # Extract the complete data
# Extract the message number shown in between the characters "," and '\r'
p=list(locate(fd, ","))
q=list(locate(fd, '\r'))
MsgNo=fd[p[0]+1:q[1]]
# Read the message corresponds to the message number
rd=port.write('AT+CMGR='+MsgNo+'\r\n')
msg=''
for j in range(10):
rcv = port.read(20)
msg=msg+rcv
print msg
time.sleep(0.1)
After executing the above program, the message will be received and retrieved on the mobile
number specified in the program code.
4.8 Interfacing Ultrasonic Sensor to Raspberry Pi
• Ultrasonic sensors are used to measure the distance between two objects using ultrasonic
waves. Ultrasonic waves are used as they are more accurate and not audible to human
ear.
• HC-SR04 ultrasonic sensor as shown in below Fig. 4.10 is widely used for distance
measurement up to 400 cm. It consists of transmitter, receiver and control circuit. As
shown in Fig. 4.10, it has Vcc, Trig, Echo and GND.
• The ultrasonic transmitter transmits waves (of 40 kHz) get reflected by the target which
are received by the receiver.
• The Echo pin will change the state and it becomes high. It remains in high state until it hit
the target object and returns to receiver.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 4-23 Interfacing of Devices Using Python Programming
• Based on the time for which Echo pin stays high, distance can be calculated using the
formula: Speed = Distance/Time.
Ultrasound Ultrasound
transmitter receiver
VCC Trig Echo GND
• The Raspberry Pi read the Echo pin to calculate the time, so this pin is connected to GPIO
and configured as an input pin. The output is available on Trig pin, so it is configured as
output pin.
• The range of ultrasonic sensor is from 2 cm to 400 cm. So in the program it is checked
whether the object is within the range or not.
The python program for interfacing ultrasonic sensor is given below:
import RPi.GPIO as GPIO #Import GPIO library
import time #Import time library
GPIO.setmode(GPIO.BCM) #Set GPIO pin numbering
TRIG = 21 #connect pin 21 to TRIG
ECHO = 23 #connect pin 23 to ECHO
print "Distance measurement starts"
GPIO.setup(TRIG,GPIO.OUT) #configure Trig as GPIO out
GPIO.setup(ECHO,GPIO.IN) #configure Echo as GPIO in
while True:
GPIO.output(TRIG, False) #Set TRIG as LOW
print "Waitng For Sensor To Settle"
time.sleep(2) #Delay of 2 seconds
GPIO.output(TRIG, True) #Set TRIG as HIGH
time.sleep(0.00001) #Delay of 0.00001 seconds
GPIO.output(TRIG, False) #Set TRIG as LOW
while GPIO.input(ECHO)==0: #Check whether the ECHO is LOW
pulse_start = time.time() #Saves the last known time of LOW pulse
while GPIO.input(ECHO)==1: #Check whether the ECHO is HIGH
pulse_end = time.time() #Saves the last known time of HIGH pulse
pulse_duration = pulse_end - pulse_start #Get pulse duration to a variable
distance = pulse_duration * 17150 #Multiply pulse duration by 17150 to get distance
distance = round(distance, 2) #Round to two decimal points
if distance > 2 and distance < 400: #Check whether the distance is within range
print "Distance:",distance - 0.5,"cm" #Print distance with 0.5 cm calibration
else:
print "Object is Out Of Range" #display object is out of range
time.sleep(0.00001)
After running the program, corresponding message will get displayed.
3v3 Power 1 2 5V
GPIO 2 3 4 5V
GPIO 3 5 6 Ground
GPIO 4 7 8 GPIO 14
Ground 9 10 GPIO 15
R
GPIO 17 11 12 GPIO 18
a
GPIO 27 13 s 14 Ground
p
GPIO 22 15 b 16 GPIO 23
e 18 GPIO 24
3.3 V 17 r
GPIO 10 19 r 20 Ground
y
GPIO 9 21 22 GPIO 25
GPIO 11 23 P 24 GPIO 8
i
Ground 25 26 GPIO 7
H 28 GPIO 1
GPIO 0 27 e
GPIO 5 29 a 30 Ground
d
GPIO 6 31 32 GPIO 12
e 330
r 34 Ground LED
GPIO 13 33
GPIO 19 35 36 GPIO 16
GPIO 26 37 38 GPIO 20
Ground 39 40 GPIO 21
• To interface fingerprint reader to Raspberry Pi, USB to TTL converter is required which can
support various baud rates for serial communication. CP2102 USB to TTL converter is
widely used in between fingerprint reader and Raspberry Pi.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 4-27 Interfacing of Devices Using Python Programming
Fig. 4.15
• To write a python program, first fingerprint package has to be imported from python
library. Then the sensor is initialised with appropriate baud rate and checked for its
password. The fingerprints are stored in memory.
• At the beginning of the program, packages required to read fingerprint has to be
downloaded.
The steps for interfacing the fingerprint reader are given below:
(i) Install required library and packages by typing following commands:
sudo bash
wget –O – http://apt.pm-codeworks.de/pm-codeworks.de.gpg | apt-key add –
wget http://apt.pm-codeworks.de/pm-codeworks.list -P /etc/apt/sources.list.d/
(ii) Update library and download fingerprint sensor library by typing following commands:
sudo apt-get update
sudo apt-get install python-fingerprint –yes
(iii) Check USB port where fingerprint sensor is connected by using below command:
ls /dev/ttyUSB*
(iv) Allot memory space to store fingerprint image in digital form.
(v) Below code will initialize fingerprint sensor and allot memory space:
import time
from pyfingerprint.pyfingerprint import PyFingerprint
# Detect new finger
# Initialize the sensor
init:
f = PyFingerprint('/dev/ttyUSB0', 9600, 0xFFFFFFFF, 0x00000000)
if ( f.verifyPassword() == False ):
raise ValueError('The fingerprint sensor password is wrong!')
except Exception as e:
print('The fingerprint sensor could not be initialized!')
print('Exception message: ' + str(e))
exit(1)
# Gets some sensor information
print('Currently used templates: ' + str(f.getTemplateCount()) +'/'+
str(f.getStorageCapacity()))
After executing above steps, the fingerprint is detected and stored in char buffer 1.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 4-28 Interfacing of Devices Using Python Programming
(vi) if-else loop can be used to check whether fingerprint is matching with the particular image
which is already stored.
## Enroll new finger
try:
print('Waiting for fingerprint...')
f.convertImage(0x01)
# Convert image into digital form and stores it in char buffer 1
result = f.searchTemplate() # Checks if fingerprint is already enrolled
positionNumber = result[0]
if ( positionNumber >= 0 ):
print('Template already exists at position #' + str(positionNumber))
exit(0)
print('Remove finger...')
time.sleep(2)
print('Wait for same finger again...')
while ( f.readImage() == False ):
pass
(vii) The fingerprint is detected and stored in char buffer 2. This process is repeated and if a new
fingerprint is detected it is stored in another variable called PositionNumber.
(viii) Python program code is given below:
import time
from pyfingerprint.pyfingerprint import PyFingerprint
# initialize the sensor
init:
f = PyFingerprint('/dev/ttyUSB0', 9600, 0xFFFFFFFF, 0x00000000)
if ( f.verifyPassword() == False ):
raise ValueError('The fingerprint password is wrong!')
except Exception as e:
print('The fingerprint sensor could not be initialized!')
print('Exception message: ' + str(e))
exit(1)
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 4-29 Interfacing of Devices Using Python Programming
except Exception as e:
print('The fingerprint sensor could not be initialized!')
print('Exception message: ' + str(e))
exit(1)
print('Currently used templates:
' + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))
delet:
#delete the template of the fingerprint
positionNumber = input('Please enter the template position you want to delete: ')
positionNumber = int(positionNumber)
if ( f.deleteTemplate(positionNumber) == True ):
print('Template deleted!')
except Exception as e:
print('Operation failed!')
print('Exception message: ' + str(e))
exit(1)
(x) Below code is used to search fingerprint from the stored data.
import hashlib
from pyfingerprint.pyfingerprint import PyFingerprint
# initialize the sensor
init:
f = PyFingerprint('/dev/ttyUSB0', 9600, 0xFFFFFFFF, 0x00000000)
if ( f.verifyPassword() == False ):
raise ValueError('The fingerprint password is wrong!')
except Exception as e:
print('The fingerprint sensor could not be initialized!')
print('Exception message: ' + str(e))
exit(1)
print('Currently used templates:
' + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))
search:
print('Waiting for finger...') # search the finger and calculate hash
while ( f.readImage() == False ): #read fingerprint image
pass
f.convertImage(0x01) #Convert image into digital form and stores it in charbuffer 1
result = f.searchTemplate()
positionNumber = result[0]
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 4-31 Interfacing of Devices Using Python Programming
accuracyScore = result[1]
if ( positionNumber == -1 ):
print('No match found!')
exit(0)
else:
print('Found template at position #' + str(positionNumber))
print('The accuracy score is: ' + str(accuracyScore))
exit(1)
Think Over It
Points to Remember
• Python interpreter can be run in two ways: as an interactive shell to execute individual
commands or as a command-line program to execute standalone programs or scripts.
• The integrated development environment (IDE) bundled with Python and the Raspberry
Pi is called as IDEL.
• To write a Python program for Raspberry, first Operating System has to be installed and
then Raspberry has to be configured. Booting Raspberry Pi for the first time include
following steps:
o Push the microSD card into the socket on the bottom of the board.
o Plug in a USB keyboard and mouse.
o Plug the HDMI output into TV or monitor. Make sure that monitor is ON and set to
the correct input.
o Plug in power supply and switch ON the board.
• In Raspbian, Python and GPIO library are preinstalled.
• Pin number 3, 5, 7, 8, 10, 11, 12, 13, 15, 16, 18, 19, 21, 22, 23, 24, 26 are the GPIO pins of
Raspberry Pi.
• Most of the Raspberry Pi models have on board connectivity options for Wi-Fi and
Bluetooth.
• The Raspberry Pi 3, 3B+, Raspberry Pi Zero w and Raspberry Pi 4 have built-in Wi-Fi and
Bluetooth facility.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 4-32 Interfacing of Devices Using Python Programming
• The Raspberry Pi 3 is the first version of the computer to have in-built wireless and
Bluetooth features. Subsequently, all latest models of Raspberry Pi have these features.
• Blueman: Blueman is a full featured Bluetooth manager. It provides GUI based setting
panel Bluetooth manager.
• Bluez: Bluez provides the Bluetooth protocol stack and the bluetoothctl utility.
• A direct Ethernet connection is always much faster than a Wi-Fi connection to access
Internet.
• Raspberry Pi can be directly connected to Ethernet on laptop or desktop with an Ethernet
cable bypassing the local network so that bandwidth is not shared with other computers.
• The camera module is provided with Raspberry Pi which can be used to take pictures and
videos.
• Raspberry Pi camera v1.3 have features as: resolution 5 MP, HD Video recording, it can
capture wide, still images of resolution 2592 × 1944 pixels and it can be connected
through CSI interface.
• Raspberry Pi board has CSI (Camera Serial Interface) port through which camera can be
directly connected to Raspberry Pi using 15-pin ribbon cable.
• Camera module should be handled very carefully as camera can be damaged by static
electric charge.
• Ultrasonic sensors are used to measure the distance between two objects using ultrasonic
waves. Ultrasonic waves are used as they are more accurate and not audible to human
ear.
• HC-SR04 ultrasonic sensor is widely used for distance measurement up to 400 cm. It
consists of transmitter, receiver and control circuit. As shown in Fig. 4.10, it has VCC, Trig,
Echo and GND.
• Passive Infrared (PIR) sensor detects any movement of human or animals which emits
infrared.
• PIR sensor detects change in the infrared radiation.
• Fingerprint technology is most popular technology to verify the identity of an individual.
• The characteristics such as ridges or minutia patterns of a Fingerprint found within print
area are used for matching purpose.
Exercises
[A] True or False :
1. The GPIO pin number and physical pin number of Raspberry Pi are different.
2. Python is not an interpreted language.
3. The integrated development environment (IDE) bundled with Python and the Raspberry
Pi is called as IDEL.
4. If Raspbian Lite is installed then keyboard, mouse and monitor are not required.
5. In Raspbian, Python and GPIO library are not preinstalled.
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 4-33 Interfacing of Devices Using Python Programming
6. A direct Ethernet connection is always much faster than a Wi-Fi connection to access
Internet.
7. The Raspberry Pi 3 is the first version of the computer to have in-built wireless and
Bluetooth features.
[B] Multiple Choice Questions :
1. Which operating system does Python supports?
(a) Windows (b) Linux
(c) Both (a) and (b) (d) None of these
2. Following models of Raspberry Pi have Bluetooth facility.
(a) Raspberry Pi 3 (b) Raspberry Pi Zero
(c) Raspberry Pi 4 (d) All of these
3. PIR sensor detects change in the …… radiation.
(a) Infrared (b) Micro
(c) Ultraviolet (d) None of these
4. Ultrasonic sensor widely used to measure ……
(a) Time (b) Distance
(c) Frequency (d) None of these
5. Which library/libraries have to be imported to interface fingerprint reader to Raspberry
Pi?
(a) PyFingerprint (b) Numpy
(c) Both (a) and (b) (d) None of these
[C] Fill in the Blanks:
1. Python is an ______ language.
2. The integrated development environment (IDE) bundled with Python and the Raspberry
Pi is called as ____ .
3. The Raspberry Pi 3 is the first version of the computer to have in-built ____ and ______
features.
4. Ultrasonic sensors are used to measure the distance between two objects using ____
waves.
5. PIR sensor detects change in the _____ radiation.
6. In Raspbian, ______ and ______ library are preinstalled.
[D] Short Answer Questions:
1. What is IDEL?
2. List two popular modules used in Raspberry Pi.
3. What is the difference between Raspbian and Raspbian Lite?
4. How many pins are as GPIO in Raspberry Pi?
5. What is Bluetooth technology?
6. What is the difference between Bluetooth and Wi-Fi?
7. What is the use of GSM module?
S.Y.B.Sc. (Comp. Sci.) : Elect. - S-IV - P-I 4-34 Interfacing of Devices Using Python Programming
Answers
[A] True or False :
(1) True (2) False (3) True
(4) True (5) False (6) True
(7) True
[B] Multiple Choice Questions :
1. (a) 2. (d) 3. (a) 4. (b) 5. (a)
[C] Fill in the Blanks :
(1) interpreted (2) IDEL (3) wireless and bluetooth
(4) ultrasonic (5) infrared (6) Python and GPIO
✍✍✍
Model Question Paper - I
Time : 2 Hours Maximum Marks : 35
Note :
1. Q.1 is compulsory.
2. Solve any three questions from Q.2 to Q.5.
3. Q.2 to Q.5. carry equal marks.
Q.1. Answer the flowing questions in one or two sentences. (Any 5) (5 marks)
1. What is SBC?
2. Write any one advantage and disadvantage of SoC.
3. What is Raspbian? List features of Raspbian.
4. State any two types of SBC.
5. List two popular modules used in Raspberry Pi.
6. What is the use of GSM module?
7. List at 4 features of Python.
Q.2. Answer the following : (10 marks)
[A] 1. Draw and explain the block diagram of single board computer. (3)
2. What is Python? List features of Python. (3)
[B] Draw the diagram of interfacing the LED to Raspberry Pi and write python program to blink
the LED. (4)
Q.3. Answer the following : (10 marks)
[A] 1. Compare any three types of SBC. (3)
2. Explain membrane keyboard. (3)
[B] Draw and explain the architecture of SoC with the help of neat diagram. (4)
Q.4. Answer the following : (10 marks)
[A] 1. Write a short note of comparison of Raspberry Pi modules. (3)
2. Write a short note on Python variables. (3)
[B] Explain how camera is interfaced to Raspberry Pi? Write python program to capture images
using the camera. (4)
Q.5. Write a short note on the following : (Any 4) (10 marks)
1. Break and Pass statements used in Python.
2. Four features of ARM1176JZ-S.
3. Prefetch unit.
4. Data types used in Python.
5. Pipelining used in Raspberry Pi.
6. Types of keyboard.
✍✍✍
(M.1)
Model Question Paper - II
Time : 2 Hours Maximum Marks : 35
Note :
1. Q.1 is compulsory.
2. Solve any three questions from Q.2 to Q.5.
3. Q.2 to Q.5. carry equal marks.
Q.1. Answer the flowing questions in one or two sentences. (Any 5) (5 marks)
1. What is SoC?
2. Write any one advantage and disadvantage of SBC.
3. What is Python? List features of Python.
4. State any types of keyboard.
5. Write two softwares used for Raspberry Pi.
6. What is the use of ultrasonic sensor?
7. List at 4 features of Raspberry Pi.
Q.2. Answer the following : (10 marks)
[A] 1. Draw and explain the block diagram of SoC. (4)
2. Give at least 4 examples of data type conversion functions. (2)
[B] Explain with help of neat diagram the interfacing of fingerprint reader to Raspberry Pi. Write a
python program to read and store the fingerprint. (4)
Q.3. Answer the following : (10 marks)
[A] 1. What are the advantages and disadvantages of SBC? (3)
2. Explain the procedure of setting Wi-Fi on Raspberry Pi. (3)
[B] Draw the diagram of interfacing the GSM module to Raspberry Pi. Write a python program to
send SMS on given mobile number. (4)
Q.4. Answer the following : (10 marks)
[A] 1. Explain if else, for and while loops used in Python. (3)
2. Explain CPU pipelining stages. (3)
[B] Explain how ultrasonic sensor is interfaced to Raspberry Pi. Write a python program to
measure the distance between two objects. (4)
Q.5. Write a short note on the following : (Any 4) (10 marks)
1. LCD display.
2. Branch prediction.
3. Continue and try statements used in Python.
4. Functions used in Python.
5. Procedure of installing the Ethernet on Raspberry Pi.
6. GPU of Raspberry Pi.
✍✍✍
(M.2)