Introduction to
Embedded Systems
Programming
Embedded Systems?
Cyber-Physical Systems (CPS)
[Link] [Link]
An Embedded System (ES) is ….
• a computing system that does a specific task
inside a machine or larger electrical system.
(Cambridge Dictionary)
• a computer system that is embedded into a
larger electrical or mechanical system
performing specific dedicated tasks of that
larger system. (Prof. Peter Waszecki)
• a controller with a dedicated function within a
larger mechanical or electrical system, often
with real-time computing constraints. (Wikipedia)
• a combination of computer hardware and
software, either fixed in capability or
programmable, designed for a specific function
or functions within a larger system.
([Link])
• …
Analogue & Digital World
The human world is Embedded systems must
analogue and continuous, use a mix of analogue and
while the computer world digital electronics to
is digital and discrete. represent the corresponding
signals.
Properties of Embedded Systems
• …are an embedded or integral part of a device, often
including hardware and electromechanical parts.
• ...are dedicated to handle specific tasks that are known
and assigned to them at design-time.
• …use sensors and actuators to interact with the real
world.
• …have strict timing constraints due to their interaction
with the physical world in a safety-critical environment.
• …use limited resources (e.g. memory, processing
power, power, etc.) compared to general-purpose
computers.
• …are based on microcontrollers (i.e. CPUs with
integrated memory and/or peripheral interfaces).
Timing characteristics
Many embedded systems have real-time constraints…but what is real-time?
A real-time system is one in which the correctness of the
application depends on both their functional and temporal
results (the time at which the result is produced).
In other words, a late answer is a wrong answer.
Consequences of tasks missing their deadlines helps to classify real-time systems:
Non real-time constraints Soft real-time constraints Hard real-time constraints
▪ Tasks have no deadlines ▪ Tasks are allowed to miss deadlines ▪ It is imperative that tasks meets their
A late response usually does not occasionally deadlines at all times
significantly affect the performance and ▪ A late response can degrade the system ▪ A late response is not considered even if
functionality performance its value is correct
▪ A late response causes no danger ▪ A missed deadline causes no significant ▪ Missed deadline can have catastrophic
▪ E.g., TV remote control, lawn sprinkler, danger consequences
window lifter ▪ E.g., mobile phone, air-conditioning, ▪ E.g., nuclear reactor temperature, air-
refrigerator bag controller, flight control system
Different Embedded Systems Hardware Options
Microcontroller (µC) System on Chip (SoC) Application Specific Neural Processing
Integrated Chip (ASIC) Unit (NPU)
Microprocessor (µP) Digital Signal Field-Programmable Graphics Processing
Processor (DSP) Gate Array (FPGA) Unit (GPU)
Microprocessor Microcontroller
System on Chip (SoC)
Apple A16 Bionic
Other SoC
• Qualcomm - Snapdragon • Google - Tensor
• Samsung - Exynos • Broadcom - BCM series
• Huawei - Kirin (used in Raspberry Pi)
• MediaTek - Dimensity, Helio • Intel - Atom, Movidius
• Apple - A-series (e.g., A16 • AMD - Ryzen Embedded
Bionic), M-series (e.g., M1, • Rockchip - RK series
M2) • Unisoc - Tiger series
• NVIDIA - Tegra • Allwinner - A-series
Microcontroller SoC
Evolution of Computing
Edge-Fog-Cloud Architecture
Countless Billions Millions Thousands
Ref: Cao, Hung & Wachowicz, M. & Renso, Chiara & Carlini, Emanuele. (2019). Analytics Everywhere: Generating Insights From the Internet of Things. IEEE Access. 7. 71749-71769. 10.1109/ACCESS.2019.2919514.
Why embedded software must be done right
Embedded software is the "hidden brain" inside devices we use daily. It makes things work properly, from phones
and cars to medical equipment and airplanes. Its pervasive nature means that its quality directly impacts safety,
reliability, and business success.
Why It Matters: The Imperative for Excellence:
• Ubiquity (Everywhere) • Proactive Quality (Fix problems early)
• Found in almost every device • Don’t wait for errors to show up in real life. Test and catch
• (e.g., washing machines, smartwatches, cars). them during development.
• Mission-Critical (Life or Death) • Example: A phone bug can be patched later, but a bug in
• Controls critical systems an airbag system must be fixed before the car is sold.
• (e.g., pacemakers, airplane autopilots). • Rigorous Standards (Follow strict rules)
• Core Competency (Essential Skill) • Use proven methods, safety checks, and certifications to
• Companies rely on it for success ensure reliability.
• (e.g., Tesla’s car software is as essential as its engines). • Example: Airplane software follows aviation standards
• Unique Challenges (DO-178C) to guarantee safety before flights.
• Works with limited memory, power, and must run without crashing
• (e.g., a car airbag must always respond instantly).
One Software Mistake Is All It Takes
• Poorly designed software can severely damage a brand's
reputation and could lead to the company's collapse
[Link]
Ref: [Link]
Embedded Software: More Than Just Code
Embedded software development presents unique and
significant challenges that differentiate it from traditional
desktop or web application development. The tight integration Many embedded systems are mission-critical, performing
with hardware and stringent performance requirements demand functions where failure is unacceptable and can lead to:
a specialised approach.
• Safety Risks
• Significant Financial or Business Loss
Key Challenges:
• Resource Constraints
• Real-Time Requirements
• Hardware-Software Co-Design.
• Concurrency and Interrupts.
• Reliability and Safety.
• Debugging Difficulties.
The Deadly Race Condition: A Therac-25 Case Study
• The Bug:
• Race condition between UI and control software
• triggered by a specific sequence of rapid keystrokes
• causing lethal radiation overdoses instead of therapeutic doses.
• Reproduction Difficulty:
• A “Heisenbug” (disappeared when observed)
• debugger or logging altered timing, preventing the issue from manifesting.
• Took years and multiple deaths to identify the exact cause.
• High Cost of Failure:
• At least six lethal overdoses, deaths, and severe injuries.
• Multiple lawsuits, reputation damage, complete software redesign, and new safety protocols.
• Immense financial cost (recalls, legal fees, lost business) and immeasurable human cost.
[Link]
The Systemic Flaw:
Toyota's Spaghetti Code Issue
Toyota's car software is famously difficult to maintain and debug due to its unstructured design, a style
known as "spaghetti code“. This complexity posed a significant obstacle during investigations into unintended
acceleration incidents, making it challenging to pinpoint the source of the problem.
Complexity: Debugging Challenges: Safety Concerns:
The code was a monolithic, Engineers struggled to trace the flow of The entangled nature of the code
interconnected block without clear logic and identify the source of errors, created an environment where a
modularity, making it difficult to isolate leading to prolonged and costly small change in one area could have
and fix bugs. investigations. unintended and potentially
dangerous consequences in another.
[Link]
The Ariane 5's Fatal Integer Overflow
The specific line of code that failed was:
A classic and well-documented example of a single line of code
leading to catastrophic failure is the Ariane 5 rocket crash. B_H = (float) H_O / 65536.0;
The rocket, which was carrying a payload worth half a billion
dollars, was destroyed just 37 seconds into its maiden flight. The value of B_H was stored in a variable that was too small.
The root cause was a software bug in the onboard inertial This single line of code, which failed to perform a simple range
reference system. check, led to a chain of events:
1. The overflow caused a crucial variable to hold a
The "Bad Line" of Code: The software was written to handle a nonsensical value.
64-bit floating-point number representing the horizontal velocity 2. The flight control system interpreted this garbage data as
of the rocket and convert it to a 16-bit signed integer. The a severe error.
original code was reused from the Ariane 4 rocket, which had a 3. The system, believing it was in a critical fault state, shut
much slower flight profile. down the rocket's engines, causing it to veer off course
During the Ariane 5's ascent, the horizontal velocity value was and self-destruct.
larger than what a 16-bit integer could hold, resulting in an The cost of this one line of code was half a billion dollars and a
integer overflow. major setback for the European space program.
What is the SDLC?
STRUCTURED APPROACH TO ENSURES REPEATABILITY AND CRITICAL IN EMBEDDED SYSTEMS
SOFTWARE DEVELOPMENT QUALITY DUE TO SAFETY, TIMING, AND
RESOURCE CONSTRAINTS
Waterfall Development Cycle (MODEL)
REQUIREMENT Product
ANALYSIS Requirements
SYSTEM DESIGN Software
Requirements
ARCHITECTURE High Level
DESIGN Design
Detailed
MODULE DESIGN
Design
IMPLEMENTATION
Source
• Effective for well-understood domains Code
• Works best if you don’t make many big mistakes TESTING
Production
System
• Any problem encountered requires backtracking
DEPLOYMENT &
MAINTENANCE
Verification and Validation
Development Cycle (V-MODEL)
REQUIREMENT ACCEPTANCE
USER ACCEPTANCE TEST PLAN
ANALYSIS & RESULTS TESTING
PRODUCT ‘TECHNICAL’
REQUIREMENTS PRODUCT
SYSTEM DESIGN SYSTEM TEST PLAN SYSTEM TESTING
& RESULTS
SOFTWARE INTEGRATION
REQUIREMENTS TEST RESULT
ARCHITECTURE INTEGRATION
INTEGRATION TEST PLAN
DESIGN & RESULTS TESTING
HIGH LEVEL UNIT TEST
DESIGN RESULT
MODULE DESIGN UNIT TEST PLAN UNIT TESTING
& RESULTS
DETAILED SOURCE
• Emphasizes traceability DESIGN CODE
IMPLEMENTATION
Embedded vs General Software Engineering
Embedded General
Runs on resource-constrained microcontrollers or Runs on general-purpose computers with
SoCs abundant resources
Updates may require physical access or re-flashing Updates and patches can be deployed easily
devices
Tightly coupled with hardware; resources managed Abstracted from hardware; OS handles resource
manually (hw/sw co-design) management
Focus on timing constraints, power consumption, Focus on performance, scalability,
and reliability maintainability
Tools often specific to MCU vendor and hardware Wide choice of development tools and
environments
Testing often on target hardware under real Testing mainly in simulated or virtual
conditions (more complex) environments
Memory and processing limits
Embedded Timing and real-time deadlines
Constraints
Hardware coupling
(specific MCU/peripheral sets)
Environmental constraints
Limited debugging visibility
(no full OS-level tools).
etc…
Lessons from 50+ Years of SW DEV
Dividing up into
Bad architecture will doom a project.
subsystems is critical
Process formality is a Traceability, formal reviews, etc.
good investment Skipping steps costs more in the end.
Requirements change Suggests using an iterated approach.
Traceability from high to low levels.
Finding bugs early is
Layered testing.
important
Peer reviews most cost effective for this.
Mold Before the Gold: BUGS
Sniffing Out Bugs early
Design Peer Review
Majority of the bugs
should be caught here;
cheaper to resolve
Code Peer Review
Software Testing
The remaining bugs must be
swatted here; expensive to
resolve and might be too late.
Product Testing
or else…. SOFTWARE
FAILURES
Building an Embedded System Application
[Link]
Low-level languages for different ES H/W
• Low-level language
• good for squeezing the best performance from the underlying hardware
• compact and more optimised code FORTRAN C PASCAL
• High-level language required to improve: HIGH-LEVEL LANGUAGE
• Productivity ASSEMBLY LANGUAGE
• Code abstraction MACHINE LANGUAGE
HARDWARE
• Portable
• Only a machine understands low-level language
• need a compiler to translate the high-level language
Assembly vs Machine Code: [Link]
Assembly vs C
Assembly C
str fp, [sp, #-4]!
add fp, sp, #0
sub sp, sp, #12
int add() mov r3, #6
{ str r3, [fp, #-8]
mov r3, #6 int a = 6; ARM ldr r3, [fp, #-8]
add r3, r3, #5 a = 5 + a; GCC 8.2 add r3, r3, #5
return 0; str r3, [fp, #-8]
} mov r3, #0
mov r0, r3
add sp, fp, #0
ldr fp, [sp], #4
bx lr
C/Assembly Code into Binary File
C Library (.a) / C-SDK
compiler
C Files (.c) Object Files (.o)
Loader /
LINKER Locator
Reset Code (reset.s) Binary File Memory
(.bin)
assembler
Assembly Files (.s) Object Files (.o) Linker Script (.ld)
Startup Code (crt0.s)
Compiler / Assembler
• Compiler
• Translate programs written in human-readable language into an
equivalent set of opcode for a particular processor
• Cross compiling - compiling on a host for a target platform
• Native compiling - compiling for the same architecture you're running under
• Example: GCC, KEIL, IAR, CCS, etc.
• Assembler cross compiling
• One-to-one translation
• [Link]
C/Assembly Code into Binary File
C Library (.a) / C-SDK
compiler
C Files (.c) Object Files (.o)
Loader /
LINKER Locator
Reset Code (reset.s) Binary File Memory
(.bin)
assembler
Assembly Files (.s) Object Files (.o) Linker Script (.ld)
Startup Code (crt0.s)
Startup code
• A small block of assembly language code that prepares the way for the execution of
software written in a high-level language.
• Most cross-compilers for embedded systems include an assembly language file called
[Link] or crt0.s (short for C runtime).
• Typical startup code:
• Disable interrupt
• Copy data into RAM
• Zero uninitialized data area
• Allocate space and initialize the stack
• Create and initialize the heap
• Enable interrupt
• Call main
C/Assembly Code into Binary File
C Library (.a) / C-SDK
compiler
C Files (.c) Object Files (.o)
Loader /
LINKER Locator
Reset Code (reset.s) Binary File Memory
(.bin)
assembler
Assembly Files (.s) Object Files (.o) Linker Script (.ld)
Startup Code (crt0.s)
Linker
• takes one or more object files generated by a compiler/assembler
and combines them into a single executable file.
• cross-file dependencies are resolved properly, e.g. if you define a variable/function
in one .c file, and use it in another .c file, the linker connects the two together.
• link `reuse’ library files; static and dynamic
• every link is controlled by a linker script, that describes how the executable are mapped
onto the memory during execution.
Prof, Explain It to Me in Plain English
C SDK Compiler Bootloader
The C SDK (Software Development Kit) for The compiler is a tool that translates the user's The bootloader is a small program pre-installed
the Raspberry Pi Pico provides a collection C source code into machine code (binary) that on the Raspberry Pi Pico. It is responsible for
of libraries, functions, and tools that simplify the Raspberry Pi Pico can understand. The loading the compiled binary into the
hardware interaction. It abstracts the low- compiler processes the source code, linking it microcontroller's flash memory and executing it.
level details of the microcontroller, allowing with the necessary libraries from the C SDK, When the Raspberry Pi Pico is powered on or
the user to focus on writing high-level and generates an executable binary file. This reset, the bootloader checks for the presence of
application code. The SDK offers pre-written binary file is typically in the form of a .uf2 or .bin a new binary file (e.g., via USB) and writes it to
code to manage peripherals, such as GPIO, file. flash memory if found. If no new binary is
PWM, UART, and others. detected, it simply runs the existing program
Similar Terms: stored in flash.
• Application Programming Interface (API) SOURCE
• Development Framework, e.g. Arduino CODE
• Board Support Package (BSP)
BOOTLOADER/
• Toolkit / Toolchain COMPILER .UF2
DEBUGGER
• Middleware
• Library
C SDK