ARCHITECTURE AND PROGRAMMING OF EMBEDDED SYSTEMS

Jeevanandhams14 356 views 170 slides Aug 28, 2025
Slide 1
Slide 1 of 170
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138
Slide 139
139
Slide 140
140
Slide 141
141
Slide 142
142
Slide 143
143
Slide 144
144
Slide 145
145
Slide 146
146
Slide 147
147
Slide 148
148
Slide 149
149
Slide 150
150
Slide 151
151
Slide 152
152
Slide 153
153
Slide 154
154
Slide 155
155
Slide 156
156
Slide 157
157
Slide 158
158
Slide 159
159
Slide 160
160
Slide 161
161
Slide 162
162
Slide 163
163
Slide 164
164
Slide 165
165
Slide 166
166
Slide 167
167
Slide 168
168
Slide 169
169
Slide 170
170

About This Presentation

ARCHITECTURE AND PROGRAMMING OF EMBEDDED SYSTEMS 12
Overview of Embedded systems – Definitions and Constraints– Design challenge – Embedded processor
technology – Embedded Program – Role of Infinite loop – Compiling, Linking and locating
–downloading and debugging – Emulators and sim...


Slide Content

PRESENTATION BY Mr.S.Jeevanandham , Assistant Professor( Sr.Gr )/IT SRI RAMAKRISHNA ENGINEERING COLLEGE [Educational Service : SNR Sons Charitable Trust] [Autonomous Institution, Reaccredited by NAAC with ‘A+’ Grade] [Approved by AICTE and Permanently Affiliated to Anna University, Chennai] [ISO 9001:2015 Certified and all Eligible Programmes Accredited by NBA] VATTAMALAIPALAYAM, N.G.G.O. COLONY POST, COIMBATORE – 641 022. 20EC211 – EMBEDDED SYSTEMS AND INTERNET OF THINGS Department of Information Technology Semester : 05 Year : III Academic Year : 2025-2026

14-08-2025 20IT214 – INFORMATION SECURITY – S.JEEVANANDHAM, AP/IT 2 Module I : ARCHITECTURE AND PROGRAMMING OF EMBEDDED SYSTEMS 12 Overview of Embedded systems – Definitions and Constraints– Design challenge – Embedded processor technology – Embedded Program – Role of Infinite loop – Compiling, Linking and locating –downloading and debugging – Emulators and simulators processor – External peripherals – Memory testing – Programming of Flash Memory – Guidelines for the use of the C language in critical systems based on secure coding standard MISRA. 20EC211 – EMBEDDED SYSTEMS AND INTERNET OF THINGS

14-08-2025 20IT214 – INFORMATION SECURITY – S.JEEVANANDHAM, AP/IT 3 Module II : EMBEDDED LINUX 12 Introduction – Advantages– Embedded Linux Distributions – Architecture of Embedded Linux – Linux kernel architecture – User space – Linux startup sequence – GNU cross platform Tool chain – Device Driver: Introduction and Types – Tracing and Profiling tools. 20EC211 – EMBEDDED SYSTEMS AND INTERNET OF THINGS

4 Audience Q&A The Slido app must be installed on every computer you’re presenting from Do not edit How to change the design

14-08-2025 20IT214 – INFORMATION SECURITY – S.JEEVANANDHAM, AP/IT 5 Module III : REAL TIME SYSTEMS 12 Foreground/Background Systems – Context Switching – Non-Preemptive Kernel, Preemptive Kernel – Scheduler – Scheduling Reentrancy – Priority Inversion – Assigning Task Priorities – Priority Inheritance – Mutual Exclusion – Semaphores – Deadlock – Synchronization – Event Flags – Inter Task Communications – Message Mailboxes – Message Queues – Interrupts – Clock Tick – Memory Requirements. 20EC211 – EMBEDDED SYSTEMS AND INTERNET OF THINGS

14-08-2025 20IT214 – INFORMATION SECURITY – S.JEEVANANDHAM, AP/IT 6 Module IV : INTERNET OF THINGS 11 Introduction to IOT, Physical Design of IOT, Logical Design of IOT, IOT Enabling Technologies–IOT and M2M– Essential Characteristics of Cloud Computing – Service Models – Deployment Models. Case Study: Air Quality Monitoring System and Data Logger–Landslide Detection and Disaster Management–Smart Motion Detector. 20EC211 – EMBEDDED SYSTEMS AND INTERNET OF THINGS

Course Outcome 14-08-2025 20IT214 – INFORMATION SECURITY – S.JEEVANANDHAM, AP/IT 7 CO1: Explain the hardware architecture of embedded systems and building and debugging tools for embedded software. PO1 CO2: Summarize the strategies to test embedded memories and MISRA secure coding standards. PO1, PO12 CO3: Interpret the concepts and architecture of Embedded Linux. PO1, PO5, PO12 CO4: Explain real time embedded systems using the concepts of RTOS. PO1, PO3, PO12 CO5: Describe the concepts of Internet of Things and cloud computing. PO1, PO12 CO6: Develop an IoT system for real time applications. PO1, PO10, PO11, PO12

Module 1: FUNDAMENTALS OF EMBEDDED SYSTEMS

Definition System: A group of interdependent items that interact regularly to perform a task An established or organized procedure A set of detailed methods, procedures and routines created to carry out a specific activity, perform a duty, or solve a problem A way of working, organizing or performing one or many tasks according to a fixed set of rules, program or plan A computer system refers to the hardware and software components that run a computer or computers An information system is a system that collects and stores data * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 9

Embedded Systems An embedded system is one kind of a computer system mainly designed to perform several tasks like to access, process, store and also control the data in various electronics-based systems Embedded systems are a combination of hardware and software where software is usually known as firmware that is embedded into the hardware One of its most important characteristics of these systems is, it gives the o/p within the time limits Embedded systems support to make the work more perfect and convenient So, we frequently use embedded systems in simple and complex devices too The applications of embedded systems mainly involve in our real life for several devices like microwave, calculators, TV remote control, home security and neighbourhood traffic control systems, etc * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 10

Embedded Systems To simply say that an Embedded System is an integrated system including both hardware and software is not enough. An embedded system is a dedicated computer system, designed to work for single or few specific functions often within a larger system. Embedded Systems, therefore, are Built to function with little or no human intervention Specially designed keeping in consideration the tasks that need completion in the most efficient way These systems are different from the general-purpose computers (desktops and laptops) – the general-purpose computer can handle a wide range of processing tasks unlike embedded systems. * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 11

FIRMWARE Simply saying an embedded system is example of firmware. Why? * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 12 SOFTWARE PROGRAM #include <16f876a.h> #use delay (clock=20000000) #byte PORTB=6 main() { set_tris_b(0); portb=255; //decimal

Characteristics All Embedded Systems are task specific. They do the same task repeatedly /continuously over their lifetime. An mp3 player will function only as an mp3 player. Embedded systems are created to perform the task within a certain time frame. It must therefore perform fast enough. A car’s brake system, if exceeds the time limit, may cause accidents. They have minimal or no user interface (UI). A fully automatic washing machine works on its own after the programme is set and stops once the task is over. Some embedded systems are designed to react to external stimuli and react accordingly. A thermometer, a GPS tracking device. Embedded systems are built to achieve certain efficiency levels. They are small sized, can work with less power and are not too expensive. Embedded systems cannot be changed or upgraded by the users. Hence, they must rank high on reliability and stability. They are expected to function for long durations without the user experiencing any difficulties. * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 13

Characteristic Microcontroller or microprocessors are used to design embedded systems. Embedded systems need connected peripherals to attach input & output devices. The hardware of an embedded-system is used for security and performance. The Software is used for features. * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 14

