42,22 €
Explore various constraints and challenges that embedded developers encounter in their daily tasks and learn how to build effective programs using the latest standards of C++
Key Features
Book Description
Developing applications for embedded systems may seem like a daunting task as developers face challenges related to limited memory, high power consumption, and maintaining real-time responses. This book is a collection of practical examples to explain how to develop applications for embedded boards and overcome the challenges that you may encounter while developing.
The book will start with an introduction to embedded systems and how to set up the development environment. By teaching you to build your first embedded application, the book will help you progress from the basics to more complex concepts, such as debugging, logging, and profiling. Moving ahead, you will learn how to use specialized memory and custom allocators. From here, you will delve into recipes that will teach you how to work with the C++ memory model, atomic variables, and synchronization. The book will then take you through recipes on inter-process communication, data serialization, and timers. Finally, you will cover topics such as error handling and guidelines for real-time systems and safety-critical systems.
By the end of this book, you will have become proficient in building robust and secure embedded applications with C++.
What you will learn
Who this book is for
This book is for developers, electronic hardware professionals, and software and system-on-chip engineers who want to build effective embedded programs in C++. Familiarity with the C++ programming language is expected, but no previous knowledge of embedded systems is required.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 406
Veröffentlichungsjahr: 2020
Copyright © 2020 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Richa TripathiAcquisition Editor:Vincy DavisContent Development Editor:Pathikrit RoySenior Editor: Storm MannTechnical Editor:Pradeep SahuCopy Editor: Safis EditingProject Coordinator:Francy PuthiryProofreader: Safis EditingIndexer:Pratik ShirodkarProduction Designer: Jyoti Chauhan
First published: April 2020
Production reference: 1160420
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-83882-104-3
www.packt.com
Packt.com
Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Fully searchable for easy access to vital information
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Igor Viarheichyk works as an engineering manager at Samsung, developing a safety-critical middleware platform for advanced driver assistance systems aimed at specialized automotive embedded platforms. Prior to joining Samsung, in the past 20 years of his career, he has played different roles, from software engineer to software architect, to engineering manager in a variety of projects, and he has gained vast experience in the areas of system programming, embedded programming, network protocols, distributed and fault-tolerant systems, and software internationalization. Though he knows and actively uses programming languages such as C, Java, and Python, C++ is his language of choice to implement large-scale, high-performance applications.
Antonino Calderone has worked in the computer software industry for over 20 years as a software engineer in various domains, including telecommunications and networks, embedded systems, cybersecurity, machine learning algorithms, and DBMS. He has worked for companies such as Ericsson, Intel, and McAfee. He has also been a security architect, technical writer, and teacher in programming courses in C++ and design patterns. Antonino is an author and maintainer of several open source projects, including mipOS, an RTOS for SoC microcontrollers, and nuBASIC, a language designed for educational purposes. He was also a contributor to the magazine Computer Programming, one of the most well-known programming magazines in Italy in the 90s and 2000s.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Embedded Programming with Modern C++ Cookbook
Dedication
About Packt
Why subscribe?
Contributors
About the author
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Sections
Getting ready
How to do it…
How it works…
There's more…
See also
Get in touch
Reviews
Fundamentals of Embedded Systems
Exploring embedded systems
How are they different from desktop or web applications?
Types of embedded systems
Microcontrollers
System on Chip
Application-specific integrated circuits
Field programmable gate arrays
Working with limited resources
Looking at performance implications
Working with different architectures
Endianness
Alignment
Fixed-width integer types
Working with hardware errors
Early versions of hardware
Hardware is unreliable
The influence of environmental conditions
Using C++ for embedded development
You don't pay for what you don't use
Object-oriented programming to time the code complexity
Resource acquisition is initialization
Exceptions
The powerful standard library
Threads and a memory model as part of the language specification
Deploying software remotely
Running software remotely
Logging and diagnostics
Summary
Setting Up the Environment
Setting up the build system in a Docker container
How to do it...
How it works...
There's more...
Working with emulators
How to do it...
How it works...
There's more...
Cross-compilation
Getting ready
How to do it...
How it works...
There's more...
Connecting to the embedded system
Getting ready
How to do it...
How it works...
There's more...
Debugging embedded applications
Getting ready
How to do it...
How it works...
There's more...
Using gdbserver for remote debugging
Getting ready
How to do it...
How it works...
There's more...
Using CMake as a build system
Getting ready
How to do it...
How it works...
There's more...
Working with Different Architectures
Exploring fixed-width integer types
How to do it...
How it works...
There's more...
Working with the size_t type
How to do it...
How it works...
There's more...
Detecting the endianness of the platform
How to do it...
How it works...
There's more...
Converting the endianness
How to do it...
How it works...
Working with data alignment
How to do it...
How it works...
There's more... 
Working with packed structures
How to do it...
How it works...
There's more...
Aligning data with cache lines
How to do it...
How it works...
There's more...
Handling Interrupts
Data polling
Interrupt service routines
General considerations for ISRs
8051 microcontroller interrupts
Implementing an interrupt service routine
How to do it...
How it works...
Generating a 5 kHz square signal using 8-bit auto-reload mode
How to do it...
How it works...
Using Timer 1 as an event counter to count a 1 Hz pulse
How to do it...
How it works...
There's more...
Receiving and transmitting data serially
How to do it...
How it works...
There's more...
Debugging, Logging, and Profiling
Technical requirements
Running your applications in the GDB
How to do it...
How it works...
There's more...
Working with breakpoints
How to do it...
How it works...
There's more...
Working with core dumps
How to do it...
How it works...
There's more...
Using gdbserver for debugging
Getting ready...
How to do it...
How it works...
Adding debug logging
How to do it...
How it works...
There's more...
Working with debug and release builds
How to do it...
How it works...
There's more...
Memory Management
Using dynamic memory allocation
How to do it...
How it works...
Exploring object pools
How to do it...
How it works...
There's more...
Using ring buffers
How to do it...
How it works...
Using shared memory
How to do it...
How it works...
There's more...
Using specialized memory
How to do it...
How it works...
There's more...
Multithreading and Synchronization
Exploring thread support in C++
How to do it...
How it works...
Exploring data synchronization
How to do it...
How it works...
There's more...
Using condition variables
How to do it...
How it works...
There's more...
Using atomic variables
How to do it...
How it works...
There's more...
Using the C++ memory model
How to do it...
How it works...
There's more...
Exploring lock-free synchronization
How to do it...
How it works...
There's more...
Using atomic variables in shared memory
How to do it...
How it works...
Exploring async functions and futures
How to do it...
How it works...
There's more...
Communication and Serialization
Using inter-process communication in applications
How to do it...
How it works...
There's more...
Exploring the mechanisms of inter-process communication
Getting ready
How to do it...
How it works...
There's more...
Learning about message queue and publisher-subscriber models
How to do it...
How it works...
There's more...
Using C++ lambdas for callbacks
How to do it...
How it works...
There's more...
Exploring data serialization
How to do it...
How it works...
There's more...
Using the FlatBuffers library
How to do it...
How it works...
There's more...
Peripherals
Controlling devices connected via GPIO
How to do it...
How it works...
Exploring pulse-width modulation
How to do it...
How it works...
There's more...
Using ioctl to access a real-time clock in Linux
How to do it...
How it works...
There's more
Using libgpiod to control GPIO pins
How to do it...
How it works...
There's more...
Controlling I2C peripheral devices
How to do it...
How it works...
There's more...
Reducing Power Consumption
Technical requirements
Exploring power-saving modes in Linux
How to do it...
How it works...
There's more...
Waking up using RTC
How to do it...
How it works...
There's more...
Controlling the autosuspend of USB devices
How to do it...
How it works...
There's more...
Configuring CPU frequency
How to do it...
How it works...
There's more...
Using events for waiting
How to do it...
How it works...
There's more...
Profiling power consumption with PowerTOP
How to do it...
How it works...
There's more...
Time Points and Intervals
Exploring the C++ Chrono library
How to do it...
How it works...
There's more...
Measuring time intervals
How to do it...
How it works...
There's more...
Working with delays
How to do it...
How it works...
There's more...
Using the monotonic clock
How to do it...
How it works...
There's more...
Using POSIX timestamps
How to do it...
How it works...
There's more...
Error Handling and Fault Tolerance
Working with error codes
How to do it...
How it works...
There's more...
Using exceptions for error handling
How to do it...
How it works...
There's more...
Using constant references when catching exceptions
How to do it...
How it works...
There's more...
Tackling static objects
How to do it...
How it works...
Working with watchdogs
How to do it...
How it works...
Exploring heartbeats for highly available systems
How to do it...
How it works...
There's more...
Implementing software debouncing logic
How to do it...
How it works...
Guidelines for Real-Time Systems
Using real-time schedulers in Linux
How to do it...
How it works...
Using statically allocated memory
How to do it...
How it works...
There's more...
Avoiding exceptions for error handling
How to do it...
How it works...
There's more...
Exploring real-time operating systems
How to do it...
How it works...
There's more...
Guidelines for Safety-Critical Systems
Using the return values of all functions
How to do it...
How it works...
There's more...
Using static code analyzers
How to do it...
How it works...
There's more...
Using preconditions and postconditions
How to do it...
How it works...
There's more...
Exploring the formal validation of code correctness
How to do it...
How it works...
There's more...
Microcontroller Programming
Setting up the development environment
How to do it...
How it works...
There's more...
Compiling and uploading a program
How to do it...
How it works...
There's more...
Debugging microcontroller code
How to do it...
How it works...
Other Books You May Enjoy
Leave a review - let other readers know what you think
For a long time, development for embedded systems required either plain C or assembly language. There was a host of good reasons for this. The hardware did not have enough resources to run applications written in higher-level programming languages, such as C++, Java, or Python, but more importantly, there was no real need to write software in these languages. Limited hardware resources put a limit on software complexity, the functionality of embedded applications remained relatively simple, and the capabilities of C were sufficient to implement it.
As a result of the progress in hardware development, more and more embedded systems nowadays are powered by inexpensive yet powerful System-on-Chip capable of running a general-purpose multitasking operating system such as Linux.
Growing hardware capabilities demand more complex software, and more and more often C++ becomes the language of choice for new embedded systems. With its you don't pay for what you don't use approach it allows developers to create applications that use computational and memory resources, like applications written in C, but gives developers many more tools for dealing with complexity and safer resource management, such as object-oriented programming and the RAII idiom.
Seasoned embedded developers with substantial experience in C often tend to write code in C++ in a similar, habitual way, considering this language just as an object-oriented extension of C, a C with classes. Modern C++, however, has its own best practices and concepts that, properly used, help developers avoid common pitfalls and allow them to do a lot in a few lines of code.
On the other side, developers with C++ experience entering the world of embedded systems should be aware of the requirements, limitations, and capabilities of specific hardware platforms and application domains and design their C++ code accordingly.
The goal of this book is to bridge this gap and demonstrate how features and best practices of modern C++ can be applied in the context of embedded systems.
This book is for developers and electronic hardware, software, and system-on-chip engineers who want to build effective embedded programs in C++.
The world of embedded systems is vast. This book tries to cover one type of them, the SoCs running Linux OS, such as Raspberry Pi or BeagleBoard, briefly touching low-level microcontrollers such as Arduino.
Familiarity with C++ is expected, but no deep knowledge of C++ or experience with embedded systems is required.
Chapter 1, Fundamentals of Embedded Systems, defines what embedded systems are, how they are different from other systems, why specific programming techniques are needed, and why C++ is good and in many cases the best choice for embedded development. It outlines the constraints and challenges that embedded developers encounter in their everyday work: limited system resources and CPU performance, dealing with hardware errors, and remote debugging.
Chapter 2, Setting Up the Environment, explains the differences in a development environment for embedded systems compared to web or desktop application development and goes through concepts of the build and target system, cross-compilation and cross-toolkits, the serial console, and the remote shell. It provides practical steps for setting up virtualized build and target hosts for the most common desktop configurations running Windows, macOS, or Linux.
Chapter 3, Working with Different Architectures, explains how to take into account important differences in CPU architectures and memory configuration of target systems in your C++ code.
Chapter 4, Handling Interrupts, covers the low-level concepts of interrupts and interrupt service routines. In modern OSes, even developers or device drivers have to use a higher-level API provided by the OS. That is why we explore the interrupt techniques using the 8051 microcontroller.
Chapter 5, Debugging, Logging, and Profiling, covers debugging techniques specific to Linux-based embedded systems, such as running gdb directly on the target board, setting up gdbserver for remote debugging, and the importance of logging for debugging and failure root cause analysis.
Chapter 6, Memory Management, provides several recipes and best practices of memory allocation that will be helpful for developers of embedded systems. We discuss why dynamic memory allocation is avoided in embedded applications and what alternatives can be considered for fast, deterministic memory allocation.
Chapter 7, Multithreading and Synchronization, explains how to use the functions and classes provided by the standard library of C++ to implement efficient multithreading applications that can utilize all the power of the modern multicore CPUs.
Chapter 8, Communication and Serialization, covers the concepts, challenges, and best practices for inter-process and inter-system communications, such as sockets, pipes, shared memory, and memory-efficient serialization using the FlatBuffers library. Decoupling applications into independent components that talk to each other using well-defined asynchronous protocols is a de facto standard way of scaling a software system while keeping it fast and fault-tolerant.
Chapter 9, Peripherals, explains how to work with various peripheral devices in C++ programs. Though most device communication APIs do not depend on a particular programming language, we will learn how to use the power of C++ to write wrappers that are convenient for developers and help prevent common resource leaking errors.
Chapter 10, Reducing Power Consumption, explores the best practices for writing energy-efficient applications and utilizing the power management functions of the OS. It provides several practical recipes for Linux-based embedded systems, but the same concepts can be expanded to any OS and any platform.
Chapter 11, Time Points and Intervals, covers various topics related to time manipulations, from measuring intervals to adding delays. We will learn about the API provided by the standard C++ Chrono library and how it can be used efficiently to build portable embedded applications.
Chapter 12, Error Handling and Fault Tolerance, explores possible implementations and best practices of error handling for embedded applications written in C++. It explains how to use C++ exceptions efficiently and compares it to alternatives such as traditional error codes and complex return types. It touches on basic fault-tolerance mechanisms such as watchdog timers and heartbeats.
Chapter 13, Guidelines for Real-Time Systems, covers the specifics of real-time systems. It briefly describes how real-time systems are defined and what kinds of real-time systems exist. It contains practical recipes on how to make the behavior of applications more deterministic, a crucial requirement for real-time systems.
Chapter 14, Guidelines for Safety-Critical Systems, explains what safety-critical systems are and how they are different from other embedded systems. It covers development methodologies and tools that are required when working on safety-critical systems, from following formalized coding guidelines such as MISRA, AUTOSAR, or JSF to using static code analysis or formal software validation tools.
Chapter 15, Microcontroller Programming, outlines basic concepts of writing, compiling, and debugging C++ code for microcontrollers. We will learn how to set up the development environment using the widely used Arduino board as an example.
Development for embedded systems implies that your applications will interact with some sort of specialized hardware—a specific SoC platform, a specific microcontroller, or a specific peripheral device. There is a huge variety of possible hardware configurations, along with specialized OSes or IDEs that are needed to work with those hardware setups.
The goal of this book is to let everyone start learning about programming for embedded systems without investing too much in hardware. That is why most of the recipes are aimed at working in a virtualized Linux environment or an emulator. Some of the recipes, however, may require physical hardware. These recipes were designed to be run on either a Raspberry Pi or an Arduino, the two most widely used and inexpensive platforms that can be obtained relatively easily.
Software/Hardware covered in the book
OS requirements
Docker (
https://www.docker.com/products/docker-desktop
)
Microsoft Windows 10 Professional or Enterprise 64-bit
macOS 10.13 or newer
Ubuntu Linux 16.04 or newer
Debian Linux Stretch (9) or Buster (10)
Fedora Linux 30 or newer
QEMU (
https://www.qemu.org/download/
)
Windows 8 or newer (32-bit or 64-bit)
macOS 10.7 or newer
Linux (various distributions)
Raspberry Pi 3 Model B+
Arduino UNO R3 or ELEGOO UNO R3
If you are using the digital version of this book, we advise you to type the code yourself or access the code via the GitHub repository (link available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packt.com
.
Select the
Support
tab.
Click on
Code Downloads
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Embedded-Programming-with-Modern-CPP-Cookbook. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781838821043_ColorImages.pdf.
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Run the hello application under gdbserver."
A block of code is set as follows:
#include <iostream>int main() { std::cout << "Hello, world!" << std::endl; return 0;}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
#include <iostream>int main() { std::cout << "Hello, world!" << std::endl;
return 0;
}
Any command-line input or output is written as follows:
$ docker run -ti -v $HOME/test:/mnt ubuntu:bionic
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "The best way to configure cross-compilation for CMake is by using the so-called toolchain files"
In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There's more..., and See also).
To give clear instructions on how to complete a recipe, use these sections as follows:
This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
Embedded systems are computer systems that combine hardware and software components to solve a specific task within a larger system or device. Unlike general-purpose computers, they are heavily specialized and optimized to perform only one task but do it really well.
They are everywhere around us, but we rarely notice them. You can find them in virtually every home appliance or gadget, such as a microwave oven, TV set, network-attached storage, or smart thermostat. Your car contains several interconnected embedded systems that handle brakes, fuel injection, and infotainment.
In this chapter, we are going to deal with the following topics on embedded systems:
Exploring embedded systems
Working with limited resources
Looking at performance implications
Working with different architectures
Working with hardware errors
Using C++ for embedded development
Deploying software remotely
Running software remotely
Logging and diagnostics
Every computer system created to solve a particular problem as part of a larger system or device is an embedded system. Even your general-purpose PC or laptop contains many embedded systems. A keyboard, a hard drive, a network card, or a Wi-Fi module—each of these is an embedded system with a processor, often called a microcontroller, and its own software, often called firmware.
Let's now dive into the different features of an embedded system.
The most distinctive feature of embedded systems compared to desktops or servers is their tight coupling of hardware and software specialized to accomplish a particular task.
Embedded devices work in a wide range of physical and environmental conditions. Most of them are not designed to work only in dedicated conditioned data centers or offices. They have to be functional in uncontrollable environments, often without any supervision and maintenance.
Since they are specialized, hardware requirements are precisely calculated to accomplish the task of being as cost-efficient as possible. As a result, the software aims to utilize 100% of the available resources with minimal or no reserves.
The hardware of embedded systems is much more differentiated compared to regular desktops and servers. The design of each system is individual. They may require very specific CPUs and schematics that connect them to memory and peripheral hardware.
Embedded systems are designed to communicate with peripheral hardware. A major part of an embedded program is checking the status, reading input, sending data, or controlling the external device. It is common for an embedded system to not have a user interface. This makes development, debugging, and diagnostics much more difficult compared to doing the same on traditional desktop or web applications.
Embedded systems span a wide range of use cases and technologies—from powerful systems used for autonomous driving or large-scale storage systems to tiny microcontrollers used to control light bulbs or LED displays.
Based on the level of integration and specialization of hardware, embedded systems can roughly be divided into the following categories:
Microcontrollers
(
MCUs
)
A
System on Chip
(
SoC
)
Application-Specific Integrated Circuits
(
ASICs
)
Field Programmable Gate Arrays
(
FPGAs
)
MCUs are general-purpose integrated circuits designed for embedded applications. A single MCU chip typically contains one or more CPUs, memory, and programmable input/output peripherals. Their design allows them to interface directly with sensors or actuators without adding any additional components.
MCUs are widely used in automobile engine control systems, medical devices, remote controls, office machines, appliances, power tools, and toys.
Their CPUs vary from simple 8-bit processors to the more complex 32-bit and even 64-bit processors.
Lots of MCUs exist; the most common ones nowadays are the following:
The Intel MCS-51 or 8051 MCU.
AVR by Atmel
The
Programmable Interface Controller
(
PIC
) from Microchip Technology
Various ARM-based MCUs
An SoC is an integrated circuit that combines all the electronic circuits and parts needed to solve a particular class of problem on a single chip.
It may contain digital, analog, or mixed-signal functions, depending on the application. The integration of most electronic parts in a single chip gives two major benefits: miniaturization and low power consumption. Compared to a less-integrated hardware design, an SoC requires significantly less power. The optimization of power consumption on the hardware and software levels allows it to create systems that can work for days, months, and even years on a battery without an external power source. Often, it also integrates radio frequency signal processing, which, along with its compact physical size, makes it an ideal solution for mobile applications. Besides that, SoCs are commonly used in the automotive industry, in wearable electronics, and in the Internet of Things (IoT):
A Raspberry Pi family of single-board computers is an example of a system based on the SoC design. Model B+ is built on top of a Broadcom BCM2837B0 SoC with an integrated quad-core 1.4 Hz ARM-based CPU, 1 GB memory, a network interface controller, and four Ethernet interfaces.
The board has four USB interfaces, a MicroSD card port to boot an operating system and store data, Ethernet and Wi-Fi network interfaces, HDMI video output, and a 40-pin GPIO header to connect custom peripheral hardware.
It is shipped with the Linux operating system and is an excellent choice for educational and DIY projects.
Application-specific integrated circuits, or ASICs, are integrated circuits customized by their manufactures for a particular use. The customization is an expensive process but allows them to meet the requirements that are often infeasible for solutions based on general-purpose hardware. For example, modern high-efficiency Bitcoin miners are usually built on top of specialized ASIC chips.
To define the functionality of ASICs, hardware designers use one of the hardware description languages, such as Verilog or VHDL.
Unlike SoCs, ASICs, and MCUs, field programmable gate arrays, or FPGAs, are semiconductor devices that can be reprogrammed on a hardware level after manufacturing. They are based around a matrix of configurable logic blocks (CLBs), which are connected via programmable interconnects. The interconnects can be programmed by developers to perform a specific function according to their requirements. The FPGA is programmed with aHardware Definition Language (HDL). It allows the implementation of any combination of digital functions in order to process a massive amount of data very quickly and efficiently.
It is a common misconception that embedded systems are based on hardware that is much slower compared to regular desktop or server hardware. Although this is commonly the case, it is not always true.
Some particular applications may require lots of computation power of large amounts of memory. For example, autonomous driving requires both memory and CPU resources to handle the large amount of data that comes from various sensors using AI algorithms in real time. Another example is high-end storage systems that utilize large amounts of memory and resources for data caching, replication, and encryption.
In either case, the embedded system hardware is designed to minimize the cost of the overall system. The results for software engineers working with embedded systems is that resources are scarce. They are expected to utilize all of the available resources and take performance and memory optimizations very seriously.
Most embedded applications are optimized for performance. As discussed earlier, the target CPU is chosen to be cost-efficient and developers extract all the computation power that it is capable of. An additional factor is communication with peripheral hardware. This often requires precise and fast reaction times. As a result, there is only limited room for the scripting, interpretable, bytecode languages such as Python or Java. Most of the embedded programs are written in languages that compile into the native code, primarily C and C++.
To achieve maximum performance, embedded programs utilize all the performance optimization capabilities of compilers. Modern compilers are so good at code optimization that they can outperform code in assembly language written by skilled developers.
However, engineers cannot rely solely on the performance optimizations provided by compilers. To achieve maximum efficiency, they have to take into account the specifics of the target platform. Coding practices that are commonly used for desktop or server applications running on an x86 platform may be inefficient for different architectures such as ARM or MIPS. The utilization of specific features of the target architecture often gives a significant performance boost to the program.
Developers of desktop applications usually pay little attention to the hardware architecture. First, they often use high-level programming languages that hide these complexities at the cost of some performance drop. Second, in most cases, their code runs on x86 architecture and they often take its features for granted. For example, they may assume that the size of int is 32 bits, which is not true in many cases.
Embedded developers deal with a much wider variety of architectures. Even if they do not write code in assembly language native to the target platform, they should be aware that all C andC++ fundamental typesare architecture-dependent; the standard only guarantees that int is at least 16bits. They should also know the traits of particular architectures, such as endianness and alignment, and take into account that operations with floating point or 64-bit numbers, which are relatively cheap on x86 architecture, may be much more expensive on other architectures.
C and C++ developers often forget that the size of fundamental data types, such as char, short, or int, is architecture-dependent. To make the code portable, embedded developers often use fixed-size integer types that explicitly specify the size of a data field.
The most commonly used data types are as follows:
Width
Signed
Unsigned
8-bit
int8_t
uint8_t
16-bit
int16_t
uint16_t
32-bit
int32_t
uint32_t
The pointer size also depends on the architecture. Developers often need to address elements of arrays and since arrays are internally represented as pointers, the offset representation depends on the pointer size. size_t is a special data type to represent the offset and data sizes in an architecture-independent way.
A significant part of an embedded developer's work is dealing with hardware. Unlike most application developers, embedded developers cannot rely on hardware. Hardware fails for different reasons and embedded developers have to distinguish purely software failures from software failures caused by hardware failures or glitches.
Embedded systems are based on specialized hardware designed and manufactured for a particular use case. This implies that at the time that the software for the embedded system is being developed, its hardware is not yet stable and well tested. When software developers encounter an error in their code behavior, it does not necessarily mean there is a software bug but it might be a result of incorrectly working hardware.
It is hard to triage these kinds of problems. They require knowledge, intuition, and sometimes the use of an oscilloscope to narrow the root cause of an issue down to hardware.
Hardware is inherently unreliable. Each hardware component has a probability of failure and developers should be aware that hardware can fail at any time. Data stored in memory can be corrupted because of memory failure. Messages being transmitted over a communication channel can be altered because of external noise.
Embedded developers are prepared for these situations. They use checksums or cyclic redundancy check (CRC) code to detect and, if possible, correct corrupted data.
High temperature, low temperature, high humidity, vibration, dust, and other environmental factors can significantly affect the performance and reliability of hardware. While developers design their software to handle all potential hardware errors, it is common practice to test the system in different environments. Besides that, knowledge of environmental conditions can give an important clue when working on the root-cause analysis of an issue.
For many years, the vast majority of an embedded project was developed using the C programming language. This language perfectly fits the needs of embedded software developers. It provides feature-rich and convenient syntax but at the same time, it is relatively low-level and does not hide platform specifics from developers.
Due to its versatility, compactness, and the high performance of the compiled code, it became a de facto standard development language in the embedded world. Compilers for the C language exist for most, if not all, architectures; they are optimized to generate machine code that is more efficient than those that are written manually.
Over time, the complexity of embedded systems increased and developers faced the limitations of C, the most notable being error-prone resource management and a lack of high-level abstractions. The development of complex applications in C requires a lot of effort and time.
At the same time, C++ was evolving, gaining new features and adopting programming techniques that make it the best choice for developers of modern embedded systems. These new features and techniques are as follows:
You don't pay for what you don't use.
Object-oriented programming to time the code complexity.
Resource acquisition is initialization
(
RAII
).
Exceptions.
A powerful standard library.
Threads and memory model as part of the language specification.
As the complexity of embedded programs grows over time, it becomes more and more difficult to manage them using the traditional procedural approach provided by the C language. If you take a look at a large C project, such as the Linux kernel, you will see that it adopts many aspects of object-oriented programming.
The Linux kernel extensively uses encapsulation, hiding implementation details and providing object interfaces using C structures.
Though it is possible to write object-oriented code in C, it is much easier and convenient to do it in C++, where a compiler does all the heavy lifting for the developers.
