Embedded System - Merged PDF
Embedded System - Merged PDF
Embedded Systems
Lecturer: Addisalem H.
Nov. 2022
Chapter |: Introduction to Embedded Systems
1-2
What are Embedded Systems?
❖ Computer based systems that do not appear to be computers – Complexity is
hidden from the user
❖ Complexity is embedded inside the device- the user doesn’t have to deal with the
complexity
❖ Much more common that laptops or desktops
❖ They interact with users via simple interfaces
▪ Digital camera, TV, Cellphone
❖ Embedded systems tend to be application specific
▪ Perform one task or set of related tasks
▪ Some devices blur the line(e.g. cellphones)
❖ Design is focused on one application— unlike general purpose systems(e.g.
laptops)
❖ High design efficiency is possible: Special purpose Vs. General purpose(e.g. Video games)
1-3
What are Embedded Systems?
❖ Hardware and software often designed together
▪ General purpose systems use hardware and software developed by different
companies
❖ Takes data from the outside world and output data to the outside world
1-4
Embedded Systems Definition
Precisely defining Embedded System is difficult. The following definitions may, in
combination, do the job.
✓ An embedded system is a special-purpose computer system designed to
perform one or a few dedicated functions, sometimes with real-time computing
constraints
✓ Specialized computer system hardware that is used in larger systems or
machines to control devices such as automobiles, home appliances, and office
equipment .
✓ Any electronic system that uses a CPU chip, but that is not a general-purpose,
workstation, desktop or laptop computer. Such systems generally use
microprocessors, or they may use custom-designed chips or both.
1-5
Embedded Systems Definition
✓ An embedded system is some combination of computer hardware and software,
either fixed in capability or programmable, that is specifically designed for a
particular kind of application device.
✓ IEEE defines Embedded Systems as: “the devices used to control, monitor or
assist the operation of equipment, machinery or plant’’. “Embedded” reflects
the fact that they are an integral part of the system.
1-6
Embedded Systems Characteristics
Common characteristics of Embedded Systems are the following:
✓ Frequently, embedded systems are connected to the physical environment
through sensors collecting information about that environment and actuators
controlling that environment.
✓ Embedded systems have to be dependable (trusted). Many ES are safety-critical.
Examples of safety critical systems are Nuclear power plants, airplanes, trains,
cars, satellites etc.
1-7
Embedded Systems Characteristics
The important characteristics of an embedded system are
▪ Speed (bytes/sec) : should be high speed
▪ Power (watts): low power dissipation
▪ Size and weight: as far as possible small in size and low weight
▪ Percentage error: must be very accurate
▪ Adaptability: high adaptability and
▪ Accessibility Reliability: must be reliable over a long period of time
1-8
Embedded Systems Characteristics
Dependability encompasses the following aspects of a system:
1. Reliability: Reliability is the probability that a system will not fail.
3. Availability: Availability is the probability that the system is available. Both the reliability
and the maintainability must be high in order to achieve a high availability.
4. Safety: This term describes the property that a failing system will not cause any harm.
5. Security: This term describes the property that confidential data remains confidential
and that authentic communication is guaranteed.
1-9
Embedded Systems Characteristics
✓ Embedded systems have to be efficient. The following metrics can be used for
evaluating the efficiency of embedded systems:
1. Energy: Many embedded systems are mobile systems obtaining their energy
through batteries. Available electrical energy must be used very efficiently.
2. Code-size: the code-size should be as small as possible for the intended
application.
3. Run-time efficiency: We should be able to meet time constraints using
the least amount of hardware resources and energy. In order to reduce the
energy consumption, clock frequencies and supply voltages should be as
small as possible.
1-10
Embedded Systems Characteristics
4. Weight: All portable systems must be of low weight. Low weight is
frequently an important argument for buying a certain system.
5. Cost: For high-volume embedded systems, especially in consumer
electronics, competitiveness on the market is an extremely crucial issue, and
efficient use of hardware components and the software development budget
are required.
1-11
Embedded Systems Characteristics
✓ These systems are dedicated towards a certain application. For example,
processors running control software in a car or a train will always run that
software, and there will be no attempt to run a computer game or spreadsheet
program on the same processor.
✓ There are mainly two reasons for this:
▪ Running additional programs would make those systems less dependable.
▪ Running additional programs is only feasible if resources such as memory are
unused. No unused resources should be present in an efficient system.
1-12
Embedded Systems Characteristics
✓ Most embedded systems use a dedicated user-interface consisting of push-
buttons, steering wheels, pedals etc. Because of this, the user hardly recognizes
that information processing is involved.
✓ Many embedded systems must meet real-time constraints. Not completing
computations within a given time-frame can result in a serious loss of the quality
provided by the system. A time-constraint is called hard if not meeting that
constraint could result in a catastrophe. All other time constraints are called
soft
1-13
Embedded Systems Characteristics
✓ Many embedded systems are hybrid systems in the sense that they include
analog and digital parts.
✓ Typically, embedded systems are reactive systems. A reactive system is one that
is in continual interaction with its environment and executes at a pace
determined by that environment.
1-14
Embedded Systems Examples
❖ Even though often nearly invisible, embedded systems are ubiquitous.
❖ Embedded systems are present in many industries, including industrial automation,
defense, transportation, and aerospace. For example, NASA’s Mars Path Finder,
Lockheed Martin’s missile guidance system, and the Ford automobile all contain
numerous embedded systems.
❖ Every day, people throughout the world use embedded systems without even
knowing it.
❖ Remarkably adaptable and versatile, embedded systems can be found at home, at
work, Indeed, it is difficult to find a segment of daily life that does not involve
embedded systems in some way.
1-15
Embedded Systems Examples
❖ Automotive electronics: Modern cars can be sold only if they contain a significant amount of
electronics. These include air bag control systems, engine control systems, anti-braking systems
(ABS), air-conditioning, GPS systems, safety features, and many more.
❖ Aircraft electronics: A significant amount of the total value of airplanes is due to the information
processing equipment, including flight control systems, anti-collision systems, pilot information
systems, and others. Dependability is of utmost importance.
❖ Trains: Again, safety features contribute significantly to the total value of trains, and dependability is
extremely important.
❖ Medical systems: There is a huge potential for improving the medical service by taking advantage of
information processing taking place within medical equipment.
❖ Military applications: Information processing has been used in military equipment for many years. In
fact, some of the very first computers analyzed military radar signals.
❖ Authentication systems: Embedded systems can be used for authentication purposes.
❖ Fabrication equipment: Fabrication equipment is a very traditional area in which embedded systems
have been employed for decades. Safety is very important for such systems, the energy consumption
is less a problem.
1-16
Embedded Systems Examples
1-17
Contrast Between Embedded Systems and Other Computer Systems
Designers can decide the number of memory Fixed number for memory or I/O makes a
or I/O ports needed. micro-controller ideal for a limited but specific task.
Programming microcontrollers
• Write code on a host machine– regular desktop or laptop
• Programming the microcontroller– transferring the program from host to microcontroller
• Programming hardware can be used to place program in microcontroller memory
1-19
Components of Embedded Systems
❖ Sensors: Receives information from the environment
▪ Provide simple information
• Thermistor: reports temperature
• Photoresistor: reports light intensity
▪ Complex sensors: more complicated data
• CMOS camera: Captures images
• Ethernet controller: enables network communication
❖ Actuators: Cause events to occur in the environment
▪ Simple actuators
• Light emitting diodes(LEDs)– Small lights
• LCD display– simple display
▪ Complex actuators
• Servo motor: moves something
• Ethernet controller: enables network communication
1-20
Categories of Embedded Systems
❖ Embedded systems are classified based on performance and functional
requirements, as well as the performance of microcontrollers. These
classifications can be further divided into categories and subcategories.
1-21
Categories of Embedded Systems
Real-time embedded systems
Real-time embedded systems must provide results or outputs promptly. Priority is assigned to
output generation speed, as real-time embedded systems are often used in mission-critical sectors,
such as defense and aerospace, that need important data,
Examples of real-time embedded systems include:
• Aircraft controls
• Land-vehicle and flight computers that process and transmit sensor-acquired data
• Missile defense system controls
• Autonomous and semi-autonomous vehicle controls
❖ Real-time embedded systems are further divided into soft real-time embedded systems and hard real-time
embedded systems to account for the importance of output generation speed.
▪ Soft real-time embedded systems have lenient output timeframes or deadlines. If outputs are not provided in a specified
timeframe, performance decline may ensue, but the consequences of this decline are relatively insignificant, do not
constitute a system or application failure, and are unlikely to result in a harmful outcome. The system's outputs are also
still considered valuable, despite their tardiness.
▪ Hard real-time embedded systems are the antithesis of soft real-time embedded systems. These systems must
consistently meet their assigned output deadlines, as not doing so is considered a system or application failure, which, in
many cases, could have catastrophic outcomes because of the hard real-time embedded system's typical deployment in
mission-critical programs and applications.
1-22
Categories of Embedded Systems
Standalone embedded systems
Standalone embedded systems don't require a host computer to function. They
can produce outputs independently.
1-23
Categories of Embedded Systems
Networked embedded systems
Network, or networked, embedded systems rely on wired or wireless networks and
communication with web servers for output generation.
1-24
Categories of Embedded Systems
When classifying embedded systems based on the performance of microcontrollers,
embedded systems are divided into three categories:
• Small-scale embedded systems
• Medium-scale embedded systems
• Sophisticated embedded systems
1-25
Debre Berhan University
Electrical and Computer Engineering Department
Embedded Systems
Lecturer: Addisalem H.
Nov. 2022
Chapter II: Embedded Microcontrollers
❖ Introduction
2-2
Introduction
❖ A microcontroller(µC or MCU ) is a compact integrated circuit
designed to govern a specific operation in an embedded system.
2-3
Introduction
Elements of Microcontroller
❖ The processor(CPU)-- A processor can be thought of as the brain of the device. It processes and
responds to various instructions that direct the microcontroller's function. This involves performing basic
arithmetic, logic and I/O operations. It also performs data transfer operations, which communicate commands
to other components in the larger embedded system.
❖ Memory-- A microcontroller's memory is used to store the data that the processor receives and uses to
respond to instructions that it's been programmed to carry out. A microcontroller has two main memory
types:
1. Program memory, which stores long-term information about the instructions that the CPU carries out. Program
memory is non-volatile memory, meaning it holds information over time without needing a power source.
2. Data memory, which is required for temporary data storage while the instructions are being executed. Data memory is
volatile, meaning the data it holds is temporary and is only maintained if the device is connected to a power source.
❖ I/O peripherals-- The input and output devices are the interface for the processor to the outside world.
The input ports receive information and send it to the processor in the form of binary data. The processor
receives that data and sends the necessary instructions to output devices that execute tasks external to the
microcontroller
2-4
Introduction
Elements of Microcontroller
❖ While the processor, memory and I/O peripherals are the defining elements of the microprocessor,
there are other elements that are frequently included. The term I/O peripherals itself simply refers
to supporting components that interface with the memory and processor. There are many
supporting components that can be classified as peripherals. Having some manifestation of an I/O
peripheral is elemental to a microprocessor, because they are the mechanism through which the
processor is applied.
Other supporting elements of a microcontroller include:
• Analog to Digital Converter (ADC)-- An ADC is a circuit that converts analog signals to digital signals. It allows
the processor at the center of the microcontroller to interface with external analog devices, such as sensors.
• Digital to Analog Converter (DAC)-- A DAC performs the inverse function of an ADC and allows the
processor at the center of the microcontroller to communicate its outgoing signals to external analog
components.
• System bus-- The system bus is the connective wire that links all components of the microcontroller together.
• Serial port-- The serial port is one example of an I/O port that allows the microcontroller to connect to
external components. It has a similar function to a USB or a parallel port but differs in the way it exchanges
bits.
2-5
Introduction
Microcontroller Features
❖ A microcontroller's processor will vary by application. Options range from the simple 4-
bit, 8-bit or 16-bit processors to more complex 32-bit or 64-bit processors.
❖ Microcontrollers can use volatile memory types such as random access memory (RAM)
and non-volatile memory types -- this includes flash memory, erasable programmable read-
only memory (EPROM) and electrically erasable programmable read-only memory
(EEPROM).
❖ Generally, microcontrollers are designed to be readily usable without additional computing
components because they are designed with sufficient onboard memory as well as offering
pins for general I/O operations, so they can directly interface with sensors and other
components.
❖ Microcontroller architecture can be based on the Harvard architecture or von Neumann
architecture, both offering different methods of exchanging data between the processor
and memory. With a Harvard architecture, the data bus and instruction are separate,
allowing for simultaneous transfers. With a Von Neumann architecture, one bus is used
for both data and instructions.
2-6
Introduction
Microcontroller Features
❖ When they first became available, microcontrollers solely used assembly language. Today, the C
programming language is a popular option. Other common microprocessor languages include
Python and JavaScript.
❖ MCUs feature input and output pins to implement peripheral functions. Such functions include
analog-to-digital converters, liquid crystal display (LCD) controllers, real-time clock (RTC), universal
synchronous/asynchronous receiver transmitter (USART), timers, universal asynchronous receiver
transmitter (UART) and universal serial bus (USB) connectivity. Sensors gathering data related to
humidity and temperature, among others, are also often attached to microcontrollers.
❖ Microcontroller processors can be based on complex instruction set computing (CISC) or reduced
instruction set computing (RISC). CISC generally has around 80 instructions while RISC has about
30, as well as more addressing modes, 12-24 compared to RISC's 3-5. While CISC can be easier to
implement and has more efficient memory use, it can have performance degradation due to the
higher number of clock cycles needed to execute instructions. RISC, which places more emphasis
on software, often provides better performance than CISC processors, which put more emphasis
on hardware, due to its simplified instruction set and, therefore, increased design simplicity, but
because of the emphasis it places on software, the software can be more complex. Which ISC is
used varies depending on application.
2-7
Introduction
Microcontroller Applications
❖ Microcontrollers are used in multiple industries and applications, including in the home and
enterprise, building automation, manufacturing, robotics, automotive, lighting, smart energy,
industrial automation, communications and internet of things (IoT) deployments.
❖ One very specific application of a microcontroller is its use as a digital signal processor. Frequently,
incoming analog signals come with a certain level of noise. Noise in this context means ambiguous
values that cannot be readily translated into standard digital values. A microcontroller can use its
ADC and DAC to convert the incoming noisy analog signal into an even outgoing digital signal.
❖ The simplest microcontrollers facilitate the operation of electromechanical systems found in
everyday convenience items, such as ovens, refrigerators, toasters, mobile devices, key fobs, video
game systems, televisions and lawn-watering systems. They are also common in office machines
such as photocopiers, scanners, fax machines and printers, as well as Smart meters, ATMs and
security systems.
❖ More sophisticated microcontrollers perform critical functions in aircraft, spacecraft, ocean-going
vessels, vehicles, medical and life-support systems as well as in robots. In medical scenarios,
microcontrollers can regulate the operations of an artificial heart, kidney or other organs. They can
also be instrumental in the functioning of prosthetic devices.
2-8
Introduction
Microcontrollers Vs. Microprocessors
❖ The distinction between microcontrollers and microprocessors has gotten less
clear as chip density and complexity has become relatively cheap to manufacture
and microcontrollers have thus integrated more "general computer" types of
functionality. On the whole, though, microcontrollers can be said to function
usefully on their own, with a direct connection to sensors and actuators, where
microprocessors are designed to maximize compute power on the chip, with
internal bus connections (rather than direct I/O) to supporting hardware such as
RAM and serial ports. Simply put, coffee makers use microcontrollers; desktop
computers use microprocessors.
❖ Microcontrollers are less expensive and use less power than microprocessors.
Microprocessors do not have built-in RAM, read-only memory (ROM) or other
peripherals on the chip, but rather attach to these with their pins. A
microprocessor can be considered the heart of a computer system, whereas a
microcontroller can be considered the heart of an embedded system.
2-9
Introduction
Choosing the Right Microcontroller
❖ There are a number of technology and business considerations to keep in mind
when choosing a microcontroller for a project.
❖ Beyond cost, it is important to consider the maximum speed, amount of RAM or
ROM, number or types of I/O pins on an MCU, as well as power consumption and
constraints and development support. Be sure to ask questions such as:
• What hardware peripherals are required?
• Are external communications needed?
• What architecture should be used?
• What sort of community and resources are available for the microcontroller?
• What is the market availability of the microcontroller?
2-10
Internal Components of a Computer
The internal components of a computer system consist of the hardware required to
store and process data, and communicate with external, peripheral devices.
❖ These components are connected by the system bus, which is made up of the
address bus, data bus, and control bus.
❖ Other types of memory are crucial for the operation of a computer system.
Secondary storage (e.g. SSD, HDD) provides permanent storage for programs and
data.
2-11
Internal Components of a Computer
The processor
❖ The processor, sometimes referred to as the CPU (central processing unit), is the
part of the computer that processes data by executing program instructions. At
processor level, there will be low-level instructions in the form of machine code
that the processor has been designed to handle, based on a specific processor
instruction set.
❖ For the processor to be able to execute a program, the program instructions need
to be transferred from secondary storage into main memory from where they can
be fetched, decoded, and executed. The data that needs to be processed is also
loaded into main memory (from secondary storage) or provided by the input and
output devices via the I/O controllers.
2-12
Internal Components of a Computer
Main Memory
❖ Main memory is memory that can be accessed directly by the processor. Each
memory location, where instructions or data are stored as binary sequences, has a
physical address, which is a number used to locate that memory location and
access its contents.
❖ Main memory is distinct from secondary storage, which the processor can't work
with directly. Secondary storage must be accessed through I/O controllers.
2-13
Internal Components of a Computer
Input/Output (I/O) Controllers
❖ All external (peripheral) devices are connected to the processor through I/O controllers.
These provide the mechanism for:
• input data to be received for processing from input devices, such as keyboards
• the results of computation to be output from the system to output devices, such as display screens
❖ Secondary storage devices are also connected to the processor through I/O controllers.
Secondary storage, in contrast to main memory, cannot be accessed directly by the processor.
It is not favorable for peripheral devices to be directly attached to the processor. Each device
operates in a different way, at different speeds, and using different electronic signals. An I/O
controller can be described as an interface between the core computer system and its
peripherals.
❖ I/O controllers provide a set of addressable registers that the processor (CPU) can access to
communicate with the I/O devices. For example, the characters entered using a keyboard
would be stored in an I/O controller that the processor (CPU) can access and process, such as
displaying the characters on a screen.
Read more!
2-14
Internal Components of a Computer
Buses
❖ The components of a computer system are connected together using buses. A bus is a
communication system that is used to transfer data between components.
• The system bus is a set of parallel connections that allow internal components to communicate with each other and
exchange data.
• There are also external buses that are used to connect the peripherals to the processor. These can be serial or parallel
connections.
❖ Buses can be implemented in different ways, depending on their intended use, for example wires,
electronic pathways, and tracks on printed circuits.
A model of the system bus
❖ In Von Neumann architecture, the system bus is made up of:
• an address bus
• a data bus, and
• a control bus
❖ The system bus is used to connect the processor (CPU), main memory, and the I/O controllers.
The following diagram illustrates an abstract model of the connections.
Read more!
2-15
Internal Components of a Computer
The system bus is used to connect the processor (CPU), main memory, and the I/O controllers. The following
diagram illustrates an abstract model of the connections.
2-16
Internal Components of a Computer
Data bus
❖ The data bus is used to transfer data and instructions. The data bus is bidirectional, i.e. it allows a
two-way connection between internal components of the system allowing values to be written to
or read from a location.
• Data is transferred to and from the processor
• Data is transferred to and from main memory
• Data is transferred to and from the I/O controllers
❖ Instructions are carried from main memory into the processor (to be decoded and executed)
❖ The width of the data bus refers to its number of parallel lines. This determines the number of bits
that can be transferred in one operation. For example, how many bits can be transferred in one go
between the memory and the processor. It is typically a multiple of a byte (e.g. 8, 16, 32, or 64 bits).
❖ If the width of the data bus is expressed as n bits, then n bits can be transferred at one time. The
amount of data that can be fetched at one time can affect the processor performance.
2-17
Internal Components of a Computer
Address bus
❖ The address bus is used to specify the address of a memory location to either read (i.e. load) data from or
write (i.e. store) data to that memory location.
❖ There is a one-way connection from the processor to the address bus and a one-way connection from the
address bus to the main memory and to the I/O controllers. This is because the address bus is a unidirectional
bus, which allows the processor to establish a connection with an addressable 'unit', whether it's a memory
location or an I/O controller.
❖ The width of the address bus refers to its number of parallel lines, which determines the number of bits that
can be used to form an address of a memory location. It is typically a multiple of a byte (e.g. 8, 16, 32, or 64
bits).
• If the width of the address bus is 8 bits, then there are 28 numbers that can be used to address memory locations
• If the width of the address bus is 16 bits, then there are 216 numbers that can be used to address memory locations
❖ In general, if the width of the address bus is expressed as n bits, then there are 2n numbers that can be used to
address memory locations.
❖ Therefore, the width of the address bus determines the maximum number of addressable memory locations,
i.e. the maximum memory capacity of a computer system. This is called the address space and it can affect
processor performance.
2-18
Internal Components of a Computer
Control bus
❖ The control bus is used to send control signals that manage and orchestrate the
operations that take place inside a computer system. This includes exchanging status
signals between the components of the computer system, and transmitting clock signals
required for the coordination of operations.
❖ For example, a control signal can be used to:
• Request communication between two units
• Acknowledge a communication request
• Specify the type of data that is being transferred via the other buses (i.e. data values, instructions, or
addresses)
• Synchronize the communication between the components using the clock pulses
❖ The control bus is bidirectional, i.e. there are two-way connections between the
components that the control bus connects.
❖ Examples of control signals include: Memory read, Memory write, Bus request, Bus grant,
Bus busy, Interrupt request, Clock signals:
2-19
Inside Microcontroller
2-20
Inside the Embedded System
CPU:
Memory:
Peripherals: are used to communicate with the outside world. The main types of peripherals that are
used include:
▪ Binary outputs: They can be used individually or grouped together to create parallel ports
where a group of bits can be input or output simultaneously.
▪ Serial outputs: These are interfaces that send or receive data using one or two pins in a serial
mode. They are less complex to connect but are more complicated to program.
▪ Analogue values: While processors operate in the digital domain, the natural world does not
and tends to orientate to analogue values.
▪ Displays: Displays are becoming important and can vary from simple. LEDs and seven segment
displays to small alpha-numeric LCD panels.
▪ Time derived outputs: Timers and counters are probably the most commonly used functions
within an embedded system.
2-21
Inside the Embedded System
Software: The software components within an embedded system often encompasses
the technology that adds value to the system and defines what it does and how well it
does it. The software can consist of several different components:
• Initialization and configuration
• Operating system or run-time environment
• The applications software itself
• Error handling
• Debug and maintenance support.
Algorithms: are the key constituents of the software that makes an embedded system
behave in the way that it does. They can range from mathematical processing through
to models of the external environment which are used to interpret information from
external sensors and thus generate control signals.
2-22
CPU Families used in Microcontrollers
Reduced Instruction Set Architecture (RISC) Vs. Complex Instruction Set Architecture (CISC)
Both approaches try to increase the CPU performance
RISC: The main idea behind this is to make hardware simpler by using an instruction set composed of a
few basic steps for loading, evaluating, and storing operations just like a load command will load data, a
store command will store the data.
Reduce the cycles per instruction at the cost of the number of instructions per program.
CISC: The main idea is that a single instruction will do all loading, evaluating, and storing operations just
like a multiplication command will do stuff like loading data, evaluating, and storing it, hence it’s
complex.
The CISC approach attempts to minimize the number of instructions per program but at the cost of an
increase in the number of cycles per instruction.
2-23
CPU Families used in Microcontrollers
Princeton(Von Neumann) and Harvard Architecture
Harvard Architecture:
Harvard Architecture is the digital computer architecture whose design is based on
the concept where there are separate storage and separate buses (signal path) for
instruction and data. It was basically developed to overcome the bottleneck of Von
Neumann Architecture.
2-24
CPU Families used in Microcontrollers
Read about the difference between Von Neumann and Harvard Architecture
Read about hardwired Vs. Micro-programmed architecture
2-25
AVR, ARM, 8051 and PIC Microcontrollers
AVR
❖ It is an electronic chip which is manufactured by Atmel. This microcontroller is the advanced
version of a microcontroller. It contains a chip CPU, ROM, RAM, input/output unit, interrupts
controller, etc. This microcontroller is used for high-speed signal processing operation which is
connected inside an embedded system.
2-26
AVR, ARM, 8051 and PIC Microcontrollers
ARM
❖ Advanced RISC Machine (ARM) this microcontroller was introduced by Acron Computer
Organization. It is manufactured by Apple, Qualcomm, Motorola, etc. The Processor of the ARM
microcontroller belongs to the family of CPUs which are based on Reduced Instruction Set
Computer (RISC) and also ARM Microprocessor. Mostly ARM microcontrollers are of 32-bit bus
width and also 64 bit is available. The speed of the ARM microcontroller is 1 clock cycle per
machine cycle and the power consumption is low.
❖ The popular microcontroller of ARM includes ARM Cortex-M0 to ARM Cortex-M7, etc. Flash,
EEPROM, SDRAM memory is used in ARM microcontroller. ARM consists of an Arithmetic logic
unit, booth multiplier, barrel shifter, control unit, register file.
2-27
AVR, ARM, 8051 and PIC Microcontrollers
8051
❖ 8051 microcontroller is an 8-bit microcontroller. 8051 microcontroller has the
ability to read, write and process 8-bit data. It is widely used in embedded systems,
consumer electronics, robotics, etc. The peripherals of this microcontroller are
integrated into a single chip, and the overall system cost is very low.
❖ The size of the product is small as compared to the microcontroller-based system
thus very handy. All features are available in 40 pin IC of the 8051
microcontrollers.
2-28
AVR, ARM, 8051 and PIC Microcontrollers
PIC
PIC stands for Programmable Interface Controllers. These are electronic circuits that can be
programmed to carry out a vast range of tasks. It consists of memory structure, input/output
ports, timers, A/D Converter, Oscillators, CCP module. PIC Microcontrollers are relatively
cheap. PIC devices are familiar with both industrial developers and hobbyists due to their low
cost, wide availability, large user base, extensive collection of application notes, serial
programming, free development tools, and reprogrammable flash memory capability.
Read about the differences between 8051, ARM, AVR, And PIC Microcontrollers
2-29
Debre Berhan University
Electrical and Computer Engineering Department
Embedded Systems
Lecturer: Addisalem H.
Dec. 2022
Outline
2-2
The Arduino Platform and C Programming
Arduino Environment
A development board
▪ 8-bit microcontroller
▪ Programming hardware
▪ USB programming interface
▪ I/O pins
▪ Has a microcontroller and USB interface to a PC
▪ Large open source community
2-3
The Arduino Platform and C Programming
Arduino Environment
A software environment
▪ Cross compiler
▪ Debugger
▪ Simulator
▪ Programmer
2-4
The Arduino Platform and C Programming
Arduino Environment
2-5
The Arduino Platform and C Programming
Arduino Board
• ATmega328 is the processor
programmed by the user
• ATmega16U2 handles USB
communication
2-6
The Arduino Platform and C Programming
Firmware
Two types of code executing on Bootloader
a simple microcontroller:
• Firmware on a microcontroller
1. Application code
• Allows the Flash and EEPROM to be
• Executes the system’s main functionality
programmed
• We write this code
• Manage USB communication, since
2. Firmware
application programming is via USB
• Low-level code: supports the main function
• USB interface, Power modes, reset, etc.
• Preprogrammed
In-Circuit Serial Programming (ICSP)
• A special programming method to program the firmware
• Needed because the bootloader can’t reprogram itself
2-7
The Arduino Platform and C Programming
Arduino UNO Schematic
• Arduino designs are open source
• Design is available
• You can build your own
2-8
The Arduino Platform and C Programming
Arduino Board and Microcontroller
Microcontroller ATmega328 Typical of an 8-bit processor
Operating Voltage 5V
• Low speed, low memory,
Input Voltage (recommended) 7-12V
Low cost
Input Voltage (limits) 6-20V
Digital I/O Pins 14 (of which 6 provide PWM output) • $1.50 for the MCU
Analog Input Pins 6 • $40 for the board
DC Current per I/O Pin 40mA
DC Current for 3.3V Pin 50mA
Flash Memory 32 KB (ATmega328)
Of which 0.5KB used by bootloader
SRAM 2 KB (ATmega328)
EEPROM 1 KB (ATmega328)
Clock Speed 16MHz
2-9
The Arduino Platform and C Programming
Arduino Integrated Development Environment (IDE)
2-10
The Arduino Platform and C Programming
Arduino Integrated Development Environment (IDE)
✓Verify: Compiles code, checks for errors Compiling Code
✓Upload: Compiles code, checks for errors, • Verify and Upload both compile
uploads to board • Message window will show either
✓New: Creates a new sketch completion message or error messages
✓Open: Opens an existing sketch • Error messages will show line numbers
✓Save: Saves your sketch to a file
✓Serial Monitor: Opens a window to Serial Monitor
communicate with the board • Display serial data sent from the Arduino
• Allows serial data to be sent to the
Arduino from the keyboard
• Library functions in the serial library
2-11
The Arduino Platform and C Programming
C Programming
Getting Started
2-12
The Arduino Platform and C Programming
C Programming
Variables Types and Type Qualifiers Variable names
• Names that represent values • Several built in types, different sizes • A sequence of visible
in the program characters
Type Size Notes
• Similar to algebraic variables • Must start with a non
char 1 byte Fixed size numerical character
• All variables have a type
which must be declared int Typically, word size 16 bits minimum int testvar1✓
int x; float Floating point 64 bits, typical int 1testvar✘
float y; double Double precision 64, 128 typical • No C language keywords
• Type determines how if, else, while✘
arithmetic is performed, how • Type qualifiers exist: short, long
much memory space is • Char is 8 bits on all platforms
required
2-13
The Arduino Platform and C Programming
C Programming Arithmetic/Relational operators
Basic C Operators ❑ +, -, *, /
❑ % is the modulo operator, division
Constants remainder
❑ Can use #define compiler directive Ex. 9%2 = 1, 9%3 = 0
#define ANSWER 42 ❑ ++ (increment), -- (decrement)
❑ Any instance of the string is substituted at compile time ❑ ==, <, >, <=, >=, !=
❑ Character constants Ex. If(x < 5)…
▪ Written as a single character in single quotes
Logical Operators
#define TERMINATOR ‘x’
❑ &&(AND), ||(OR), !(NOT)
▪ Integer equals to the ASCII value of the character
❑ Treat arguments as 1-bit binary values
▪ Some characters are not easy to represent (i.e bell)
0 is FALSE, not-0 is TRUE
Ex. If((A==1) && !B)
2-14
The Arduino Platform and C Programming
C Programming
Conditional Statements (if else) Example
if (expression) if (expr1)
statement1 stat1
else else if (expr2)
statement2 stat2
else
stat3
❑ else is optional
❑ expression is evaluated
▪ Execute statement1 if TRUE, statement2 if FALSE
❑ expr2 evaluated if expr1 is FALSE
2-15
The Arduino Platform and C Programming
C Programming
Conditional Statements (switch)
switch (expression) { switch (x) {
case const_expr1: stat1 case 0:
case const_expr2: stat2 y = 1;
default: stat3 case 1:
} y = 2;
break;
❑ expression is evaluated, compared to const_expr case 2:
❑ Statements are executed corresponding to the first matching expression Y = 3;
❑ default is optional }
❑ Without a break statement, the case will not end
❑ If x == 0 then both y = 1; and y = 2; are executed
2-16
The Arduino Platform and C Programming
C Programming Examples
Loops (for, while and do-while)
for (expr1; expr2; expr3)
statement
expr1; expr1;
while (expr2) { do {
statement statement
expr3; expr3;
} } while (expr2);
2-18
The Arduino Platform and C Programming
C Programming
Functions
❑ Functions can replace group of instructions
❑ Data can be passed to functions are arguments
❑ Functions can return a value to the caller
❑ The type of return value must be declared
2-19
The Arduino Platform and C Programming
C Programming
Global Variables
❑A variable is global if it’s defined outside of any function
❑A global variable must be declared as an extern in any function using it
• Extern not needed if global declaration is before the function
❑Variables can be global across files
int global_i;
void foo () {
extern int global_i;
2-20
The Arduino Platform and C Programming
Arduino Toolchain
Verify and Upload
2-21
The Arduino Platform and C Programming
Cross Compilation
Combine and Transform, Compile, Link, Hex File Creation and
Programming
❑ All program files are combined into one
❑ An #include is added to reference basic Arduino libraries
❑ Function prototypes are added
❑ A main() function created
❑ avr-gcc is invoked to cross compile the code
• Resulting code executes on AVR, not intel
❑ Generates an object file(.o)
❑ Object file is linked to Arduino library functions
❑ avr-objcopy is invoked to change the format of the executable file
❑ A .hex file is generated from the .elf file
2-22
The Arduino Platform and C Programming
Arduino Programs class X {
public:
▪ A program is called a sketch int m;
int mf(int v) {
▪ C/C++ program using Arduino library function int old = m;
▪ C++ is a super set of C m = v;
return old;
• All C programs are legal C++
}
▪ C++ also includes classes (OOP) };
X var;
var.m = 7;
Classes and Members int z = var.mf(9);
• Declaration of variable creates an object
Classes in Libraries
• .Operator used to access members Ethernet.begin(mac);
– Data and functions Serial.begin(speed);
• Functions can be declared inside the class client.print(“hello”);
Serial.print(“hello”);
2-23
The Arduino Platform and C Programming
Sketch Structure
setup() Function loop() Function
• A sketch doesn’t have a main() function • Every sketch has a loop()function
• Every sketch has a setup() function • Executes iteratively as long as the
• Executed once when Arduino is powered up
Arduino is powered up
• loop() starts executing after
• Used for initialization operations
setup() has finished
• Returns no value, takes no arguments
• loop() is the main program
control flow
void setup() {
• Returns no value, takes no argument
…
} void loop() {
…
}
2-24
The Arduino Platform and C Programming
Pins
❑ Pins are wires connected to the microcontroller Output Pins
❑ Pins are the interface of the microcontroller Output pins are controlled by the Arduino
❑ Pin voltages are controlled by a sketch
• Voltage is determined by your
❑ Pin voltages can be read by a sketch
sketch
Digital Vs. Analog • Other components can be
• Some pins are digital only controlled through outputs
• Read digital input, write digital output Input Pins
• 0 volts or 5 volts • Input pins are controlled by other
• Some pins can be analog inputs components
• Can read analog voltage on the pin • Arduino reads the voltage on the
pins
• Useful for analog sensors
• Allows it to respond to events and
• Analog only pins are clearly labeled
data
• No pins can generate an analog out put
2-25
The Arduino Platform and C Programming
Input/Output (I/O) Digital Input
int digitalRead(pin)
❑These functions allow accesses to the pins
• Returns the state of an input pin
void pinMode(pin, mode)
• Returns either LOW (0 volts) or HIGH (5 volts)
❑ Sets a pin to as act as either an input or an
Example:
output
int pinval;
❑ pin is the number of the pin pinval = digitalRead(3)
❑ 0 - 13 for the digital pins • pinval is set to the state of digital pin 3
❑ A0 - A5 for the analog pins Digital Output
❑ mode is the I/O mode the pin is set to void digitalWrite(pin, value)
❑ INPUT, OUTPUT, or • Assigns the state of an output pin
INPUT_PULLUP • Assigns either LOW(0 volts) or HIGH(5 volts)
❑ INPUT_PULLUP acts as input with Example:
reversed polarity digitalWrite(3, HIGH)
• Digital pin 3 is set HIGH (5 volts)
2-26
The Arduino Platform and C Programming
Analog Input Delay Example: Blink sketch
int analogRead(pin) void delay(msec) Void setup () {
pinMode(13, OUTPUT);
• Returns the state of an analog • Pause the program for msec }
input pin seconds
Void loop () {
• Returns an integer from 0 to 1023 • Useful for human interaction
digitalWrite(13, HIGH);
• 0 for 0 volts, 1023 for 5 volts Example: delay (1000);
Example: digitalWrite(3, HIGH); digitalWrite(13, LOW);
delay(1000); delay (1000);
int pinval;
}
pinval = analogRead(A3); digitalWrite(3, LOW);
• Pin must be an analog pin • Pin 3 is HIGH for 1 second
2-27
The Arduino Platform and C Programming
Debugging I/O access is insufficient
Debug and Trace • Observation of I/O is not enough to debug
Controllability
• Ability to control sources of data used by the If pin 2 is incorrect, how do you locate the bug?
system
Properties of a debugging environment
• Input pins, input interfaces (serial, ethernet, etc.)
1. Run control of the target
• Registers and internal memory • Start and stop program execution
• Observe data at stop points
Observability 2. Real time monitoring of target execution
• Non-intrusive in terms of performance
• Ability to observe intermediate and final results
3. Timing and functional accuracy
• Output pins, output interfaces • Debugged system should act like the real system
• Registers and internal memory
2-28
The Arduino Platform and C Programming
Debugging Environment
Remote debugger Remote Debug Tradeoffs
Advantages:
1. Good run control using break points
to stop execution
2. Debug monitor can alter memory
and register
3. Perfect functional accuracy
2-29
The Arduino Platform and C Programming
Debugging Environment
Embedded Debug Interfaces Debug and Trace Features
• Many modern processors include embedded • Break points, stopping points in the code
debug logic • Watchpoints, memory locations which trigger stop
• Typically an optional IP block • On-the-fly memory access
• Embedded trace microcell(ARM) • Examine/change internal processor values
• Background debug mode(Freescale) • Single-step through the code
• Debug logic permanently built into the • Export exceptions to the debugger (hit a watchpoint)
processor • Export software-generated data (printf)
• A few dedicated debug pins are added • Timestamp information for each event
• Instruction trace (special purpose HW needed)
2-30
The Arduino Platform and C Programming
Debug via Serial
Serial protocols UART Applications
▪ Data is transmitted serially • Used by modems to
• Only one bit needed (plus common ground) communicate with network
▪ Parallel data transmitted serially • Computers used to have an
▪ Original bytes/words regrouped by the receiver RS232 port, standard
▪ Many protocols are serial to reduce pin usage • Not well used anymore, outside
UART of embedded systems
▪ Universal Asynchronous Receiver/Transmitter • Replaced by USB, ethernet,
▪ Used for serial communication between devices I2C, SPI
▪ UART is Asynchronous; no shared clock • Simple, low HW overhead
▪ Asynchronous allows longer distance communication
• Built into most microcontrollers
• Clock skew is not a problem
2-31
The Arduino Platform and C Programming
UART Protocol
Simple UART structure Bit Duration
• Each bit is transmitted for a fixed duration
• The duration must be known to Tx and Rx
• Data is serialized by Tx, deserialized by Rx • Baud rate (f) determines the duration (T)
• Status indicates the state of the • Baud rate is the number of transitions per
transmit/receive buffers second
• Used for flow control • Typically measured in “bits per second
(bps)”
UART Timing Diagram
• T = 1/f
• f = 9600 baud, T = ~104microsec
• Transmission rate is less than baud rate
• First bit is the Start bit; initiates the transfer
• Need Start bit, Stop bit, Parity bit
• Next bits are the data
• Last are the stop bits
Read: UART Synchronization
2-32
The Arduino Platform and C Programming
UART Parity and Stop
Parity Bit Stop Bit
• Transmission medium assumed to be error- • Receiver expects a 1 after all data bits and
prone parity bits
• E-M radiation noise, synchronization • If 1 is not received, an error has occurred
accuracy
• Parity bit may be transmitted to check for Data Throughput Vs. Baud rate
errors • Every transmission involves sending signaling bits
• Even parity: Number of 1’s is even • stop, start, parity
• Odd parity: Number of 1’s is odd • Data throughput rate is lower than baud rate
• Parity bit is added to ensure even/odd parity • Signaling bits must be sent
• After data, before stop bit(s) • 8 data bits, 1 parity bit, baud rate = 9600
• Data = 011011010 • Sends 11 bits to send 8 data bits
• Parity bit = 1, total parity is odd • Transmission efficiency = 8/11 = 73%
• Data throughput rate = 9600*0.73 = 6981.8 bps
2-33
The Arduino Platform and C Programming
Serial on Arduino
Arduino Serial Communication Sending Text Over Serial
• UART protocol used over the USB cable • Use Serial.print() or
• Initialize by using Serial.begin() Serial.println() to print text in the serial
• Serial.begin(speed) or monitor
Serial.begin(speed, config) Serial.print(“hello”);
• speed is the baud rate
• config sets the data bits, parity, and stop bits
• Serial.begin(9600)
• Serial.begin(9600, SERIAL_8N1)
• 8 data, no parity, 1 stop
• Usually call Serial.begin() in the setup
function • String are converted to ASCII and sent using UART
• Serial monitor interprets bytes as ASCII
2-34
The Arduino Platform and C Programming
Serial on Arduino
Sending Data Over Serial Reading Data Over Serial
• Use Serial.write() • Data can be sent to the Arduino via the serial monitor:
Serial.write(42);
• When data is sent it goes into a buffer in the Arduino until it is
read
• Serial.available() is used to see how many bytes are
waiting in the buffer
Int bytenum = Serial.available();
• Serial.read() returns one byte from the serial buffer
Int bval = Serial.read();
• Serial monitor still interprets data as ASCII • Returns -1 if no data is available
• 42 the ASCII value for ‘*’ • Serial.readBytes() writes several bytes into a buffer
char buff[10];
Serial.readBytes(buff, 10);
2-35
Interfacing with the Arduino
Hardware and Software Ohm’s Law
• Embedded devices combine hardware and V = I*R
software
• What resistor do I need to limit
• Hardware interacts with the world current flow?
• Software is the “intelligence” • What voltage can I expect for a given
Electrical Circuits resistance?
• Electrical current flows through wires
Electrical Components
• Battery/power supply moves current
Electrical Properties • Resistors
• Voltage (V): Potential difference between two • Battery/DC Power
points in the circuit; measured in volts • Battery, Power, Ground
• Current (I): Rate of carrier flow; measured in • Diodes and LEDs
amperes • Switches/Pushbuttons
• Resistance (R): Any obstacle to current flow; • Potentiometers
measured in ohms
2-36
Interfacing with the Arduino
Wiring
Interpreting a Schematic Solderless Breadboard
• Show how components are connected in a
real circuit
• You need to be able to build a real circuit
from a schematic
• You need to be able to draw a schematic to
represent your design
Wiring Process
1. Select hardware components • Allows components to be easily connected
2. Select one of the terminals on the HW component in a non permanent way
Connect the terminal to a row of the breadboard
3.
• Great for prototyping
• If the terminal needs to be connected to another
terminal already in the breadboard, share the raw • Holes fit 24 AWG solid wire
Otherwise, use a free raw
•
• Connected in rows of 5 holes and columns
4. Go back to step 2 until all terminals are done
5. Go back to step 1 until all components are done
along the sides
2-37
Interfacing with the Arduino
Sensors Sensing the Environment
• Allow the microcontroller to receive • Microcontrollers sense voltage
information about the environment • digitalRead(pin) returns state of a
• How bright is it? digital pin
• How loud is it? • analogRead(pin) returns the analog
• How humid is it? voltage on a pin
• Is the button being pressed?
• Sensing logic must convert an environmental
• Perform operations based on the state of the effect into voltage
environment
• Turn on a light if it’s dark out
Reading a Pushbutton
• Voice controlled operation
2-38
Interfacing with the Arduino
Resistive Sensors Voltage-Controlling Sensors
• Some sensors control voltage directly
2-41
Interfacing with the Arduino
Making Sounds Piezo Element, Buzzer
• tone() can generate a square wave
with an arbitrary frequency
• analogWrite() has a fixed
frequency
• Duty cycle is fixed at 50%
• Can be used to drive a speaker or
• Two inputs: signal and ground
buzzer
• Produces a click when a rising edge is
• Two or three arguments
applied
• Pin number
• Driving with a square wave produces a
• Frequency, in Hz pitch
• Duration in ms (optional)
2-42
Interfacing with the Arduino
Arduino Libraries
▪ Many devices are more complicated then simple sensors/actuators
▪ Microcontroller (ATMega328) has components which are hard to use
• Memories, communication interfaces, PWM logic, etc.
▪ Arduino provides libraries to facilitate their use
▪ Libraries are also available for external hardware
• Wifi controller, LCD, GSM controller Reading and Writing (EEPROM)
• Access one address at a time
EEPROM
• Each address contains one byte
• Electronically Erasable Programmable Read-
• EEPROM.read(address) returns
Only Memory
the content of an address
• Non-volatile memory; holds data without
• EEPROM.write(address, data)
power
writes a single byte of data into the
• Similar to Flash but more flexible address
• Write a single byte at a time
• Address must be between 0 to 1023
• Supports many more write cycles
• Only 1024 bytes available on ATMega328
Read more about reading, writing and masking!
2-43
Interfacing with the Arduino
I2C Communication Protocol I2C Terminology
• Synchronous, serial protocol • Master – Initiates and terminates
• Multiple masters, multiple slaves transmission; generates SCL
• Bitwidth is fixed, independent of number of • Slave – Addressed by the Master
slaves • Transmitter – Placing data on the bus
• Two wires: SDA (serial data) and SCL (serial
• Receiver – Reading data from the bus
clock)
• Both lines are open-drain
I2C Network
• Pulled up to high by default
• State of bus is always known
• SDA and SCL are bidirectional
2-44
Interfacing with the Arduino
Wire library Master Communication
• The wire library is used to access I2C 1. Start the transmission
• #include <Wire.h> needed at the top 2. Sends data
• Wire.begin() function initializes I2C
3. End the transmission
hardware
• Calling Wire.begin() with no argument • Data is put into a buffer before sending
makes the Arduino a Master • Wire.beginTransmission(address):
• Calling Wire.begin(addr) with an address Start condition and address are initialized
makes the Arduino a Slave • Wire.write(data): Buffers data for
Master Read sending
• Wire.requestFrom(): used to specify read transaction • Wire.endTransmission():
• Three transactions • Transmits data in buffer
1. Address of the slave
• Returns a status byte, 0 for success
2. Number of bytes to read
3. Option stop argument to release the bus after
• Wire.read(): returns a single byte from the receive buffer
• Wire.available(): returns number of bytes waiting
2-45
Interfacing with the Arduino
Slave Operation
• Slave must wait for a transmission,
cannot initiate
• Busy wait loops are wasteful
• Callback functions: functions called
when an event occurs
• Wire.onReceive(): Identifies the
function called when the slave receives
data from a master (write transaction)
• Wire.onRequest(): Identifies the
function called when data is requested
from the slave (read transaction)
2-46
Interfacing with the Arduino
Arduino Shields
• Shield: A printed circuit board (PCB) that
adds functionality to Arduino
• Hardware: A circuit is pre-wired and sold
on a printed circuit board
• Software: A software library is provided Connected pins
to interact with the hardware • Pins on the bottom of the shield connect
Benefits of Shields to pins of the Arduino
• No wiring needed • Most shields only use a small subset of
• Circuit is pre-wired pins
• Connections to Arduino are fixed by stacking • Need to know which pins are used when
• Simple to use using multiple shields
• Library takes care of complicated details • Shield headers may need to be soldered
2-47
Interfacing with the Arduino
Ethernet Shields Internet Addresses
• Allows internet connections through a • MAC address: unique address “hardware”
wired interface into each network adapter. 6 bytes long
• Shield includes an Ethernet jack (RJ45) for • IP address: address used for addressing by
a network cable internet protocols. 4 bytes long
• Several shields are available
• Common library is used
2-48
Interfacing with the Arduino
Ethernet Library Dynamic Host Connection Protocol (DHCP)
#include • Every node on the internet needs an IP address
• There are many .h files to include • DHCP allows the IP address to be assigned dynamically
• Ethernet.h • DHCP is invoked if Ethernet.begin() has no IP
• EthernetClient.h address argument
• Most routers are configured for DHCP
• EthernetServer.h
• Static IP addresses are typical for servers
Initialize the Ethernet Interface
• Invoke the Ethernet.begin() function Ethernet Client
• Arduino can act as a client, create a client object
• 5 possible arguments, only the first is required
• EthernetClient client;
• MAC address required
• Needs to connect to a server
• IP address • result = client.connect(ip,
• DNS: address of the domain name server port); or
• Gateway: address of a router which knows how • result = client.connect(domain,
to forward packets to other networks port);
• Returns 1 if connection is made, 0 if it is not
• Subnet mask: Mask which specifies the local
• client.stop(); ends connection
network (i.e. 255.255.255.0)
2-49
Interfacing with the Arduino
Ethernet Library
Sending and Receiving data Ethernet Server
• client.print(data); and • Arduino can act as a server, create a server object
client.println(data); send data • EthernetServer server = EthernetServer(port);
• println() adds carriage return • Port argument is the port that the server listens to
• data is a string or an array of bytes • To start listening, server must create a client object
• client.write(value); sends a raw • EthernetClient client = server.available();
byte • Client object will be false (0) if client is not available
• data = client.read(); reads the • client.stop(); will close client with connection
next byte
• Use client.print() and client.write() to send data
• result = client.available();
• Use client.read() to read data
returns 1 if data is waiting
2-50
Interfacing with the Arduino
WiFi Shield WiFi Client and Server
• Same as ethernet client and server process
• Allows internet connection through
• WiFiClient:
wireless interface • WiFiClient client;
• IEEE 802.11 (WiFi) standard is used • result = client.connect(ip, port);
• Library is similar to the ethernet • client.stop();
• WiFiServer: slightly different
library
• WiFiServer server = server(port);
WiFi Initialization • Server.begin(); -starts server listening on port
• Wifi.begin(); - no arguments; just
Scanning WiFi Networks
initialize the shield
• Which network(SSID) should you connect to?
• Wifi.begin(ssid); - connects the
• netnum = WiFi.scanNetworks(); -returns the number of
network ssid
networks available
• Wifi.begin(ssid, pass); - connects to • ssid = WiFi.SSID(i); -returns the SSID of the ith network
ssid with WPA-2 password
• strength = WiFi.RSSI(i); -returns the signal strength of the
• Wifi.begin(ssid, keyindex, key); ith network (-80 to 0)
- connects to ssid with key as WEP password • enc = WiFi.encryptionType(i); -returns the encryption
• WEP can have up to 4 keys type used in the ith network
• keyindex indicates which key to use • WEP, WPA, WPA2, none, multiple possible
2-51
Debre Berhan University
Electrical and Computer Engineering Department
Embedded Systems
Lecturer: Addisalem H.
Dec. 2022
Chapter IV: Real-Time Operating Systems (RTOS)
❖ Introduction
❖ History and Purpose
❖ The Scheduler
❖ Real-Time Scheduling
❖ Scheduling Points
❖ Locking and Unlocking
❖ Tasks
❖ Message Passing
❖ Other Functionality
❖ Interrupt Handling
❖ Real-Time Characteristics
❖ RTOS Selection Process
4-2
Real-Time Operating Systems (RTOS)
Introduction
▪ In general, an operating system (OS) is responsible for managing the hardware resources of a
computer and hosting applications that run on the computer
▪ An RTOS performs these tasks, but is also specially designed to run applications with very precise
timing and a high degree of reliability
▪ This can be especially important in measurement and automation systems where downtime is costly
or a program delay could cause a safety hazard
▪ Many embedded systems today incorporate an operating system
▪ This can range from a small kernel to a full-featured operating system typically called a real-time
operating system or RTOS (pronounced “are-toss”)
▪ To be considered "real-time", an operating system must have a known maximum time for each of
the critical operations that it performs (or at least be able to guarantee that maximum most of the
time)
▪ Some of these operations include OS calls and interrupt handling
4-3
Real-Time Operating Systems (RTOS)
Introduction
▪ Operating systems that can absolutely guarantee a maximum time for these operations are
commonly referred to as "hard real-time", while operating systems that can only guarantee a
maximum most of the time are referred to as "soft real-time“
▪ In practice, these strict categories have limited usefulness - each RTOS solution demonstrates
unique performance characteristics and the user should carefully investigate these characteristics
Example: Imagine that you are designing an airbag system for a new model of car. In this case, a small error in timing (causing the
airbag to deploy too early or too late) could be catastrophic and cause injury. Therefore, a hard real-time system is needed; you
need assurance as the system designer that no single operation will exceed certain timing constraints. On the other hand, if you
were to design a mobile phone that received streaming video, it may be ok to lose a small amount of data occasionally even
though on average it is important to keep up with the video stream. For this application, a soft real-time operating system may
suffice.
▪ The main point is that, if programmed correctly, an RTOS can guarantee that a program will run with very
consistent timing.
▪ Real-time operating systems do this by providing programmers with a high degree of control over how tasks are
prioritized, and typically also allow checking to make sure that important deadlines are met
4-4
Real-Time Operating Systems (RTOS)
Important Terminology and Concepts
▪ Determinism: An application (or critical piece of an application) that runs on a hard real-time operating system is
referred to as deterministic if its timing can be guaranteed within a certain margin of error.
▪ Soft, Hard, Firm RTOS: An OS that can absolutely guarantee a maximum time for the operations it performs is
referred to as hard real-time. In Hard RTOS, all critical tasks must be completed within the specified time
duration, i.e., within the given deadline. Not meeting the deadline would result in critical failures such as damage
to equipment or even loss of human life (e.g. airbags in cars). In contrast, an OS that can usually perform
operations in a certain time is referred to as soft real-time. Soft RTOS accepts a few delays via the means of the
Operating system. In this kind of RTOS, there may be a closing date assigned for a particular job, but a delay for
a small amount of time is acceptable. So, cut off dates are treated softly via means of this kind of RTOS (e.g.
Online Transaction systems). In Firm RTOS additionally want to observe the deadlines. However, lacking a
closing date might not have a massive effect, however may want to purposely undesired effects, like a massive
discount within the fine of a product (e.g. various forms of Multimedia applications).
▪ Jitter: The amount of error in the timing of a task over subsequent iterations of a program or loop is referred to
as jitter. Real-time operating systems are optimized to provide a low amount of jitter when programmed
correctly; a task will take very close to the same amount of time to execute each time it is run.
4-5
Real-Time Operating Systems (RTOS)
Example Real-Time Applications
❖ Real-time operating systems were designed for two general classes of applications: event response and closed-loop
control. Event response applications, such as automated visual inspection of assembly line parts, require a response to
a stimulus in a certain amount of time. In this visual inspection system, for example, each part must be photographed
and analyzed before the assembly line moves.
❖ By carefully programming an application that runs on a hard real-time operating system, designers working on event
response applications can guarantee that a response will happen deterministically (within a certain maximum amount
of time). Considering the parts inspection example, using a general-purpose OS could result in a part not being
inspected in time, therefore delaying the assembly line, forcing the part to be discarded, or shipping a potentially
defective part.
❖ In contrast, closed-loop control systems, such as an automotive cruise control system, continuously process feedback
data to adjust one or more outputs. Because each output value depends on processing the input data in a fixed
amount of time, it is critical that loop deadlines are met in order to assure that the correct outputs are produced.
What would happen if a cruise control system failed to determine what the throttle setting should be at a given point
in time? Once again, hard real-time operating systems can guarantee that control system input data is processed in a
consistent amount of time (with a fixed worst-case maximum).
❖ It should also be noted that many applications that must run for extended periods of time can benefit from the
reliability that an RTOS can provide. Because real-time operating systems typically run a minimal set of software rather
than many applications and processes at the same time, they are well suited for systems that require 24-7 operation or
where down-time is unacceptable or expensive.
4-6
Real-Time Operating Systems (RTOS)
How RTOSs Differ From General-Purpose OSs
Operating systems such as Microsoft Windows and Mac OS can provide an excellent platform for developing and running
your non-critical measurement and control applications. However, these operating systems are designed for different use
cases than real-time operating systems, and are not the ideal platform for running applications that require precise timing
or extended up-time.
Setting Priorities
▪ When programming an application, most operating systems (of any type) allow the programmer to specify a
priority for the overall application and even for different tasks within the application (threads).
▪ These priorities serve as a signal to the OS, dictating which operations the designer feels are most important.
▪ The goal is that if two or more tasks are ready to run at the same time, the OS will run the task with the higher
priority.
▪ In practice, general-purpose operating systems do not always follow these programmed priorities strictly. Because
general-purpose operating systems are optimized to run a variety of applications and processes simultaneously,
they typically work to make sure that all tasks receive at least some processing time. As a result, low-priority
tasks may in some cases have their priority boosted above other higher priority tasks. This ensures some amount
of run-time for each task, but means that the designer's wishes are not always followed.
▪ In contrast, real-time operating systems follow the programmer's priorities much more strictly. On most real-
time operating systems, if a high priority task is using 100% of the processor, no other lower priority tasks will
run until the high priority task finishes. Therefore, real-time system designers must program their applications
carefully with priorities in mind. In a typical real-time application, a designer will place time-critical code (e.g.
event response or control code) in one section with a very high priority. Other less-important code such as
logging to disk or network communication may be combined in a section with a lower priority.
4-7
Real-Time Operating Systems (RTOS)
How RTOSs Differ From General-Purpose OSs
Interrupt Latency
▪ Interrupt latency is measured as the amount of time between when a device generates an interrupt and when that
device is serviced. While general-purpose operating systems may take a variable amount of time to respond to a
given interrupt, real-time operating systems must guarantee that all interrupts will be serviced within a certain
maximum amount of time. In other words, the interrupt latency of real-time operating systems must be
bounded.
Performance
▪ One common misconception is that real-time operating systems have better performance than other general-
purpose operating systems.
▪ While real-time operating systems may provide better performance in some cases due to less multitasking
between applications and services, this is not a rule.
▪ Actual application performance will depend on CPU speed, memory architecture, program characteristics, and
more.
▪ Though real-time operating systems may or may not increase the speed of execution, they can provide much
more precise and predictable timing characteristics than general-purpose operating systems.
4-8
Real-Time Operating Systems (RTOS)
Why use an RTOS?
There are well-established techniques for writing good embedded software without the use of an RTOS. In
some cases, these techniques may provide the most appropriate solution; however as the solution becomes
more complex, the benefits of an RTOS become more apparent. These include:
▪ Priority Based Scheduling: The ability to separate critical processing from non-critical is a powerful tool.
▪ Abstracting Timing Information: The RTOS is responsible for timing and provides API functions. This allows for
cleaner (and smaller) application code.
▪ Maintainability/Extensibility: Abstracting timing dependencies and task based design results in fewer
interdependencies between modules. This makes for easier maintenance.
▪ Modularity: The task based API naturally encourages modular development as a task will typically have a clearly
defined role.
▪ Promotes Team Development: The task-based system allows separate designers/teams to work independently on
their parts of the project.
▪ Easier Testing: Modular task based development allows for modular task based testing.
▪ Code Reuse: Another benefit of modularity is that similar applications on similar platforms will inevitably lead to
the development of a library of standard tasks.
▪ Improved Efficiency: An RTOS can be entirely event driven; no processing time is wasted polling for events that
have not occurred.
▪ Idle Processing: Background or idle processing is performed in the idle task. This ensures that things such as CPU
load measurement, background CRC checking etc. will not affect the main processing.
4-9
Real-Time Operating Systems (RTOS)
History and Purpose
▪ In the early days of computing, there was no such thing as an operating system
▪ Application programmers were completely responsible for controlling and monitoring the state of the processor
and other hardware.
▪ In fact, the purpose of the first operating systems was to provide a virtual hardware platform that made
application programs easier to write.
▪ To accomplish this goal, operating system developers needed only provide a loose collection of routines much
like a modern software library for resetting the hardware to a known state, reading the state of the inputs, and
changing the state of the outputs.
▪ Modern operating systems add to this the ability to execute multiple software tasks simultaneously on a single
processor a feature called multitasking.
▪ Each such task (also commonly called a thread) is a piece of the software that can be separated from the rest of
the operating system and run independently.
▪ A set of embedded software requirements can usually be broken down into a small number of such independent
pieces
▪ Tasks provide a key software abstraction that makes the design and implementation of embedded software easier,
and the resulting source code simpler to understand and maintain.
▪ By breaking the larger program into smaller pieces, the programmer can more easily concentrate her energy and
talents on the unique features of the system under development.
4-10
Real-Time Operating Systems (RTOS)
History and Purpose
▪ Tasks provide a key software abstraction that makes the design and implementation of embedded software easier,
and the resulting source code simpler to understand and maintain.
▪ By breaking the larger program into smaller pieces, the programmer can more easily concentrate her energy and
talents on the unique features of the system under development.
▪ Strictly speaking, an operating system is not a required component of any computer system embedded or
otherwise.
▪ It is always possible to perform the same functions from within the application program itself. There is one path
of execution starting at main that runs on the system.
▪ This is the equivalent of having only one task. But as the complexity of the application expands beyond the simple
task of blinking an LED, the benefits of an operating system far outweigh the associated costs. One common part
of all operating systems is the kernel.
▪ In most operating systems, the kernel consists of the scheduler, the routine to handle switching between the
different tasks running in the system, and the mechanisms of communication between tasks.
4-11
Real-Time Operating Systems (RTOS)
The Scheduler
▪ In actuality, the tasks are not executed at the same time. Rather, they are executed in pseudo-parallel. They merely take
turns using the processor. This is similar to the way several people might read the same copy of a book. Only one person
can actually use the book at a given moment, but each person can read it if everyone takes turns.
▪ An operating system is responsible for deciding which task gets to use the processor at a particular moment. The piece of
the operating system that decides which of the tasks has the right to use the processor at a given time is called the
scheduler.
▪ The scheduler is the heart and soul of any operating system. Some of the more common scheduling algorithms
are:
First-in-first-out (FIFO)
This scheduling (also called cooperative multitasking) allows each task to run until it is finished, and only after that is the next task
started.
Shortest job first
This algorithm allows each task to run until it completes or suspends itself; the next task selected is the one that will require the
least amount of processor time to complete.
Priority
This algorithm is typically used in real-time operating systems. Each task is assigned a priority that is used to determine when the
task executes once it is ready. Priority scheduling can be either preemptive or non preemptive. Preemptive means that any
running task can be interrupted by the operating system if a task of higher priority becomes ready.
Round robin
In this scheduling algorithm, each task runs for some predetermined amount of time called a time slice. After that time interval
has elapsed, the running task is preempted by the operating system, and the next task in line gets its chance to run. The
preempted task doesn’t get to run again until each of the other tasks in that round has had its chance.
4-12
Real-Time Operating Systems (RTOS)
Real-Time Scheduling
▪ The scheduler in some operating systems is real-time.
▪ While the schedulers in the previous section take only priorities and time slices into account, a real-time scheduler takes into
account that some tasks have deadlines.
▪ Some tasks in a real-time system may not have deadlines or might have low penalties for missing deadlines.
▪ Tasks such as these can use background processing time to do their work.
▪ In this type of operating system, the real-time scheduler should know the deadlines of all the tasks.
▪ The scheduler should base decisions on a comparison of the deadlines of tasks that are in the ready queue
There are several real-time schedulers, including:
Real-time executive
Each task is assigned a unique timeslot in a periodically repeating pattern. A real-time executive is more static than an operating system and assumes that the
programmer knows how long each task takes. If the executive knows the task
can complete its work in the allotted time, its deadlines can all be met. This won’t work if you need to create and exit tasks on the fly or run tasks at irregular
intervals.
Earliest deadline first
The operating system tracks the time of the next deadline for all tasks. At each scheduling point, the scheduler selects the task with the closest deadline. This is a
priority-based scheduler, but with the addition that it calculates the deadlines of real-time tasks at each timer tick and adjusts priorities as appropriate. If new
priorities are assigned, this might mean new tasks are run and, therefore, that a context switch (which we discuss later in this chapter in the section “Context
switch”) must take place. One disadvantage to this scheduler is that it has a large computational overhead.
Minimal laxity first
The operating system tracks deadlines and the time to complete the remaining work for each task. The scheduler selects the task with least laxity, where laxity is
the available time minus the remaining work time, and the available time is the deadline time minus the current time. The theory behind this scheduling algorithm is
that the task with the least “time to spare” can least afford to yield the processor. The exact order of which tasks run may differ from the earliest-deadline first
scheduler.
Resource reservation
When a task is created, it states its requirements in terms of deadlines, processor usage, and other relevant resources. The operating system should admit the new
task only if the system can guarantee those resources without making any other (already admitted) tasks fail.
4-13
Real-Time Operating Systems (RTOS)
Scheduling Points
You might be asking yourself how the scheduler which is also a piece of software gets an opportunity to execute and do its
job. That is where scheduling points enter in. Simply stated, scheduling points are the set of operating system events that
result in a run of the scheduler code. Following is a list of scheduling points:
Task creation
When a task is created, the scheduler is called to select the next task to be run. If the currently executing task still has the highest
priority of all the ready tasks, it will be allowed to continue using the processor. Otherwise, the highest-priority ready task will be
executed next.
Task deletion
As in task creation, the scheduler is called during task deletion. However, in the case of task deletion, if the currently running task is
being deleted, a new task is always selected by virtue of the fact that the old one no longer exists.
Clock tick
The clock tick is the heartbeat of the system. It is a periodic event that is triggered by a timer interrupt (similar to the one we have
already discussed). The clock tick provides an opportunity to awaken tasks that are waiting for a certain length of time to pass before
taking their next action.
Task block
When the running task makes a system call that blocks, that task is no longer able to use the processor. Thus, the scheduler is invoked
to select a new task to run.
Task unblock
A task might be waiting for some event to take place, such as for data to be received. Once the event occurs, the blocked task
becomes ready to execute and thus is immediately eligible to be considered for execution.
4-14
Real-Time Operating Systems (RTOS)
Task States
▪ Different types of tasks can run in an operating system. For example, a task can be periodic, where it exits after
its work is complete.
▪ The task can then be restarted when there is more work to be done. Typically, however, a task runs forever.
Each task also has its own stack that is typically allocated statically
▪ Only one task could actually use the processor at a given time. That task is said to be the running task, and no
other task can be in that same state at the same time.
▪ Tasks that are ready to run but are not currently using the processor are in the ready state, and tasks that are
waiting for some event external to themselves to occur before going on are in the waiting state. Figure below
shows the relationships between these three states.
4-15
Real-Time Operating Systems (RTOS)
Task States
▪ A transition between the ready and running states occurs whenever the operating system selects a new task to
run during a scheduling point.
▪ The task that was previously running leaves the running state, and the new task (selected from the queue of tasks
in the ready state) is promoted to running.
▪ Once it is running, a task will leave that state only if it terminates, if a higher-priority task becomes ready, or if it
needs to wait for some event external to itself to occur before continuing.
▪ In the latter case, the task is said to block, or wait, until that event occurs. A task can block by waiting for another
task or for an I/O device, or it can block by sleeping (waiting for a specific time period to elapse).
▪ When the task blocks, it enters the waiting state, and the operating system selects one of the ready tasks to be
run. So, although there may be any number of tasks in each of the ready and waiting states, there will always be
exactly one task in the running state at any time.
▪ It is important to note that only the scheduler can promote a task to the running state. Newly created tasks and
tasks that are finished waiting for their external event are placed into the ready state first.
▪ The scheduler will then include these new ready tasks in its future decision-making. In order to keep track of the
tasks, the operating system typically implements queues for each of the waiting and ready states.
▪ The ready queue is often sorted by priority so that the highest-priority task is at the head of the queue. The
scheduler can then easily pick the highest-priority
4-16
Real-Time Operating Systems (RTOS)
Context Switch
▪ The actual process of changing from one task to another is called a context switch
▪ Task contexts are processor-specific and sometimes compiler-specific, as is the code that implements the context
switch
▪ That means it must always be written in assembly language and is very hardware-specific
▪ Operating systems, especially for embedded systems, emphasize the goal of minimizing the time needed to switch
task contexts
4-17
Real-Time Operating Systems (RTOS)
Task Context
▪ The scheduler maintains information about the state of each task. This information is called the task context.
▪ A task’s context records the state of the processor just prior to the point at which another task takes control of
it.
▪ This usually consists of a pointer to the next instruction to be executed (the instruction pointer), the address of
the current top of the stack (the stack pointer), and the contents of the processor’s flag and general-purpose
registers.
▪ To keep tasks and their contexts organized, the operating system maintains some information about each task.
▪ Operating systems written in C often keep this information in a data structure called the task control block.
▪ The task control block contains a pointer to the task’s context, the current state of the task, the task priority, the
task entry-point function, and any task-specific data (such as parameters and task identification)
4-18
Real-Time Operating Systems (RTOS)
Task Priorities
❖ Setting the priorities of the tasks in a system is important. Care needs to be taken so that lower-priority
tasks get to do their work, just as the higher-priority tasks do. Otherwise, starvation of a task can occur,
where a low-priority task is kept from doing any work at all.
There are several reasons that starvation may occur in a system, including the following:
▪ Processor overload occurs when high-priority tasks monopolize the processor and are always running or ready to run.
▪ Low-priority tasks are always at the end of a priority-based event queue and, therefore, may be permanently blocked
from executing.
▪ A task may be prevented from running by a bug in another task; for example, one task fails to signal when it is supposed
to.
4-19
Real-Time Operating Systems (RTOS)
Rare Monotonic Scheduling
Task Mechanics
Task Synchronization
Mutexes and Semaphores
Deadlock and Priority Inversion
Message Passing
Read!
Other Functionality
Real-Time Characteristics
To Use or Not to Use an RTOS
4-20
Real-Time Operating Systems (RTOS)
Interrupt Handling
There are several issues you need to be aware of when handling interrupts in embedded systems that use an operating
system, including:
Interrupt priority
Interrupts have the highest priority in a system even higher than the highest operating system task. Interrupts are not
scheduled; the ISR executes outside of the operating system’s scheduler.
Disabling interrupts
Because the operating system code must guarantee its data structures’ integrity when they are accessed, the operating
system disables interrupts during operations that alter internal operating system data, such as the ready list. This increases
the interrupt latency. The responsiveness of the operating system comes at the price of longer interrupt latency. When a
task disables interrupts, it prevents the scheduler from doing its job. Tasks should not disable interrupts on their own.
Interrupt stack
Some operating systems have a separate stack space for the execution of ISRs. This is important because, if interrupts are
stored on the same stack as regular tasks, each task’s stack must accommodate the worst-case interrupt nesting scenario.
Such large stacks increase RAM requirements across all n tasks.
Signaling tasks
Because ISRs execute outside of the scheduler, they are not allowed to make any operating system calls that can block.
For example, an ISR cannot wait for a semaphore, though it can signal one.
4-21
Real-Time Operating Systems (RTOS)
What Should be Considered When Choosing an RTOS?
▪ Responsiveness: The RTOS scheduling algorithm, interrupt latency and context switch times will significantly
define the responsiveness and determinism of the system. The most important consideration is what type of
response is desired – Is a hard real time response required? This means that there are precisely defined deadlines
that, if not met, will cause the system to fail. Alternatively, would a non-deterministic, soft real time response be
appropriate? In which case there are no guarantees as to when each task will complete.
▪ Available system resources: Micro kernels use minimum system resources and provide limited but essential task
scheduling functionality. Micro kernels generally deliver a hard real time response, and are used extensively with
embedded microprocessors with limited RAM/ROM capacity, but can also be appropriate for larger embedded
processor systems.
▪ Alternatively, a full featured OS like Linux or WinCE could be used. These provide a feature rich operating
system environment, normally supplied with drivers, GUI’s and middleware components. Full featured OS’s are
generally less responsive, require more memory and more processing power than micro kernels, and are mainly
used on powerful embedded processors where system resources are plentiful.
▪ Open source or professionally licensed: There are widely used, free open source RTOS’s available, distributed
under GPL or modified GPL licenses. However, these licenses may contain copy left restrictions and offer little
protection. Professionally licensed RTOS products remove the copy left restrictions, offer full IP infringement
indemnification and warranties. In addition, you have a single company providing support and taking responsibility
for the quality of your product.
4-22
Real-Time Operating Systems (RTOS)
What Should be Considered When Choosing an RTOS?
▪ Quality: What emphasis does the RTOS supplier place on quality within their organization? Quality is more
than just a coding standard. Are the correct procedures in place to guarantee the quality of future products
and support? Well-managed companies that take quality seriously tend to be ISO 9001 certified.
▪ Safety Certification: Pre-certified and certifiable RTOS’s are available for applications that require
certification to international design standards such as DO-178C and IEC 61508. These RTOS’s provide key
safety features, and the design evidence required by certification bodies to confirm that the process used to
develop the RTOS meets the relevant design standard.
▪ Licensing: It’s not only the RTOS functionality and features that you’ll need to consider, but the licensing
model that will work best for your project budget and the company’s “return on investment”.
▪ RTOS Vendor: The company behind the RTOS is just as important as selecting the correct RTOS itself.
Ideally you want to build a relationship with a supplier that can support not only your current product, but
also your products of the future. To do this you need to select a proactive supplier with a good reputation,
working with leading silicon manufacturers to ensure they can support the newest processors and tools.
▪ Trust, quality of product, and quality of support is everything.
4-23
Real-Time Operating Systems (RTOS)
Important Criteria Used in Making an RTOS Selection
▪ Processor support
▪ Real-time characteristics
▪ Budget constraints
▪ Memory usage
▪ Device drivers and software components
▪ Technical support
▪ Tool compatibility
4-24
Real-Time Operating Systems (RTOS)
How does the RTOS Affect the Development of the Design?
❖ The choice of RTOS can greatly affect the development of the design. By selecting an appropriate RTOS
the developer gains:
• A Task based design that enhances modularity, simplifies testing and encourages code reuse;
• An environment that makes it easier for engineering teams to develop together;
• Abstraction of timing behavior from functional behavior, which should result in smaller code size and more
efficient use of available resources.
❖ Peripheral support, memory usage and real-time capability are key features that govern the suitability of
the RTOS. Using the wrong RTOS, particularly one that does not provide sufficient real time capability,
will severely compromise the design and viability of the final product.
❖ The RTOS needs to be of high quality and easy to use. Developing embedded projects is difficult and time
consuming the developer does not want to be struggling with RTOS related problems as well. The RTOS
must be a trusted component that the developer can rely on, supported by in-depth training and good,
responsive support.
4-25
Debre Berhan University
Electrical and Computer Engineering Department
Embedded Systems
Lecturer: Addisalem H.
Jan. 2023
Introduction
❖ Lower power embedded systems might have a range of power management
strategies implemented at the design level, or they have some sophisticated on-
chip features helping to keep power consumption low.
❖ There are also sophisticated algorithms that enable low power consumption
and power management in embedded systems, and any low power system
might need a combination of strategies to prevent excess battery power from
being used.
❖ If you’re designing an embedded system that must be highly power efficient
while also providing the required level of computing power, there are multiple
approaches you can take. It all depends on the design requirements you need
to meet, followed by opting for the right low-power components where
possible.
5-2
Introduction
Low Power Embedded Systems Design Requirements
❖ The first stage in any successful project execution is requirements gathering. For a low-power
embedded system, extending battery life or ensuring overall power efficiency are likely top
priorities, you’ll need to develop requirements around your need for power efficiency.
❖ You’ll need to make decisions around some of the following points:
• If your system is battery powered, how long the system will need to be deployed before requiring
charging?
• How much compute resources does your system need to do its job?
• Are there power-hungry peripherals or circuit blocks that need intermittent power?
• What type of power management techniques or features can your components support?
❖ If you have an idea of the answers to these questions, you can come up with a strategy to
design low power embedded systems.
❖ The design strategy starts with selecting critical components and peripherals, which may need
to be paired up with a power management algorithm.
❖ Once you’ve decided on critical components, you can determine how best to implement a
power management strategy at the system level.
5-3
Introduction
Component Selection
Power consumption in an embedded system is heavily dependent on the main processor, analog front-end,
and any peripherals like displays. Many processor units (MCUs, FPGAs, MPUs, etc.) and other components
are specifically marketed as low-power devices, and they may enable a unique power management approach
in embedded systems.
When selecting components, here are some tips you can use to design a low-power system architecture:
1. Start with must-haves. Your must-have components could be a specific processor or peripheral. Start
here and try to find the lowest power option that satisfies the minimum functional requirements.
2. Peripheral architecture. Think about how peripheral blocks will interact with the host processor and the
environment, and work these into your system architecture.
3. Interfaces and receivers. Various low-speed digital protocols (I2C, SPI, GPIO, etc.) can have different
power outputs. Also, receivers and converters like ADCs could be run at lower sampling rate to reduce
total power consumption.
4. Components with sleep/hibernate modes. Some processors and other IC have sleep modes, where
current is only supplied to critical functional blocks in the IC. Current can drop to well below 0.01 mA in
these modes.
5. Power regulation. Once all the important components have been selected, it’s time to think about power
regulation. Aim for the highest efficiency power regulation strategy you can. Careful design of regulation
stages can ensure power conversion efficiency stays well above 95%.
5-4
Introduction
Power Management Techniques in Embedded Systems
Component-level power consumption is easy to address by choosing the right parts. However,
there are times where a specific component that runs at high power is a must-have. At this point,
the system should be designed so that certain peripherals can be toggled on and off, battery
charge management is implemented, and algorithm optimization.
Peripherals
▪ A strategy where peripherals are switched on/off as needed by the host controller is one way to
ensure power is only being consumed when it is needed. Some components may implement this on-
chip, where groups of interfaces are switched off and the core voltage is reduced to when the
component is not actively processing data. This is a popular feature on many low-cost MCUs.
However, at the system level, there may be system blocks that are not directly connected to the
master processor. These could be switched off by simply cutting power to the peripheral block, or by
putting a slave processor into sleep mode.
5-5
Introduction
Power Management Techniques in Embedded Systems
Battery Management
▪ This strategy is useful for multi-cell battery packs in series, but not all battery packs will support this.
Implementing a battery management algorithm with a balancing system is one way to prevent
excessive power from being drawn from a single cell and ensuring charge is evenly distributed across
cells.
▪ One possible component for implementing a standard balancing algorithm is the BQ769x0 series
from Texas Instruments. This component provides low current balancing between cells with minimal
power loss in the component and microcontroller/FPGA/CPU/MPU.
Algorithm Optimization
▪ Embedded systems designers should ensure any specialty algorithms in their firmware are optimized
so that compute operations are minimized. Software developers working at the enterprise level often
have to consider the number of logical operations involved in implementing an algorithm and need to
find ways to minimize the number of operations to complete a computational task.
▪ Firmware developers and embedded software developers need to do the same for their systems.
Reducing algorithmic complexity leads to less power consumption in the host processor. By
eliminating background processes and services, or by eliminating unnecessary computational
operations, the processor will be performing fewer tasks while idling and will consume less power.
5-6
Importance of Low Power Design
5-7
Low Power at Various Levels of Circuit Design
5-9
Low Power Embedded System Design
3. Duration of operation: the duration of which a device needs to be active, is another major
issue determining the total energy consumption. If a device is idle for majority of the time, a
power-down mode may be incorporated into the design to save power.
4. Power required by the device: this is the most important issue and needs to be estimated even
at the stage of initial design. A better estimation helps in the design process to try out
alternatives.
5. I/O device types: the I/O interface, such as optically isolated I/O and electro-mechanical relays
consume high power. Thus, the system designer needs to avoid them altogether, or minimize
their active periods.
6. Speed of operation: power consumption is directly proportional to the frequency of operation.
The system designer needs to identify the optimum speed for each component, so that the
performance target is met, at the same time, individual subsystems are not operated at a
speed higher than the required one.
5-10
Power Reduction Techniques
5-11
Power Reduction Techniques
5-12
Power Reduction Techniques
Algorithmic Power Minimization
The important issues to be judged for selecting a particular algorithm from alternatives:
1. Memory Reference
• This is very important as memory is normally off-chip from the processor. A large number of
accesses to the memory mean good amount of activity in the address/data bus lines.
• The memory access pattern is also important. If the access pattern is sequential, only the last
significant bits of address bus change, whereas for random access through the memory, most
of the address bits will switch, thus creating higher power dissipation.
2. Presence of cache memory
• The presence and structure of cache memory plays an important role. Cache can be fruitful
utilized to reduce both execution time and power of an implementation if the underlying
algorithm has got locality in its behavior.
• The locality may be both temporal and spatial in nature. While a temporal locality refers to
the fact that a memory location accessed at some time is also likely to be accessed in near
future, spatial locality means if a memory location is accessed at some time, it’s neighboring
locations are also likely to be accessed in near future.
5-13
Power Reduction Techniques
Algorithmic Power Minimization
3. Re-computation vs. Memory Load/Store
• Normal power minimization techniques at algorithm level attempt to reduce the number of
arithmetic operations.
• However, to reduce the number of operations, some repeatedly performed computation is
done only once and stored at a memory location. Later, when necessary, it is reloaded from
the memory.
• This may lead to increased power consumption due to extra memory accesses. If the operand
are already available in CPU registers or no-chip cache, it may be better to re-compute the
value, instead of loading it from memory, from power consumption point of view.
4. Compiler optimization technique
• The typical techniques used by an optimizing compiler can be used to reduce power
consumption of a piece of code.
• The strategies involve strength reduction, common sub-expression elimination, minimizing
memory traffic etc.. Loop unrolling is also often beneficial as it reduced loop overhead.
5-14
Power Reduction Techniques
Algorithmic Power Minimization
5. Number representation: This is another area for algorithmic power trade-off.
The following points may be noted:
– Fixed vs. floating point representation: Fixed point operation are much simpler
than floating point. Thus, it normally leads to power saving, though accuracy may
suffer.
– Sign-magnitude vs. 2’s complement: Selection of sign-magnitude representation
may have significant power saving over 2’s complement, if input samples are
uncorrelated and range is minimized.
– Precision of operations: This is important, since having lower precision allows
one to reduce the size of space needed to store the values.
– A typical example of this is to reduces the number of bits in a portion in several
signal processing applications including speech and image to improve circuit delay
and power.
5-15
Power Reduction Techniques
Architectural Power Minimization
▪ The architectural level transformations can be used to introduce power
saving in a design. There are two generic techniques to save power at the
cost of extra area, keeping the performance of the system unaltered.
These are parallelism and pipelining.
▪ To understand their impact, suppose we have to design a system with
supply voltage V and operating frequency f.
▪ The system is expected to operate on a sequence of input data arriving at
a rate of f.
▪ If we duplicate to have n such similar modules and the input data is
processed by the modules in an interleaved fashion, the blocks may
operate at a lower speed ideally, at a rate of f/n.
5-16
Power Reduction Techniques
Architectural Power Minimization
▪ The system is capable of running at frequency f and the speed of a system
is proportional to the supply voltage, we reduce the supply from V to V/n.
▪ This will reduce the power consumed by the individual blocks by a factor
of n² (as power consumption is proportional to the square of supply
voltage).,
▪ Since all such systems are operating simultaneously, total power saving is
1/n of the original power.
▪ A problem with the scheme is that the hardware is duplicated with other
necessary multiplexing and demultiplexing logic. Another possible
architectural modification often suggested is pipelining.
5-17
Power Reduction Techniques
Logic and Circuit Level Power Minimization
The power reduction approaches at logic and circuit level to reduce the effective
switched capacitance.
The following are some of the directions in which this minimization can be tried out:
1. Static vs. dynamic logic families: CMOS logic can be realized as static or dynamic CMOS.
Depending upon the signal transition probabilities, one of the design styles may have an edge
over the other.
For example, for a two-input NAND gate with uniform probability distribution for the inputs, the
probability that the output is zero is 0.25, whereas, the probability of output being one is 0.75.
2. Glitches and hazards: This is another potential sources of power consumption, particularly in
static CMOS circuits. A glitch at the output of a gate can come due to the differences in
arrival times of input signals.
5-18
Power Reduction Techniques
Logic and Circuit Level Power Minimization
3. Technology mapping: The logic synthesis library often contains
different implementations of the same logic module. They
normally differ in terms of area, delay, power, etc.
▪ A logic synthesis procedure targeted to power minimization may choose
implementations that require higher area of delay, but score better in terms
of power. For example, consider a four-input AND function.
5-19
Power Reduction Techniques
Control Logic Power Minimization
▪ Power optimization of controller circuitry is very important
▪ This is because while the data path of a design can be selectively turned OFF when not in use,
controller is always active.
▪ A controller is often specified and realized as a finite state machine.
▪ The synthesis of FSM targeting low power can be addressed from various angles.
State Assignment
▪ This is the assignment of binary codes to the FSM states to realize it. For low power state encoding, the steady
state probability for each of the states is determined
▪ Codes with lesser hamming distance are allocated to the states having higher transition probabilities between
them
▪ This minimizes the number of transitions in the next state and output combinational logic
FSM partitioning
▪ High transition probability due to FSM is in some state belonging to a cluster. Probabilities of inter-cluster
transitions are low FSM is partitioned into two or more sub-FSMs.
5-21
Debre Berhan University
Electrical and Computer Engineering Department
Embedded Systems
Lecturer: Addisalem H.
Jan. 2023
Chapter VI: Embedded Systems Design
❖ Introduction
6-2
Introduction
Why Embedded Systems are Different
▪ Embedded systems are dedicated to specific tasks, whereas PCs are generic computing
platforms
▪ Embedded systems are supported by a wide array of processors and processor architectures
▪ Embedded systems are usually cost sensitive
▪ Embedded systems have real-time constraints
▪ If an embedded system is using an operating system at all, it is most likely using an RTOS
▪ The implications of software failure are much more severe in embedded systems than in
desktop systems
▪ Embedded systems have power constraints
▪ Embedded systems must operate under extreme environmental conditions
▪ Embedded systems have far fewer system resources than desktop Systems
▪ Embedded systems require specialized tools and methods to be efficiently designed
▪ Embedded microprocessors often have dedicated debugging circuitry
6-3
The Embedded Design Life Cycle
• Unlike the design of a software application on a standard Embedded systems design life cycle follows the
platform, the design of an embedded system implies that both following seven phases in general:
software and hardware are being designed in parallel.
• Product specification
• Although this isn't always the case, it is a reality for many designs
today. • Partitioning of the design into its
• The profound implications of this simultaneous design process software and hardware components
heavily influence how systems are designed. • Iteration and refinement of the
Schematic representation of the embedded design lifecycle partitioning
• Independent hardware and software
design tasks
• Integration of the hardware and software
components
• Product testing and release
• On-going maintenance and upgrading
6-4
The Embedded Design Life Cycle
Product Specification
▪ For many R&D engineers, designing the right product means cramming
everything possible into the product to make sure they don't miss anything.
Obviously, this wastes time and resources.
▪ Which is why marketing and sales departments lead (or completely
execute) the product-specification process for most companies.
▪ Although some methods of customer research, such as questionnaires and
focus groups, clearly belong in the realm of marketing specialists, most
projects benefit from including engineers in some market-research activities.
▪ A common factor for the successful products is that the design team share
a common vision of the product they are designing.
▪ When asked about the product, everyone involved - senior management,
marketing, sales, quality assurance, and engineering - would provide the
same general description.
6-5
The Embedded Design Life Cycle
Hardware/Software Partitioning
▪ Since an embedded design will involve both hardware and software components, someone
must decide which portion of the problem will be solved in hardware and which in
software.
▪ This choice is called the “partitioning decision.”
▪ The partitioning decision is a complex optimization problem. Many embedded system
designs are required to be
• Price sensitive
• Leading-edge performers
• Non-standard
• Market competitive
• Proprietary
▪ These conflicting requirements make it difficult to create an optimal design for the
embedded product.
▪ Given this n-space of possible choices, the designer or design team must rely on
experience to arrive at an optimal design.
6-6
The Embedded Design Life Cycle
Iteration and Implementation (Before Hardware and Software Teams
Stop Communicating)
▪ This represents a somewhat blurred area between implementation and
hardware/software partitioning in which the hardware and software paths
diverge.
▪ This phase represents the early design work before the hardware and
software teams build "the wall" between them.
▪ Even though major blocks might be partitioned between the hardware
components and the software components, plenty of time remains to move
these boundaries as more of the design constraints are understood and
modeled.
6-7
The Embedded Design Life Cycle
Detailed Hardware and Software Design
The percentage of project time spent in each phase of the embedded design life cycle. The curve
shows the cost associated with fixing a defect at each stage of the process.
6-8
The Embedded Design Life Cycle
Hardware/Software Integration
▪ The process of integrating embedded software and hardware is an exercise
in debugging and discovery.
▪ Discovery is an especially apt term because the software team now finds
out whether it really understood the hardware specification document
provided by the hardware team.
▪ The difficult thing in embedded system design is to combine the first
hardware prototype, the application software, the driver code, and the
operating system software together with a pinch of optimism and to have
the design work perfectly.
▪ this scenario is so unlikely for one thing, the real-time nature of embedded
systems leads to highly complex, nondeterministic behavior that can only be
analyzed as it occurs.
6-9
The Embedded Design Life Cycle
Product Testing and Release
▪ Product testing takes on special significance when the performance of the
embedded system has life or death consequences attached.
▪ Because embedded systems usually have extremely tight design margins to
meet cost goals, testing must determine whether the system is performing
close to its optimal capabilities.
▪ This is especially true if the code is written in a high-level language and the
design team consists of many developers.
▪ The job of testing the embedded product goes to a separate team of
engineers and technicians because asking a designer to test his own code or
product usually results in erratic test results.
▪ In many instances, the Test Engineering Group is the last line of defense
between a smooth product release and a major financial disaster.
6-10
The Embedded Design Life Cycle
Maintaining and Upgrading Existing Products
▪ The majority of embedded system designers (around 60 percent) maintain
and upgrade existing products, rather than design new products.
▪ Most of these engineers were not members of the original design team for a
particular product, so they must rely on only their experience, their skills,
the existing documentation, and the old product to understand the original
design well enough to maintain and improve it.
▪ This phase of a product's life cycle requires tools that are especially tailored
to reverse engineering and rapidly facilitating "what if ..." scenarios.
• For example, it's tempting to try a quick fix by speeding up the processor clock by 25
percent; however, this could cause a major ripple effect through the entire design, from
memory chip access time margins to increased RF emissions. If such a possibility could
be as easily explored as making measurements on a few critical code modules,
however, you would have an extremely powerful tool on your hands.
6-11
The Embedded Design Life Cycle
❖ Even the development of a microcontroller-based embedded system is a complex process.
❖ Development tools are hardware and software tools designed to help programmers develop
and test systems in a relatively short time.
❖ The tools for developing software and hardware for microcontroller-based embedded systems
include editors, assemblers, compilers, debuggers, simulators, emulators, and device
programmers.
❖ A typical development cycle starts with writing the application program using a text editor. The
program is then translated into an executable code with the help of an assembler or compiler.
❖ If the program has several modules, a linker is used to combine them into a single application.
Any syntax errors are detected by the assembler or compiler and must be corrected before
the executable code can be generated.
❖ Next, a simulator is used to test the application program without the target hardware.
Simulators are helpful in checking the correctness of an algorithm or a program with limited or
no input-outputs, and most errors can be removed during simulation.
❖ Once the program seems to be working and the programmer is happy with it, the executable
code is loaded to the target microcontroller chip using a device programmer, and the system
logic is tested.
6-12
The Embedded Design Life Cycle
Software Development Tools
▪ Software development tools are computer programs, usually run on personal computers, that allow
the programmer (or system developer) to create, modify, and test applications programs.
▪ Some common software development tools are:
• Text editors
• Assemblers/compilers
• Simulators
• High-level language simulators
• Integrated development environments (IDEs)
▪ Integrated development environments (IDEs) are powerful PC-based programs which include
everything to edit, assemble, compile, link, simulate, and source-level debug a program, and then
download the generated executable code to the physical microcontroller chip using a programmer
device.
▪ These programs are in graphical user interface (GUI), where the user can select various options from
the program without having to exit it.
▪ IDEs can be extremely useful when developing microcontroller-based systems.
6-13
The Embedded Design Life Cycle
Hardware Development Tools
▪ Numerous hardware development tools are available for PIC
microcontrollers.
▪ Some of these products are manufactured by Microchip Inc., and some by
third-party companies. The most ones are:
• Development boards
• Device programmers
• In-circuit debuggers
• In-circuit emulators
• Breadboards
6-14
The Embedded Design Life Cycle
Read
▪ The Selection Process
▪ The Partitioning Decision
▪ The Development Environment
▪ Maintenance and Testing
6-15