Advantages of Embedded System They are convenient for mass production. This results in low price per piece. These systems are highly stable and reliable. Embedded systems are made for specific tasks. The embedded systems are very small in size, hence can be carried and loaded anywhere. These systems are fast. They also use less power. The embedded systems optimize the use or resources available. They improve the product quality. * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 15

Disadvantages of Embedded System Once configured, these systems cannot be changed. Hence, no improvement or upgradation on the ones designed and created can be made. They are hard to maintain. It is also difficult to take a back-up of embedded files. Troubleshooting is difficult for embedded systems. Transferring data from one system to another is also quite problematic. Because these systems are made for specific tasks, hardware is limited. * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 16

Purpose of Embedded Systems Each Embedded system is designed to serve the purpose of any one or a combination of the following tasks. 1. Data collection/Storage/Representation 2. Data communication 3. Data (Signal) processing 4. Monitoring 5. Control 6. Application specific user interface

Data collection/Storage/Representation

Data communication

Data (Signal) Processing

Monitoring

Control

Application specific user interface

Basic Component of Embedded System * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 24

Hardware Component An embedded system comprises of the following Power Supply Memory Processor Timers/Counter Input/Output circuits Communication ports SASC (System application specific circuits) * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 25

Hardware Component Power Supply Essential component of electrical or electronic circuit power supplies like SMPS (switch mode power supply), AC power supply, AC to DC power supply, programmable power supply, high voltage power supply & uninteruptable power supply Memory Store programs or data on a temporary or permanent basis Categories of memory: Volatile Memory & Non-Volatile Memory Volatile memory power is switched off, memories lose their content * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 26

* 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 27

Memory Example : RAM(Random Access Memory) Static Random Access Memory(SRAM) Dynamic Random Access Memory (DRAM) * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 28 SRAM DRAM The storage capacity is low The storage capacity is very high It is a high cost device It is a low cost device Low power consumption and faster access speeds High power consumption and slower access speeds These are used in cache memories These are used in main memories

Memory Example : Read Only Memory PROM EPROM EEPROM Flash Memory Masked ROM PROM(Programmable ROM) EPROM(Erasable PROM) EEPROM(Electrically EPROM) * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 29

Memory The main characteristic of this device is the fact that the data is written onto the device as it gets manufactured and it is impossible to change them. This is done by designing the chip in such a manner so that it already contains the necessary data. This Memory is called as MASKED ROM. They usually serve the function of storing the bootloaders in microcontrollers and to store microcode on microprocessors . This memory is the most popular one that you might come across on a day to day basis as an embedded developer. It has all the qualities of EEPROMs except one. EEPROMs are reprogrammable one bit at a time, while flash storage is a reprogrammable one block at a time. * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 30

Processor Processor Processor is the heart of an embedded system. It is the basic unit that takes inputs and produces an output after processing the data. For an embedded system designer, it is necessary to have the knowledge of both microprocessors and microcontrollers. A processor has two essential units Program Flow Control Unit (CU) - fetching instructions from the memory Execution Unit (EU)-includes the Arithmetic and Logical Unit (ALU), data transfer operation and data conversion from one form to another. * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 31

Processor Processors can be of the following categories: General Purpose Processor (GPP) Microprocessor Microcontroller Embedded Processor Digital Signal Processor Media Processor Application Specific System Processor (ASSP) Application Specific Instruction Processors (ASIPs) GPP core(s) or ASIP core(s) on either an Application Specific Integrated Circuit (ASIC) or a Very Large Scale Integration (VLSI) circuit. * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 32

Processor A microprocessor is a single VLSI chip having a CPU. In addition, it may also have other units such as coaches, floating point processing arithmetic unit, and pipelining units that help in faster processing of instructions. A microcontroller is a single-chip VLSI unit (also called  microcomputer ) which, although having limited computational capabilities, possesses enhanced input/output capability and a number of on-chip functional units. * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 33

Microprocessor Microcontroller Microprocessors are multitasking in nature. Can perform multiple tasks at a time. For example, on computer we can play music while writing text in text editor. Single task oriented. For example, a washing machine is designed for washing clothes only. RAM, ROM, I/O Ports, and Timers can be added externally and can vary in numbers. RAM, ROM, I/O Ports, and Timers cannot be added externally. These components are to be embedded together on a chip and are fixed in numbers. Designers can decide the number of memory or I/O ports needed. Fixed number for memory or I/O makes a microcontroller ideal for a limited but specific task. External support of external memory and I/O ports makes a microprocessor-based system heavier and costlier. Microcontrollers are lightweight and cheaper than a microprocessor. External devices require more space and their power consumption is higher. A microcontroller-based system consumes less power and takes less space. * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 34

Embedded Processor An embedded processor is a microprocessor designed especially for handling the needs of an embedded system. Embedded systems require less power, so these processors are very small and draw less power from the source. An ordinary microprocessor only comes with the processor in the chip. The peripherals are separate from the main chip, resulting in more power consumption. Computational micros (32- or 64-bit datapaths) CPU of workstations, PCs, or high-end portable devices (PDAs) x86, PA-RISC, PowerPC, SPARC, etc. Embedded general purpose micros (32-bit datapaths) Designed for a wide range of embedded applications Often scaled-down version of computational micros ARM, PowerPC, MIPS, x86, 68K, etc. * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 35

Embedded Processor Microcontrollers (4-, 8-, or 16-bit datapaths) Integrate processing unit, memory, I/O buses, and peripherals Often low-cost, high-volume devices Domain-specific processors (datapath size varies greatly) Designed for a particular application domain Digital signal processors, multimedia processors, graphics processors, network processors, security processors, etc. * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 36

DSP & Media processor Digital Signal Processor & Media Processor A DSP is a specialized microprocessor used to perform calculations efficiently on digitized signals that are converted from the analog domain. One of the big advantages of DSP is the programmability of the processor, which allows important system parameters to be changed easily to accommodate the application. DSPs are optimized for digital signal manipulations. A  media processor , mostly used as an image/video  processor , is a microprocessor-based system-on-a-chip which is designed to deal with digital streaming data in real-time (e.g. display refresh) rates. These devices can also be considered a class of digital signal  processors  (DSPs) * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 37

Application Specific System Processor(ASSP) : ASSP is application dependent system processor used for processing signal of embedded system. Therefore for different application performing task a unique set of system processors is required. Application Specific Instruction Processor(ASIP) : ASIP is application dependent instruction processors. It is used for processing the various instruction set inside a combinational circuit of an embedded system. * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 38

A  timer  is a specialized type of clock which is used to measure time intervals. A timer that counts from zero upwards for measuring time elapsed is often called a  stopwatch . It is a device that counts down from a specified time interval and used to generate a time delay, for example, an hourglass is a timer. A  counter  is a device that stores (and sometimes displays) the number of times a particular event or process occurred, with respect to a clock signal. It is used to count the events happening outside the microcontroller. In electronics, counters can be implemented quite easily using register-type circuits such as a flip-flop. * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 39

Comparison Timer Counter The register incremented for every machine cycle. The register is incremented considering 1 to 0 transition at its corresponding to an external input pin (T0, T1). Maximum count rate is 1/12 of the oscillator frequency. Maximum count rate is 1/24 of the oscillator frequency. A timer uses the frequency of the internal clock, and generates delay. A counter uses an external signal to count pulses. * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 40

A  watchdog timer  (WDT) is a hardware  timer  that automatically generates a  system  reset if the main program neglects to periodically service it. It is often used to automatically reset an  embedded  device that hangs because of a software or hardware fault. Features WDT can detect errors like program errors, code crashes, the software hang, and even power surges. It can immediately detect system malfunctions. Uses the embedded reset signal present in the CPU to reset the operating systems and puts the activity of the program in its normal form. One WDT monitors another one of its types to make sure the one that is doing the task doesn’t get hang or face any system failure. * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 41

Real-Time Clock (RTC) A real-time clock is a computer clock that keeps track of the current time. Although the term often refers to the devices in personal computers, servers and embedded systems, RTCs are present in almost any electronic device which needs to keep accurate time. Features These are mainly used to generate time in a readable format for humans. They have a rapid resolution in one second. It functions as a digital watch, used to tell the time to the user. A coin cell is used to power it up so that it can still run even the system is turned off. You can see the cells on the motherboard of the computer.   * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 42

Software component A program written in assembly or in embedded c language. And then we compile it. This compiled code converted into HEX code.  This hex code is programmed or burned into the ROM of the system using some programmer . ROM Image Just as an image is a unique sequence and arrangement of pixels, embedded software is also a unique placement and arrangement at each ROM address of bytes for instructions and data * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 43

Assembly Language Coding Needed for Invoking Processor Specific Instructions Requires understanding of the processor and instruction set. A program or a small specific part coded in the assembly language using an Assembler (software used for developing codes in assembly). Three steps when using assembly language 'Assembler', 'Linker' and 'Locator' * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 44

* 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 45

Converting a C program into ROM image * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 46

Final machine software Bytes at each address defined for creating the ROM image. By changing this image, the same hardware platform work differently and can be used for entirely different applications or for new upgrades of the same system Distinct ROM image in a distinct Embedded System Hardware elements between the distinct systems can be identical but it is the software that makes a system unique and distinct from the other. * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 47

Challenges in Embedded computing system design Choice of Hardware(Performance deadline &Manufacturing cost) Deadlines-Speed-clock plus memory Power Consumption: Slow down non critical parts Upgradability: Software Up gradation Reliability: Safety critical systems 20EC211- ES& IoT 48

Contd. Complex Testing: Run real machine, timing of data is req.) Limited Observability and Controllability (no k/b & screens, force values on buses) Restricted Development environment(debug programs run on PC) 20EC211- ES& IoT 49

Contd. 20EC211- ES& IoT 50

Life As an Embedded Software Developer 20EC211- ES& IoT 51

Software Tools Editor Interpreter Compiler Assembler Cross Assembler Testing tools Locator Software Development Kit (SDK) Source-code Engineering Software Integrated Development Environment(IDE) Emulator Debugger * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 52

Editor - Develop the source code Interpreter An interpreter translates code like a compiler but reads the code and immediately executes on that code, and therefore is initially faster than a compiler Name of interpreted languages:  LISP, Ant, APL, Eiffel, Forth, J,  JavaScript , Lisp, Mople , Perl,  PHP , VBScript. Compiler Compilers convert high-level language code to machine (object) code in one session. Compilers can take a while, because they have to translate high-level code to lower-level machine language all at once and then save the executable object code to memory Name of compiled languages:    Ada  ,  ALGOL , Algol 60,  Algol 68, SMALL, BASIC ,   C ,  C++ , Objective-C, C Sharp (programming language),  CLEO ,  COBOL ,  Cobra   * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 53

Assembler It is a type of computer programs which interprets the software or computer program written in assembly language into machine language  , code or data or instruction which can be read by a computer. Name of Assembly languages: ASCENT, BAL, COMPASS, FAP, GAS, HLA,HLASM, MACRO, MI, MIPS, PAL, LC, AKI, ASPER, AUTOCODER. Cross Assembler A cross-assembler is an assembler that generates machine language for a different type of computer than the one the assembler is running in. It is used to develop programs for computers on a chip or microprocessors used in specialized applications that are either too small or are otherwise incapable of handling the development software. ACME,cc65,DASM,K2X,KICKASSEMBLER * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 54

Testing tools Testing  means verifying correct behavior. Testing can be done at all stages of module development: requirements analysis, interface design, algorithm design, implementation, and integration with other modules Generation and execution of unit, integration and system tests –  Rapi Test Structural code coverage analysis –  Rapi Cover Execution time analysis –  Rapi Time Scheduling analysis –  Rapi Task SDK An SDK is a collection of software used for developing applications for a specific device or operating system. Examples of SDKs include the Windows 7 SDK, the Mac OS X SDK, and the iPhone SDK. DKs typically include an integrated development environment ( IDE ), which serves as the central programming interface.  * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 55

Source Code Engineering Tool A programming tool or software development tool is a computer program that software developers use to create, debug, maintain, or otherwise support other programs and applications.  GNU toolchain , gcc , CodeWarrior, Xcode IDE An integrated development environment (IDE) is software for building applications that combines common developer tools into a single graphical user interface (GUI).  Netbeans , Visual studios, Eclipse Prototyper Prototyping helps you test your ideas early on, and make changes before you and your team have done a lot of expensive work. Building a functional prototype lets you work with your users or your client before you launch the final product. * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 56

Emulator An emulator is hardware or software tool that has a similar functionality to the target system or guest system. It enables the host system to execute the functionality and other components. It is a replica of the target system and used for debugging the code and issues. Once program or code is fixed at the host system. It is transferred to the target system . Debugger Sometimes we are not getting expected results or output due to errors or bug. There are certain tools that are specifically used for the debugging process. The controls flow and register value to identify the issue. * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 57

Types of ES 20EC211- ES& IoT 58

Contd. Real-time systems are those which give a quick response to critical situations. They are used in military, medical and industrial applications. In these systems, quick response is very important. Better hardware is used in these systems to avoid failure in performance. Real time embedded systems are classified into two types such as soft and hard real time systems. 20EC211- ES& IoT 59

Contd. Stand alone embedded systems do not require a host system like a computer, it works by itself. It takes the input from the input ports either analog or digital and processes, calculates and converts the data and gives the resulting data through the connected device-Which either controls, drives and displays the connected devices. Examples for the stand alone embedded systems are mp3 players, digital cameras, video game consoles, microwave ovens and temperature measurement systems. 20EC211- ES& IoT 60

Contd. Networked embedded systems are those systems which are connected to the network It can be either a local area network (LAN) or a wide area network (WAN). The connection in networked embedded systems can be wireless or wired. Example for the LAN networked embedded system is a home security system wherein all sensors are connected and run on the protocol TCP/IP Mobile embedded systems are used in portable embedded devices like cell phones, mobiles, digital cameras, mp3 players and personal digital assistants, etc. Mobile embedded systems are limited in resources including memory.  20EC211- ES& IoT 61

Contd. Small-scale embedded systems consist of  8-16 bit  microcontroller( E.g.PIC microcontroller ). Little hardware and software complexity Programming tools: Editor, Assembler and Cross Assembler The need to limit power dissipation when system is running continuously. 20EC211- ES& IoT 62

Contd. Medium scale embedded systems use 16 or 32 bit microcontroller, RISCs or DSPs. Both hardware and software complexity. Programming tools: RTOS, Source code Engineering Tool, Simulator, Debugger and Integrated Development Environment (IDE). 20EC211- ES& IoT 63

Contd. Sophisticated embedded systems have enormous hardware and software complexities, that may need ASIPs, IPs, PLAs, scalable or configurable processors. They are used for cutting-edge applications that need hardware and software Co-design and  components which have to assemble  in the final system. Programming Tools: For these systems may not be readily available at a reasonable cost or may not be available at all. A compiler or retargetable compiler (designed to be relatively easy to modify to generate code for different  µp) might have to be developed for this. 20EC211- ES& IoT 64

Hardware 20EC211- ES& IoT 65

Contd. 20EC211- ES& IoT 66

Software architecture 20EC211- ES& IoT 67

Applications: Embedded systems are used in different applications like automobiles, telecommunications, smart cards, missiles, satellites, computer networking and digital consumer electronics. 20EC211- ES& IoT 68

Contd. Embedded Systems in Smart Cards, Missiles and Satellites Security systems Telephone and banking Defense and aerospace Communication 20EC211- ES& IoT 69

Contd. Embedded Systems in Automobiles and in telecommunications Motor and cruise control system Body or Engine safety Entertainment and multimedia in car E-Com and Mobile access Robotics in assembly line Wireless communication Mobile computing and networking 20EC211- ES& IoT 70

Contd. Embedded Systems in Peripherals  & Computer Networking Displays and Monitors Networking Systems Image Processing Network cards and printers 20EC211- ES& IoT 71

Contd. Embedded Systems in Consumer Electronics Digital Cameras Set top Boxes High Definition TVs DVDs 20EC211- ES& IoT 72

Embedded Program

Common System Components * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 74

Common System Components * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 75 Basic embedded software diagram a more complex embedded software diagram

Example int ledPin =8; //definition digital 8 pins as pin to control the LED void setup() { pinMode ( ledPin,OUTPUT ); //Set the digital 8 port mode, OUTPUT: Output mode } void loop() { digitalWrite ( ledPin,HIGH ); //HIGH is set to about 5V PIN8 delay(1000); //Set the delay time, 1000 = 1S digitalWrite ( ledPin,LOW ); //LOW is set to about 5V PIN8 delay(1000); //Set the delay time, 1000 = 1S } * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 76

The Role of the Infinite Loop One of the most fundamental differences between programs developed for embedded systems and those written for other computer platforms is that the embedded programs almost always have an infinite loop. Typically, this loop surrounds a significant part of the program's functionality, as it does in the Blinking LED program. The infinite loop is necessary because the embedded software's job is never done. It is intended to be run until either the world comes to an end or the board is reset, whichever happens first. In addition, most embedded systems run only one piece of software. Although hardware is important, the system is not a digital watch or a cellular phone or a microwave oven without that software. If the software stops running, the hardware is rendered useless. So the functional parts of an embedded program are almost always surrounded by an infinite loop that ensures that they will run forever. * 16EC213 EMBEDDED SYSTEMS AND IOT - S.BHAGGIARAJ 77

78

79 Host: A computer system on which all the programming tools run Where the embedded software is developed, compiled, tested, debugged, optimized, and prior to its translation into target device. Target: After writing the program, compiled, assembled and linked, it is moved to target After development, the code is cross-compiled, translated cross-assembled, linked into target processor instruction set and located into the target.

Difference 20EC211- ES& IoT 80

Compiling The job of a  compiler  is mainly to translate programs written in some human-readable language into an equivalent set of opcodes for a particular processor. - cross-compiler GNU C compiler-AVR, Intel x86, MIPS, PowerPC, ARM, and SPARC. object file-specially formatted binary file that contains the set of instructions and data-large, flexible data structure. Common Object File Format (COFF) or Executable and Linkable Format (ELF) Most object files begin with a header that describes the sections that follow.   In  gcc  all of the code blocks are collected into a section called  text initialized global variables (and their initial values) into a section called  data uninitialized global variables into a section called  bss symbol table -that contains the names and locations of all the variables and functions referenced within the source file. 20EC211- ES& IoT 81

Linker Some of the internal variable and function references-unresolved. Combine these object files and, in the process, to resolve all of the unresolved symbols All of the code from all of the input object files will be in the  text section of the new file, and all of the initialized and uninitialized variables will reside in the new data and  bss  sections 20EC211- ES& IoT 82

Contd. Compiled startup code-need to be linked( libgloss )  a small block of assembly language code that prepares the way for the execution of software written in a high-level language Disable all interrupts. Copy any initialized data from ROM to RAM. Zero the uninitialized data area. Allocate space for and initialize the stack. Initialize the processor’s stack pointer. Call main. 20EC211- ES& IoT 83

Contd. The entire embedded application—including the operating system—is frequently statically linked together and executed as a single binary image. The program is complete except for one thing: no memory addresses have yet been assigned to the code and data sections within. 20EC211- ES& IoT 84

Locating The tool that performs the conversion from  relocatable program to executable binary image is called a  locator .  Information about the memory on the target board-input Assign physical memory addresses to each of the code and data sections In the case of the GNU tools, this feature is built into the linker ( ld ) -memory information can be passed to it in the form of a  linker script( http://www.gnu.org .). 20EC211- ES& IoT 85

Example linker script MEMORY { ram : ORIGIN = 0x00000, LENGTH = 512K rom : ORIGIN = 0x80000, LENGTH = 512K } SECTIONS { data ram : /* Initialized data. */ { _ DataStart = . ; *(.data) _ DataEnd = . ; } > rom 20EC211- ES& IoT 86

Contd. bss : /* Uninitialized data. */ { _ BssStart = . ; *(. bss ) _ BssEnd = . ; } _ BottomOfHeap = . ; /* The heap starts here. */ _ TopOfStack = 0x80000; /* The stack ends here. */ text rom : /* The actual instructions. */ { *(.text) } } 20EC211- ES& IoT 87 Output will be a executable binary image can be downloaded to the embedded system or programmed into a memory chip

Downloading and Debugging Once you have an executable binary image stored as a file on the host computer, you will need a way to download that image to the embedded system and execute it. The executable binary image is usually loaded into a memory device on the target board and executed from there. And if you have the right tools at your disposal, it will be possible to set breakpoints in the program or to observe its execution in less intrusive ways. Here it describes various techniques for downloading, executing, and debugging embedded software in general, as well as focuses on the techniques available on our development environment. 20EC211- ES& IoT 88

Software development cycle 89

Debug Monitors A debug monitor, also called a ROM monitor, is a small program that resides in nonvolatile memory on the target hardware that facilitates various operations needed during development. One of the tasks that a debug monitor handles is basic hardware initialization. A debug monitor allows you to download and run software in RAM to debug the program. Most debug monitors include many other useful features to assist in the development cycle. For example, most debug monitors incorporate some kind of command-line interface (CLI) where commands can be issued to the debug monitor for execution on the target hardware—e.g., via serial port. These commands include downloading software, running the program, peeking (reading) and poking (writing) memory and processor registers, comparing or displaying blocks of memory, and setting initialization configurations for the hardware 20EC211- ES& IoT 90

RedBoot The Arcom board includes a debug monitor called RedBoot , RedBoot resides in the bootloader flash on the Arcom board and uses the board's serial port COM1 for its command-line interface. The VIPER Technical Manual and VIPER-I/O Technical Manual describe how to connect the various modules to the Arcom board. Once you have the Arcom board connected properly, you need to connect the Arcom board's COM1 port to a serial port on your computer using the cable included in the development kit. 20EC211- ES& IoT 91

Downloading with RedBoot Now that RedBoot is up and running, we are ready to download and run the Blinking LED program. RedBoot is able to load and run ELF files, RedBoot > load –m xmodem Running programs with RedBoot RedBoot > go Managing ROM with RedBoot : The Arcom board includes a type of memory called flash, which is in-circuit programmable. Even when socketed for easy removal, flash memory does not have to be removed from the board to be reprogrammed. The RedBoot debug monitor includes software that can perform the device programming function. 20EC211- ES& IoT 92

Remote Debuggers If available, a remote debugger can be used to download, execute, and debug embedded software over a serial port or network connection between the host and target (also called cross-platform debugging). The program running on the host of a remote debugger has a user interface that looks just like any other debugger that you might have used. The main debugger screen is usually either a command-line interface or graphical user interface (GUI). GUI debuggers typically contain several smaller windows to simultaneously show the active part of the source code, current register contents, and other relevant information about the executing program. 20EC211- ES& IoT 93

Components of a remote debug session 20EC211- ES& IoT 94

Emulators An in-circuit emulator (ICE) provides a lot more functionality than a remote debugger. In addition to providing the features available with a remote debugger, an ICE allows you to debug startup code and programs running from ROM, set breakpoints for code running from ROM, and even run tests that require more RAM than the system contains. An ICE typically takes the place of—or emulates—the processor on your target board. (Some emulators come with an adapter that clips over the processor on the target.) The ICE is itself an embedded system, with its own copy of the target processor, RAM, ROM, and embedded software. In-circuit emulators are usually pretty expensive. But they are powerful tools, and in a tight spot, nothing else will help you get the debug job done better. 20EC211- ES& IoT 95

Simulators A simulator is a completely host-based program that simulates (hence the catchy name) the functionality and instruction set of the target processor. The user interface is usually the same as or similar to that of the remote debugger. In fact, it might be possible to use one debugger host for the simulator target as well. Although simulators have many disadvantages, they are quite valuable in the earlier stages of a project when there is not yet any actual hardware for the programmers to experiment with. If you cannot get your hands on a development board, a simulator is the best tool for getting a jump-start on the software development The biggest disadvantage of a simulator is that it simulates only the processor. Embedded systems frequently contain one or more important peripherals. Interaction with these devices can sometimes be imitated with simulator scripts or other workarounds, but such workarounds are often more trouble to create than the simulation is worth. 20EC211- ES& IoT 96

20EC211- ES& IoT 97

Peripherals In addition to the processor and memory, most embedded systems contain a handful of other hardware devices. Some of these devices are specific to each embedded system's application domain, while others—such as timers/counters and serial ports—are useful in a wide variety of systems. The most commonly used devices are often included within the same chip as the processor and are called internal, or on-chip, peripherals. Hardware devices that reside outside the processor chip are, therefore, said to be external peripherals. 20EC211- ES& IoT 98

External peripherals Begin by making a list of the external peripherals. Depending on your application, this list might include LCD or keyboard controllers, analog-to-digital (A/D) converters, network interface chips, or custom application-specific integrated circuits (ASICs). In the case of the Arcom board, the list contains just two items: the SMSC Ethernet controller and the parallel port. When you are designing the embedded software, you should try to break the program down along device lines. It is usually a good idea to associate a software module called a device driver with each of the external peripherals. A device driver is nothing more than a collection of software routines that control the operation of a specific peripheral and isolate the application software from the details of that particular hardware device. 20EC211- ES& IoT 99

Memory Testing The purpose of a memory test is to confirm that each storage location in a memory device is working. Memory Testing is performed when prototype hardware is ready and the designer needs to verify that address and data lines are correctly wired and memory chips are working properly. Basic idea implement in testing can be understood by this simple task: Write some set of Data values to each Address in Memory and Read it back to verify. Ex. If number ’50’ is stored at a particular Address it is expected to be there unless rewritten or erased. If all values are verified by reading back then Memory device passes the test. Only through careful selection of data values can make sure passing result to be meaningful. Difficulties involved in memory testing: It can be difficult to detect all memory problems with a simple test. Many Embedded Systems include Memory Tests only to detect catastrophic memory failures which might not even notice memory chips removal. 20EC211- ES& IoT 100

COMMON MEMORY PROBLEMS Memory Problems rarely occur with the chip itself, but due to a variety of post production tests to check quality this possibility is ruled out. Catastrophic Failure is a memory problem that occurs due to physical and electrical damage, it is uncommon and easily detectable. A common source of memory problems is associated with the circuit board. Typical circuit board problems are: Circuit board wiring between Processor & Memory device. Missing Memory chip. Improperly inserted Memory chip. 20EC211- ES& IoT 101

COMMON MEMORY PROBLEMS Circuit board wiring between Processor & Memory device.These are usually caused by, An error in design An error in production of the board Any damage after manufacture Wires that connect the memory are:- i . Address line :- select the memory location ii. Data line :- transfer the data iii. Control line :- read or write operation Two wiring problems are shown below Connected to another wire on the board Not connected to anything 20EC211- ES& IoT 102

COMMON MEMORY PROBLEMS Missing Memory chip. Unfortunately, because of the capacitive nature of unconnected electrical wires, some memory tests will not detect. For e.g. suppose you decided to use the following test algorithm write the value 1 to the first location in memory, verify the value by reading it back write 2 to the second location, verify the value write 3 to the third location, verify, etc. Because each read occurs immediately after the corresponding write, it is possible that the data read back represents nothing more than the voltage remaining on the data bus from the previous write. If the data is read back too quickly, it will appear that the data has been correctly stored in memory-even though there is no memory chip at the other end of the bus! Improperly inserted Memory chip. 20EC211- ES& IoT 103

A STRATEGY FOR MEMORY TESTING A data bus test: Checks electrical wiring problems An address bus test: Checks improperly inserted chips A device test: Checks to detect missing chips and catastrophic failures and problems with the control bus wiring Data Bus Test: It is used to check data bus wiring. In this test we need to confirm that the received data is same as the data sent by processor Example Walking 1's test 20EC211- ES& IoT 104

A STRATEGY FOR MEMORY TESTING Walking 1's test This test is used to independently test every bit. A single data bit is set to 1 and “walked” through the entire data word. If the data bus is working properly, the function will return 0. 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000 20EC211- ES& IoT 105

A STRATEGY FOR MEMORY TESTING Address Bus Test Address bus problems lead to overlapping memory locations. In the Address Bus test we need to confirm that each of the address pins can be set to 0 and 1 without affecting any of the others. The smallest set of address that will cover all possible combinations is the set of “power of two” addresses. After writing one of the addresses, we must check none of the others has been overwritten. Device Test It is used to test if the memory device is working properly. It is necessary to test the integrity of the memory device itself. The thing to test is that every bit in the device is capable of holding both 0 and 1. For a thorough and complete device test every memory location has to be visited twice. 20EC211- ES& IoT 106

Introduction-Flash memory The features of Flash memory include electrically erasable, no back-up power to protect data, in-circuit programming, high-density memory, low-cost and so on, which rapidly increase the using of Flash memory in embedded system. The programming methods of Flash memory include Programmer Mode and In-Circuit Programmer Mode. Programmer Mode means erasing/programming Flash by programming tool (programmer), with the purpose of writing programs into MCU 20EC211- ES& IoT 107

Flash memory characteristics The most perfect memory should be a high-speed, non-volatile, low-cost and high-density memory. But only one or several specialties are implemented in general memory. With the maturity of its technology, flash memory has become an ideal memory in recent years. It is endowed with characteristics such as electrical erasure, data preservation without power supply, in-system programming, high storage density, low power consumption and low cost. These are just what MCU are expecting, because MCU with internal flash memory introduced in earlier years has some shortages in reliability and stability. With the maturity of the Flash technology, now more and more above characteristics are integrated to MCU and become an important part of it. Hence flash memory makes MCU progress enormously. 20EC211- ES& IoT 108

Flash memory is really a high-density, high-performance reading/writing memory with non-volatility, low-power and high-reliability and has the following characteristics comparing with old solid state memory. Non-volatility: Flash memory protects data without power supply the same as magnetic storage. Easy-updating: Comparing with old EEPROM EEPROM—Electrically Programmable Read-Only-Memory, the electrical erasure of flash memory shortens the programming cycle for developers and makes end users’ updating memory become true. Low-cost, high-density and reliability: The parameters are much better than EEPROM (or E2PROM). 20EC211- ES& IoT 109

Key Points- several issues that need to be considered when upgrading software Limit downtime Power failure Upgrade code execution Device timing requirements Software image validity Security 20EC211- ES& IoT 110

Flash memory program concepts In many embedded systems, the memory which can protect program parameters and important data without external power supply is necessary as EEPROM previously was. The ColdFire MCU family provides the function of in-system programming of flash memory in user mode instead of EEPROM, hence making the circuit design simpler and cost lower. However, different from the reading/writing of generic RAM, flash memory operations need two special processes—Erase and Program. The former, which converts all bits to 1, consists of mass erase and page erase. The latter, which converts bit to 0, can program only one word at a time. During erasing and programming, voltage higher than the power is usually needed and it is generated by Coldfire MCU inner electric charge pump. Besides, before programming, it should be insured that the program field has not been written after last erasure. That is, the field is blank (the content is $FF). So generally, erase should be carried out before perform. 20EC211- ES& IoT 111

MISRA C

Despite its popularity, there are several drawbacks with the C language The ISO Standard language definition is incomplete Behaviour that is Undefined Behaviour that is Unspecified Behaviour that is Implementation Defined Language misuse and obfuscation Language misunderstanding Run-time error checking MISRA C is one solution... 20EC211- ES& IoT 113

A Quick History MISRA-C:1998 (aka MISRA-C1) “Guidelines for the use of the C language in vehicle based software” Compatible with ISO/IEC 9899:1990 (aka C90) MISRA-C:2004 (aka MISRA-C2) “Guidelines for the use of the C language in critical systems” Remains compatible with ISO/IEC 9899:1990 (aka C90) MISRA C:2012 (aka MISRA-C3) “Guidelines for the use of the C language in critical systems” Adds compatibility with ISO/IEC 9899:1999 (aka C99) 20EC211- ES& IoT 114

MISRA-C – The 2012 Edition Published early 2013 159 Guidelines in total 16 Directives 9 Required 7 Advisory 143 Rules 10 Mandatory 101 Required 32 Advisory Includes a compliance and deviation policy 20EC211- ES& IoT 115

116 MISRA Development Guidelines ❖ MISRA: Motor Industry Software Reliability Association ❖ Guidelines for activities across the entire software process: Integrity Requirements specification Design Programming Testing Project planning Product support ❖ Built on top of ISO 9001 (international standard for quality management), with extra rules for ensuring safety – beyond ordinary “quality”

The use of C in the automotive industry C gives good support for the high-speed, low-level, input/output operations, which are essential to many automotive embedded systems. C can generate smaller and less RAM-intensive code than many other high-level languages. A growth in the use of auto-generated C code from modelling packages. Increasing interest in open systems and hosted environments.

118 Software components ❖ Software is primarily a design, with no manufacturing variation, corrosion or ageing aspects. It has a much greater capacity to contain complexity ❖ It is perceived to be easy to change. ❖ Software errors are systematic, not random. ❖ It is intangible .

119 Automotive applications ❖ High production volumes – Components subject to wear – Difficult to ensure regular maintenance ❖ Therefore automotive software has an emphasis on data driven algorithms The code processes data in continuous streams Code should be flexible, able to handle a variety of data Avoid specialized code for each data type parameter optimization Find the “right” combination of inputs to maximize/minimize output adaptive control Control laws are not fixed; rather, they adapt to changes over time (e.g. fuel levels) and sudden events (e.g. change in road surface) on-board diagnostics

120 Automotive applications Passenger car drivers receive little or no training compared with other users of computer-based products and services Therefore, automotive software requires an emphasis on failure management techniques based on the controllability of the vehicle. ❖ Traditional automotive test environments use real vehicles and components, as well as simulations. ❖ These are available to test systems and software extensively and safely before they reach the customer.

121 Integrity Software Integrity Level (SIL) assigned to each software (sub)component Based on controllability: the ability of the vehicle occupants (not necessarily the driver) to control the safety of the situation following a failure e.g. failure of power window and door lock controllers may prevent passenger from exiting car after an accident Controllability Acceptable failure rate SIL Uncontrollable Extremely improbable 4 Difficult to control Very remote 3 Debilitating Remote 2 Distracting Unlikely 1 Nuisance only Reasonably possible

10 SIL drives choices throughout process Languages & compilers SIL 0: (default to ISO 9001 standard) SIL 1: “standardized structured language” SIL 2/3: “restricted subset of a standardized structured language; Validated or tested compilers (if available)” SIL 4: “independently certified compilers with proven formal syntax & semantics (when available)”

123 SIL drives choices throughout process ❖ Testing SIL 0: (default to ISO 9001 standard) SIL1: “Show fitness for purpose Test all safety requirements Repeatable test plan” SIL 2: “Black box testing” SIL 3: “White box module testing – defined coverage; Stress testing against livelock & deadlock; Syntactic static analysis” SIL 4: “100% white box module testing; 100% requirements testing; 100% integration testing; Semantic static analysis”

Language insecurities and the C language 1. The programmer makes mistakes - as simple as mis-typing a variable name, or might involve something more complicated like misunderstanding an algorithm 2. The programmer misunderstands the language - An example is the set of rules for operator precedence 3. The compiler doesn’t do what the programmer expects -There are many areas of the C language which are not completely defined, and so behaviour may vary from one compiler to another. In some cases the behaviour can vary even within a single compiler, depending on the context.

4. The compiler contains errors -Compilers may not always compile code correctly. They may, for example, not comply with the language standard in certain situations, or they may simply contain “bugs”. 5. Run-time errors -Languages can build run-time checks into the executable code to detect many such errors and take appropriate action. C is generally poor in providing run-time checking. 125

The use of C for safety-related systems C language is very mature, and consequently well-analysed and tried in practice. Therefore its deficiencies are known and understood. Also there is a large amount of tool support available commercially which can be used to statically check the C source code and warn the developer of the presence of many of the problematic aspects of the language. C standardization ISO/IEC 9899:1990 ISO/IEC 9899/COR1:1995 ISO/IEC 9899/AMD1:1995 ISO/IEC 9899/COR2: 1996 The base 1990 document is the ISO version of ANSI X3.159-1989 [2]. In content, the ISO/IEC standard and the ANSI standard are identical. ISO/IEC 9899:1999 No commercial embedded compilers: C99

MISRA C MISRA is a set of software development guidelines for the C programming language. It enable best practices in code safety, security, portability, and reliability in embedded systems. MISRA C specifically focuses on defining a safer subset of the C programming language for development projects. The first was  MISRA C: 1998 , which has 127 coding rules and is still widely used even today. The  MISRA C:2004  with 142 coding rules. The third edition is the  MISRA C:2012 , which initially had 143 rules. They improve efficiency and flexibility, enabling the use of MISRA C beyond the auto industry and ensuring delivery of safety-compliant products in various fields.

Objectives of MISRA-C It is the hope of the MISRA that will gain industry acceptance and that the adoption of a safer subset will become established as best practice both by vehicle manufacturers and the many component suppliers. It should also encourage training and enhance competence in general C programming, and in this specific subset, at both an individual level and a company level. Great emphasis is placed on the use of static checking tools to enforce compliance with the subset and it is hoped that this too will become common practice by the developers of automotive embedded systems. Another goal of this MISRA is that engineers and managers within the automotive industry will become much more aware of the language-choice issues.

Rationale for the production of MISRA-C The MISRA consortium published its “Development Guidelines for Vehicle Based Software” in 1994, which describes the full set of measures that should be used in software development. In particular, the choices of language, compiler and language features to be used, in relationship with safety integrity level, are recognised to be of major importance. One of the measures recommended is the use of a subset of a standardized language, which is already established practice in the aerospace, nuclear and defence industries.

MISRA Guidelines address the following Documented development process Quality system capable of meeting the requirements of ISO 9001/ISO 90003 Project management Configuration management Hazard analysis Requirements Design Coding Verification Validation

The programming language and coding context Key issues, following choice of language, are Training Style guide Compiler selection and validation Checking tool validation Metrics Test coverage

Training In order to ensure an appropriate level of skill and competence on the part of those who produce the C source code formal training should be provided for the use of the C programming language for embedded applications Style guide-Typical issues to be addressed by a style guide include code layout and use of indenting layout of braces “{ }” and block structures statement complexity naming conventions use of comment statements inclusion of company name, copyright notice and other standard file header information

Compiler selection and validation recording faults reported by the users notifying existing users of known faults correcting faults in future releases The use of source code complexity metrics is highly recommended. These can be used to prevent unwieldy and untestable code being written by looking for values outside of established norms. The use of tools to collect the data is also highly recommended Source complexity metrics

Test coverage The expected statement coverage of the software should be defined before the software is designed and written. Code should be designed and written in a manner that supports high statement coverage during testing. The term “Design For Test” (DFT) has been applied to this concept in mechanical, electrical and electronic engineering. In order to develop code that adheres to the subset the following steps need to be taken Produce a compliance matrix which states how each rule is enforced Produce a deviation procedure Formalise the working practices within the quality management system

Compliance matrix In order to ensure that the source code written does conform to the subset it is necessary to have measures in place which check that none of the rules have been broken. In order to ensure that all the rules have been covered then a compliance matrix should be produced which lists each rule and indicates how it is to be checked

Deviation procedure It is recognised that in some instances it may be necessary to deviate from the rules given in MISRA C. For example, source code written to interface with the microprocessor hardware will inevitably require the use of proprietary extensions to the language. Two category Project Deviation: A Project Deviation is defined as a permitted relaxation of rule requirements to be applied in specified circumstances. In practice, Project Deviations will usually be agreed at the start of a project. should be reviewed regularly and this review should be a part of the formal deviation process Specific Deviation: A Specific Deviation will be defined for a specific instance of a rule violation in a single file and will typically be raised in response to circumstances which arise during the development process.

A Project Deviation Request should include the following: Details of the deviation, i.e. the rule that is being violated Circumstances in which the need for the deviation arises Potential consequences which may result from the deviation Justification for the deviation A demonstration of how safety is assured A Specific Deviation Request should include the following: Details of the deviation, i.e. the rule that is being violated Potential consequences which may result from the deviation Justification for the deviation A demonstration of how safety is assured

Presentation of Rules

Example https://pclintplus.com/demo/ 139

Example #include<stdio.h> int main() { int num1,num2; scanf("%d%d",&num1,&num2); sum=num1+num2; retunrn 0; } 140

Summary of rules Environment 1.1 ( req ) All code shall conform to ISO/IEC 9899:1990 “Programming languages — C”, amended and corrected by ISO/IEC 9899/COR1:1995, ISO/IEC 9899/ AMD1:1995, and ISO/IEC 9899/COR2:1996 1.2 ( req ) No reliance shall be placed on undefined or unspecified behaviour . 1.3 ( req ) Multiple compilers and/or languages shall only be used if there is a common defined interface standard for object code to which the languages/compilers/ assemblers conform. 1.4 ( req ) The compiler/linker shall be checked to ensure that 31 character significance and case sensitivity are supported for external identifiers. 1.5 ( adv ) Floating-point implementations should comply with a defined floating-point standard. 141

Language extensions 2.1 (req) Assembly language shall be encapsulated and isolated. 2.2 (req) Source code shall only use /* … */ style comments. 2.3 (req) The character sequence /* shall not be used within a comment. 2.4 (adv) Sections of code should not be “commented out”. 142

Documentation 3.1 (req) All usage of implementation-defined behaviour shall be documented. 3.2 (req) The character set and the corresponding encoding shall be documented. 3.3 (adv) The implementation of integer division in the chosen compiler should be determined, documented and taken into account. 3.4 (req) All uses of the #pragma directive shall be documented and explained. 3.5 (req) The implementation defined behaviour and packing of bitfields shall be documented if being relied upon. 3.6 (req) All libraries used in production code shall be written to comply with the provisions of this document, and shall have been subject to appropriate validation. 143

Character sets 4.1 (req) Only those escape sequences that are defined in the ISO C standard shall be used. 4.2 (req) Trigraphs shall not be used. Identifiers 5.1 (req) Identifiers (internal and external) shall not rely on the significance of more than 31 characters. 5.2 (req) Identifiers in an inner scope shall not use the same name as an identifier in an outer scope, and therefore hide that identifier. 5.3 (req) A typedef name shall be a unique identifier. 5.4 (req) A tag name shall be a unique identifier. 5.5 (adv) No object or function identifier with static storage duration should be reused. 5.6 (adv) No identifier in one name space should have the same spelling as an identifier in another name space, with the exception of structure member and union member names. 5.7 (adv) No identifier name should be reused. 144

Types 6.1 (req) The plain char type shall be used only for storage and use of character values. 6.2 (req) signed and unsigned char type shall be used only for the storage and use of numeric values. 6.3 (adv) typedefs that indicate size and signedness should be used in place of the basic numerical types. 6.4 (req) Bit fields shall only be defined to be of type unsigned int or signed int . 6.5 (req) Bit fields of signed type shall be at least 2 bits long. Constants 7.1 (req) Octal constants (other than zero) and octal escape sequences shall not be used 145

Declarations and definitions 8.1 (req) Functions shall have prototype declarations and the prototype shall be visible at both the function definition and call. 8.2 (req) Whenever an object or function is declared or defined, its type shall be explicitly stated. 8.3 (req) For each function parameter the type given in the declaration and definition shall be identical, and the return types shall also be identical. 8.4 (req) If objects or functions are declared more than once their types shall be compatible. 8.5 (req) There shall be no definitions of objects or functions in a header file. 146

8.6 (req) Functions shall be declared at file scope. 8.7 (req) Objects shall be defined at block scope if they are only accessed from within a single function. 8.8 (req) An external object or function shall be declared in one and only one file. 8.9 (req) An identifier with external linkage shall have exactly one external definition. 8.10 (req) All declarations and definitions of objects or functions at file scope shall have internal linkage unless external linkage is required. 8.11 (req) The static storage class specifier shall be used in definitions and declarations of objects and functions that have internal linkage. 8.12 (req) When an array is declared with external linkage, its size shall be stated explicitly or defined implicitly by initialisation. 147

Initialisation 9.1 (req) All automatic variables shall have been assigned a value before being used. 9.2 (req) Braces shall be used to indicate and match the structure in the non-zero initialisation of arrays and structures. 9.3 (req) In an enumerator list, the “=” construct shall not be used to explicitly initialise members other than the first, unless all items are explicitly initialised. 148

Arithmetic type conversions 10.1 (req) The value of an expression of integer type shall not be implicitly converted to a different underlying type if: (a) it is not a conversion to a wider integer type of the same signedness, or (b) the expression is complex, or (c) the expression is not constant and is a function argument, or (d) the expression is not constant and is a return expression 10.2 (req) The value of an expression of floating type shall not be implicitly converted to a different type if: (a) it is not a conversion to a wider floating type, or (b) the expression is complex, or (c) the expression is a function argument, or (d) the expression is a return expression 149

10.3 (req) The value of a complex expression of integer type shall only be cast to a type of the same signedness that is no wider than the underlying type of the expression. 10.4 (req) The value of a complex expression of floating type shall only be cast to a floating type that is narrower or of the same size. 10.5 (req) If the bitwise operators ~ and << are applied to an operand of underlying type unsigned char or unsigned short , the result shall be immediately cast to the underlying type of the operand. 10.6 (req): A “U” suffix shall be applied to all constants of unsigned type. 150

Pointer type conversions 11.1 (req) Conversions shall not be performed between a pointer to a function and any type other than an integral type. 11.2 (req) Conversions shall not be performed between a pointer to object and any type other than an integral type, another pointer to object type or a pointer to void . 11.3 (adv) A cast should not be performed between a pointer type and an integral type. 11.4 (adv) A cast should not be performed between a pointer to object type and a different pointer to object type. 11.5 (req) A cast shall not be performed that removes any const or volatile qualification from the type addressed by a pointer. 151

Expressions 12.1 (adv) Limited dependence should be placed on C’s operator precedence rules in expressions. 12.2 (req) The value of an expression shall be the same under any order of evaluation that the standard permits. 12.3 (req) The sizeof operator shall not be used on expressions that contain side effects. 12.4 (req) The right-hand operand of a logical && or || operator shall not contain side effects. 12.5 (req) The operands of a logical && or || shall be primary‑expressions . 12.6 (adv) The operands of logical operators (&&, || and !) should be effectively Boolean. Expressions that are effectively Boolean should not be used as operands to operators other than (&&, || , !, =, ==, != and ?:). 152

12.7 (req) Bitwise operators shall not be applied to operands whose underlying type is signed. 12.8 (req) The right-hand operand of a shift operator shall lie between zero and one less than the width in bits of the underlying type of the left-hand operand. 12.9 (req) The unary minus operator shall not be applied to an expression whose underlying type is unsigned. 12.10 (req) The comma operator shall not be used. 12.11 (adv) Evaluation of constant unsigned integer expressions should not lead to wraparound. 12.12 (req) The underlying bit representations of floating-point values shall not be used. 12.13 (adv) The increment (++) and decrement (--) operators should not be mixed with other operators in an expression 153

Control statement expressions 13.1 (req) Assignment operators shall not be used in expressions that yield a Boolean value. 13.2 (adv) Tests of a value against zero should be made explicit, unless the operand is effectively Boolean. 13.3 (req) Floating-point expressions shall not be tested for equality or inequality. 13.4 (req) The controlling expression of a for statement shall not contain any objects of floating type. 13.5 (req) The three expressions of a for statement shall be concerned only with loop control. 13.6 (req) Numeric variables being used within a for loop for iteration counting shall not be modified in the body of the loop. 13.7 (req) Boolean operations whose results are invariant shall not be permitted. 154

Control flow 14.1 (req) There shall be no unreachable code. 14.2 (req) All non-null statements shall either (a) have at least one side-effect however executed, or (b) cause control flow to change. 14.3 (req) Before preprocessing, a null statement shall only occur on a line by itself; it may be followed by a comment provided that the first character following the null statement is a white‑space character. 14.4 (req) The goto statement shall not be used. 14.5 (req) The continue statement shall not be used. 14.6 (req) For any iteration statement there shall be at most one break statement used for loop termination. 155

14.7 (req) A function shall have a single point of exit at the end of the function. 14.8 (req) The statement forming the body of a switch, while, do … while or for statement shall be a compound statement. 14.9 (req) An if (expression) construct shall be followed by a compound statement. The else keyword shall be followed by either a compound statement, or another if statement. 14.10 (req) All if … else if constructs shall be terminated with an else clause. 156

Switch statements 15.0 (req) The MISRA C switch syntax shall be used. 15.1 (req) A switch label shall only be used when the most closely-enclosing compound statement is the body of a switch statement. 15.2 (req) An unconditional break statement shall terminate every non‑empty switch clause. 15.3 (req) The final clause of a switch statement shall be the default clause. 15.4 (req) A switch expression shall not represent a value that is effectively Boolean. 15.5 (req) Every switch statement shall have at least one case clause 157

Functions 16.1 (req) Functions shall not be defined with variable numbers of arguments. 16.2 (req) Functions shall not call themselves, either directly or indirectly. 16.3 (req) Identifiers shall be given for all of the parameters in a function prototype declaration. 16.4 (req) The identifiers used in the declaration and definition of a function shall be identical. 16.5 (req) Functions with no parameters shall be declared and defined with the parameter list void . 16.6 (req) The number of arguments passed to a function shall match the number of parameters. 158

16.7 (adv) A pointer parameter in a function prototype should be declared as pointer to const if the pointer is not used to modify the addressed object. 16.8 (req) All exit paths from a function with non-void return type shall have an explicit return statement with an expression. 16.9 (req) A function identifier shall only be used with either a preceding &, or with a parenthesised parameter list, which may be empty. 16.10 (req) If a function returns error information, then that error information shall be tested. 159

Pointers and arrays 17.1 (req) Pointer arithmetic shall only be applied to pointers that address an array or array element. 17.2 (req) Pointer subtraction shall only be applied to pointers that address elements of the same array. 17.3 (req) >, >=, <, <= shall not be applied to pointer types except where they point to the same array. 17.4 (req) Array indexing shall be the only allowed form of pointer arithmetic. 17.5 (adv) The declaration of objects should contain no more than 2 levels of pointer indirection. 17.6 (req) The address of an object with automatic storage shall not be assigned to another object that may persist after the first object has ceased to exist. 160

Structures and unions 18.1 (req) All structure or union types shall be complete at the end of a translation unit. 18.2 (req) An object shall not be assigned to an overlapping object. 18.3 (req) An area of memory shall not be reused for unrelated purposes. 18.4 (req) Unions shall not be used. 161

Preprocessing directives 19.1 (adv) #include statements in a file should only be preceded by other preprocessor directives or comments. 19.2 (adv) Non-standard characters should not occur in header file names in #include directives. 19.3 (req) The #include directive shall be followed by either a <filename> or "filename" sequence. 19.4 (req) C macros shall only expand to a braced initialiser, a constant, a string literal, a parenthesised expression, a type qualifier, a storage class specifier, or a do-whilezero construct. 19.5 (req) Macros shall not be #define ’d or #undef ’d within a block. 162

19.6 (req) #undef shall not be used. 19.7 (adv) A function should be used in preference to a function-like macro. 19.8 (req) A function-like macro shall not be invoked without all of its arguments. 19.9 (req) Arguments to a function-like macro shall not contain tokens that look like preprocessing directives. 19.10 (req) In the definition of a function-like macro each instance of a parameter shall be enclosed in parentheses unless it is used as the operand of # or ##. 19.11 (req) All macro identifiers in preprocessor directives shall be defined before use, except in #ifdef and #ifnde f preprocessor directives and the defined() operator. 19.12 (req) There shall be at most one occurrence of the # or ## preprocessor operators in a single macro definition. 163

19.13 (adv) The # and ## preprocessor operators should not be used. 19.14 (req) The defined preprocessor operator shall only be used in one of the two standard forms. 19.15 (req) Precautions shall be taken in order to prevent the contents of a header file being included twice. 19.16 (req) Preprocessing directives shall be syntactically meaningful even when excluded by the preprocessor. 19.17 (req) All #else , #elif and #endif preprocessor directives shall reside in the same file as the #if or #ifdef directive to which they are related 164

Standard libraries 20.1 (req) Reserved identifiers, macros and functions in the standard library, shall not be defined, redefined or undefined. 20.2 (req) The names of standard library macros, objects and functions shall not be reused. 20.3 (req) The validity of values passed to library functions shall be checked. 20.4 (req) Dynamic heap memory allocation shall not be used. 20.5 (req) The error indicator errno shall not be used. 165

20.6 (req) The macro offsetof , in library <stddef.h> , shall not be used. 20.7 (req) The setjmp macro and the longjmp function shall not be used. 20.8 (req) The signal handling facilities of <signal.h> shall not be used. 20.9 (req) The input/output library <stdio.h> shall not be used in production code. 20.10 (req) The library functions atof , atoi and atol from library <stdlib.h> shall not be used. 20.11 (req) The library functions abort , exit , getenv and system from library <stdlib.h> shall not be used. 20.12 (req) The time handling functions of library <time.h> shall not be used. 166

Run-time failures 21.1 (req) Minimisation of run-time failures shall be ensured by the use of at least one of (a) static analysis tools/techniques; (b) dynamic analysis tools/techniques; (c) explicit coding of checks to handle run-time faults. 167

168

169

51 THANK YOU