Unit 3
Unit 3
✓Write the program in high level languages like Embedded C/C++ using an
Integrated Development Environment (The IDE will contain an editor,
compiler, linker, debugger, simulator etc. IDEs are different for different
family of processors/controllers.
31-12-2020 ECE-GNITS 2
Other System Components
➢Reset Circuit,
➢Oscillator Unit,
➢Watchdog Timer
31-12-2020 ECE-GNITS 3
Reset Circuit
31-12-2020 ECE-GNITS 4
Brown-out Protection Circuit
Vcc
✓ Brown-out protection circuit prevents the
processor/controller from unexpected R1
program execution behavior when the
supply voltage to the processor/controller V BE
falls below a specified voltage. R2
Q
Reset Pulse
✓ The processor behavior may not be DZ Active Low
Vz
predictable if the supply voltage falls R3
below the recommended operating voltage.
It may lead to situations like data GND
corruption.
31-12-2020 ECE-GNITS 5
Brown-out Protection Circuit
✓A brown-out protection circuit holds the processor/controller in reset
state, when the operating voltage falls below the threshold, until it rises
above the threshold voltage.
31-12-2020 ECE-GNITS 6
Oscillator Unit
✓ A microprocessor/microcontroller is a digital device made up of digital
combinational and sequential circuits.
✓ The instruction execution of a microprocessor/controller occurs in sync with a clock
signal.
✓ The oscillator unit of the embedded system is responsible for generating the precise
clock for the processor.
✓ Certain processors/controllers integrate a built-in oscillator unit and simply require
an external ceramic resonator/quartz crystal for producing the necessary clock
signals.
✓ Certain processor/controller chips may not contain a built-in oscillator unit and
require the clock pulses to be generated and supplied externally.
✓ Quartz crystal Oscillators are example for clock pulse generating devices
Microcontroller Microprocessor
C : Capacitor
Y : Resonator
Crystal Oscillator
Oscillator
Unit
Quartz Crystal Clock Input Pin
Resonator C C
Y Oscillator
31-12-2020 ECE-GNITS Unit 7
Real Time Clock (RTC)
✓ The system component responsible for keeping track of time. RTC holds
information like current time (In hour, minutes and seconds) in 12 hour /24 hour
format, date, month, year, day of the week etc and supplies timing reference to
the system.
✓RTC is intended to function even in the absence of power. RTCs are available in
the form of Integrated Circuits from different semiconductor manufacturers like
Maxim/Dallas, ST Microelectronics etc.
✓The RTC chip contains a microchip for holding the time and date related
information and backup battery cell for functioning in the absence of power, in a
single IC package.
31-12-2020 ECE-GNITS 8
Real Time Clock (RTC)
✓The RTC chip is interfaced to the processor or controller of the embedded system.
✓For Operating System based embedded devices, a timing reference is essential for
synchronizing the operations of the OS kernel. The RTC can interrupt the OS
kernel by asserting the interrupt line of the processor/controller to which the RTC
interrupt line is connected.
✓The OS kernel identifies the interrupt in terms of the Interrupt Request (IRQ)
number generated by an interrupt controller.
✓One IRQ can be assigned to the RTC interrupt and the kernel can perform
necessary operations like system date time updation, managing software timers
etc. when an RTC timer tick interrupt occurs.
31-12-2020 ECE-GNITS 9
Watch Dog Timer (WDT)
✓A timer unit for monitoring the firmware execution.
✓If the watchdog counter is in the enabled state, the firmware can write a zero (for
up counting watchdog implementation) to it before starting the execution of a
piece of code (subroutine or portion of code which is susceptible to execution
hang up) and the watchdog will start counting.
✓If the firmware execution doesn’t complete due to malfunctioning, within the
time required by the watchdog to reach the maximum count, the counter will
generate a reset pulse and this will reset the processor.
31-12-2020 ECE-GNITS 10
Watch Dog Timer (WDT)
✓If the firmware execution completes before the expiration of the
watchdog timer the WDT can be stopped from action.
31-12-2020 ECE-GNITS 11
Watch Dog Timer (WDT)
Microoprocessor/
Controller
Watchdog
Free Running
Reset Pin
Counter
Watchdog Reset
System Clock
31-12-2020 ECE-GNITS 12
Embedded Firmware Design &
Development
✓ The embedded firmware is responsible for controlling the various
peripherals of the embedded hardware and generating response in
accordance with the functional requirements of the product.
31-12-2020 ECE-GNITS 13
Embedded Firmware Design &
Development
✓The embedded firmware development process starts with the conversion
of the firmware requirements into a program model using various
modeling tools
✓There exist two basic approaches for the design and implementation of
embedded firmware, namely;
31-12-2020 ECE-GNITS 14
Embedded firmware Design Approaches –
The Super loop
✓ Suitable for applications that are not time critical and where the response time is not so
important (Embedded systems where missing deadlines are acceptable)
✓ Very similar to a conventional procedural programming where the code is executed task by
task
✓ The tasks are executed in a never ending loop. The task listed on top on the program code is
executed first and the tasks just below the top are executed after completing the first task
✓ A typical super loop implementation will look like:
1 Configure the common parameters and perform initialization for various hardware
components memory, registers etc.
2 Start the first task and execute it
3 Execute the second task
4 Execute the next task
5:
6:
7 Execute the last defined task
8 Jump back to the first task and follow the same flow
31-12-2020 ECE-GNITS 15
Contd..
Pros:
✓ Doesn’t require an Operating System for task scheduling and
monitoring and free from OS related overheads void main ()
✓ Simple and straight forward design {
✓ Reduced memory footprint Configurations ();
Initializations ();
Cons:
while (1)
✓ Non Real time in execution behavior (As the number of tasks increases
{
the frequency at which a task gets CPU time for execution also
increases) Task 1 ();
✓ Any issues in any task execution may affect the functioning of the
Task 2 ();
product (This can be effectively tackled by using Watch Dog Timers for //:
task execution monitoring) //:
Enhancements: Task n ();
}
✓ Combine Super loop based technique with interrupts
}
✓ Execute the tasks (like keyboard handling) which require Real time
attention as Interrupt Service routines
31-12-2020 ECE-GNITS 16
Embedded firmware Design Approaches –
Embedded OS based Approach
✓ The embedded device contains an Embedded Operating System which can be one of:
✓ A Real Time Operating System (RTOS)
✓ A Customized General Purpose Operating System (GPOS)
✓ The Embedded OS is responsible for scheduling the execution of user tasks and the
allocation of system resources among multiple tasks
✓ Involves lot of OS related overheads apart from managing and executing user defined
tasks
✓ Microsoft® Windows XP Embedded is an example of GPOS for embedded devices
✓ Point of Sale (PoS) terminals, Gaming Stations, Tablet PCs etc are examples of
embedded devices running on embedded GPOSs
✓ ‘Windows CE’, ‘Windows Mobile’,‘QNX’, ‘VxWorks’, ‘ThreadX’, ‘MicroC/OS-II’, ‘Embedded
Linux’, ‘Symbian’ etc are examples of RTOSs employed in Embedded Product
development
✓ Mobile Phones, PDAs, Flight Control Systems etc are examples of embedded devices
that runs on RTOSs
31-12-2020 ECE-GNITS 17
Embedded firmware Development
Languages/Options
✓Assembly Language
✓High Level Language
✓ Subset of C (Embedded C)
✓ Subset of C++ (Embedded C++)
✓ Any other high level language with supported Cross-compiler
✓Mix of Assembly & High level Language
✓ Mixing High Level Language (Like C) with Assembly Code
✓ Mixing Assembly code with High Level Language (Like C)
✓ Inline Assembly
31-12-2020 ECE-GNITS 18
Assembly Language
✓ ‘Assembly Language’ is the human readable notation of ‘machine language’
✓ ‘machine language’ is a processor understandable language
✓ Machine language is a binary representation and it consists of 1s and 0s
✓ Assembly language and machine languages are processor/controller dependent
✓ An Assembly language program written for one processor/controller family will not work with
others
✓ Assembly language programming is the process of writing processor specific machine code in
mnemonic form, converting the mnemonics into actual processor instructions (machine
language) and associated data using an assembler
✓ The general format of an assembly language instruction is an Opcode followed by Operands
✓ The Opcode tells the processor/controller what to do and the Operands provide the data and
information required to perform the action specified by the opcode
✓ It is not necessary that all opcode should have Operands following them. Some of the Opcode
implicitly contains the operand and in such situation no operand is required. The operand may
be a single operand, dual operand or more
31-12-2020 ECE-GNITS 19
Contd..
The 8051 Assembly Instruction
MOV A, #30
Moves decimal value 30 to the 8051 Accumulator register. Here MOV A is the Opcode and 30 is the
operand (single operand). The same instruction when written in machine language will look like
01110100 00011110
The first 8 bit binary value 01110100 represents the opcode MOV A and the second 8 bit binary value
00011110 represents the operand 30.
✓ Assembly language instructions are written one per line
✓ A machine code program consists of a sequence of assembly language instructions, where each
statement contains a mnemonic (Opcode + Operand)
✓ Each line of an assembly language program is split into four fields as:
LABEL OPCODE OPERAND COMMENTS
✓ LABEL is an optional field. A ‘LABEL’ is an identifier used extensively in programs to reduce the
reliance on programmers for remembering where data or code is located. LABEL is commonly used
for representing
✓ A memory location, address of a program, sub-routine, code portion etc.
✓ The maximum length of a label differs between assemblers. Assemblers insist strict formats for labeling.
Labels are always suffixed by a colon and begin with a valid character. Labels can contain number from 0 to
9 and special character _ (underscore).
31-12-2020 ECE-GNITS 20
Contd..
;####################################################################
; SUBROUTINE FOR GENERATING DELAY
; DELAY PARAMETR PASSED THROUGH REGISTER R1
; RETURN VALUE NONE
; REGISTERS USED: R0, R1
;####################################################################
DELAY: MOV R0, #255 ; Load Register R0 with 255
DJNZ R1, DELAY ; Decrement R1 and loop till R1= 0
RET ; Return to calling program
✓The symbol ; represents the start of a comment. Assembler ignores the text in a line after the ;
symbol while assembling the program
✓DELAY is a label for representing the start address of the memory location where the piece of code
is located in code memory
✓The above piece of code can be executed by giving the label DELAY as part of the instruction. E.g.
LCALL DELAY; LJMP DELAY
31-12-2020 ECE-GNITS 21
Contd..
Assembly Language – Source File to Hex File Translation
✓The Assembly language program written in assembly code is saved as .asm (Assembly file) file or a
.src (source) file or a format supported by the assembler
✓Similar to ‘C’ and other high level language programming, it is possible to have multiple source files
called modules in assembly language programming. Each module is represented by a ‘.asm’ or ‘.src’
file or the assembler supported file format similar to the ‘.c’ files in C programming
✓The software utility called ‘Assembler’ performs the translation of assembly code to machine code
✓The assemblers for different family of target machines are different. A51 Macro Assembler from Keil
software is a popular assembler for the 8051 family micro controller
✓Each source file can be assembled separately to examine the syntax errors and incorrect assembly
instructions
✓Assembling of each source file generates a corresponding object file. The object file does not contain
the absolute address of where the generated code needs to be placed (a re-locatable code) on the
program memory
✓The software program called linker/locater is responsible for assigning absolute address to object files
during the linking process
✓The Absolute object file created from the object files corresponding to different source code modules
contain information about the address where each instruction needs to be placed in code memory
✓A software utility called ‘Object to Hex file converter’ translates the absolute object file to
corresponding hex file (binary file)
31-12-2020 ECE-GNITS 22
Source File to Hex File Translation
31-12-2020 ECE-GNITS 23
Contd..
Library File Creation and Usage:
• Libraries are specially formatted, ordered program collections of object
modules that may be used by the linker later time.
• Generated with the extension ‘.lib’.
• Library file is some kind of source code hiding technique
• ‘LIB51’ from keil software is an example for library creator and it is used
for creating library files for A51 Assembler/C51 Compiler for 8051
specific controller.
Linker and Locator:
• Responsible for linking the various object modules in a multimodule
project and assigning absolute address to each module.
• It is the responsibility of the linker to link any external dependent
variables or functions declared on various modules and resolve the
external dependencies among the modules.
• The absolute object file is used for creating hex files for dumping into
code memory of processor/controller.
31-12-2020 ECE-GNITS 24
Contd..
31-12-2020 ECE-GNITS 25
Advantages of Assemble language based
Development
31-12-2020 ECE-GNITS 26
Contd..
31-12-2020 ECE-GNITS 27
Disadvantages of Assemble language based Development
High Development Time:
• Assembly language is much harder to program than high level language.
• Learning the inner details of the processor and its assembly instructions is
highly time consuming and it creates a delay impact in product
development.
• More lines of assembly code are required for performing an action which
can be done with a single instruction in a high level language like ‘C’.
Developer Dependency:
• There is no common rule for developing assembly language based
applications whereas all high level languages instruct certain set of rules for
application development.
• In assembly language programming, the developer will have a freedom to
choose the different memory locations and registers.
• Programming approach is different from developer to developer.
Non-Portable:
• Target application written in assembly instructions are valid only for that
particular family of processors and cannot be re-used for another target
processor/controllers.
31-12-2020 ECE-GNITS 28
High Level Language
✓ The embedded firmware is written in any high level language like C, C++
✓ A software utility called ‘cross-compiler’ converts the high level language to
target processor specific machine code
✓ The cross-compilation of each module generates a corresponding object file.
The object file does not contain the absolute address of where the generated
code needs to be placed (a re-locatable code) on the program memory
✓The software program called linker/locater is responsible for assigning
absolute address to object files during the linking process
✓The Absolute object file created from the object files corresponding to
different source code modules contain information about the address where
each instruction needs to be placed in code memory
✓A software utility called ‘Object to Hex file converter’ translates the absolute
object file to corresponding hex file (binary file)
31-12-2020 ECE-GNITS 29
High Level Language – Source File to Hex File Translation
Library Files
Source File 1
Module
(.c /.c++ etc) Object File 1
Cross-compiler
(Module-1)
Source File 2
Module
(.c /.c++ etc) Object File 2
Cross-compiler
(Module-2)
Machine Code
(Hex File)
High level language to machine language Conversion process
31-12-2020 ECE-GNITS 30
Advantages of High Level Language Based
Development
Reduced Development Time:
• Developer requires less or little knowledge on the internal hardware
details and architecture of the target processor/controller.
• Minimal Knowledge of the memory organisation and register details
and syntax of the high level language are the only pre-requisites for
high level language based firmware development.
Developer Independency:
• The syntax used by most of the high level languages are universal.
Portability:
• Target applications written in high level languages are converted to
target processor/controller understandable format by a cross-compiler.
• An application written in high level language for a particular target
processor can easily be converted to another target
processor/controller specific application with little modifications.
31-12-2020 ECE-GNITS 31
Limitations of High Level Language Based
Development
31-12-2020 ECE-GNITS 32
Mixing of Assembly Language with High Level
Language
31-12-2020 ECE-GNITS 33
Mixing Assembly with High level language
(e.g. Assembly with ‘C’)
• Assembly routine are mixed with 'C' that is the entire
program is written in 'C' and Assembly routine is added into
it.
31-12-2020 ECE-GNITS 34
Contd..
Scenarios
• Entire program is written c and the cross compiler in use do not have
built in support for implementing certain features like Interrupt
Service Routine function (ISR).
• If programmer want to take advantage of speed and optimized code
offered by machine code generated by hand written assembly rather
than cross compiler generated machine code.
• When accessing certain low level hardware the timing specification
may be very critical and a cross compiler generated by binary may not
be able to offer the required specification accurately
31-12-2020 ECE-GNITS 35
Contd..
Challenges
31-12-2020 ECE-GNITS 36
Contd..
Example:
31-12-2020 ECE-GNITS 37
Mixing High level language with Assembly
(e.g. 'C' with Assembly)
• High level language like 'C are mixed Assembly language that is the
entire program is written in Assembly and 'C' routine is added into it.
31-12-2020 ECE-GNITS 38
Contd..
Scenarios
31-12-2020 ECE-GNITS 39
Contd..
Challenges
Parameter are passed to the function and values are returned from the
function using CPU registers, stack memory and fixed memory.
31-12-2020 ECE-GNITS 40
Contd..
Example:
31-12-2020 ECE-GNITS 41
Contd..
31-12-2020 ECE-GNITS 42
Inline Assembly
• Inline assembly is another technique for inserting target
target/controller specific Assembly instruction at any location of the
source code written in high level Language C.
• This avoids the delay in calling an assembly routine from 'C’ code.
• Special keywords are used to indicate that the start and end of
assembly instruction.
• In C51 keywords used are #pragma asm and #pragma endasm to
indicate a block of code written in assembly.
• Example
#pragma asm
MOV A, # 13H
#pragma endasm
31-12-2020 ECE-GNITS 43
High Level Language – ‘C’ V/s Embedded C
✓ ‘C’ is a well structured, well defined and standardized general purpose programming language with
extensive bit manipulation support
✓ ‘C’ offers a combination of the features of high level language and assembly and helps in hardware
access programming (system level programming) as well as business package developments
(Application developments like pay roll systems, banking applications etc)
✓ The conventional ‘C’ language follows ANSI standard and it incorporates various library files for
different operating systems
✓ A platform (Operating System) specific application, known as, compiler is used for the conversion of
programs written in ‘C’ to the target processor (on which the OS is running) specific binary files
✓ Embedded C can be considered as a subset of conventional ‘C’ language
✓ Embedded C supports all ‘C’ instructions and incorporates a few target processor specific
functions/instructions
✓ The standard ANSI ‘C’ library implementation is always tailored to the target processor/controller
library files in Embedded C
✓ The implementation of target processor/controller specific functions/instructions depends upon
the processor/controller as well as the supported cross-compiler for the particular Embedded C
language
✓ A software program called ‘Cross-compiler’ is used for the conversion of programs written in
Embedded C to target processor/controller specific instructions
31-12-2020 ECE-GNITS 44
‘Compiler’ V/s ‘Cross-Compiler’
✓Compiler is a software tool that converts a source code written in a high level language on top of
a particular operating system running on a specific target processor architecture (E.g. Intel
x86/Pentium).
✓The operating system, the compiler program and the application making use of the source code
run on the same target processor.
✓The source code is converted to the target processor specific machine instructions
✓A native compiler generates machine code for the same machine (processor) on which it is
running.
✓Cross compiler is the software tools used in cross-platform development applications
✓In cross-platform development, the compiler running on a particular target processor/OS converts
the source code to machine code for a target processor whose architecture and instruction set is
different from the processor on which the compiler is running or for an operating system which is
different from the current development environment OS
✓Embedded system development is a typical example for cross-platform development where
embedded firmware is developed on a machine with Intel/AMD or any other target processors
and the same is converted into machine code for any other target processor architecture (E.g.
8051, PIC, ARM9 etc).
✓Keil C51compiler from Keil software is an example for cross-compiler for 8051 family architecture
31-12-2020 ECE-GNITS 45
Programming in Embedded C
Keywords
31-12-2020 ECE-GNITS 46
Programming in Embedded C
Logical Operations
Operator Operation Comments
Performs logical AND operation. Output is true (logic 1) if
&& Logical AND both operands (left to and right to of && operator) are true
Performs logical OR operation. Output is true (logic 1) if
|| Logical OR either operand (operands to left or right of || operator) is
true
! Logical NOT Performs logical Negation. Operand is complemented
(logic 0 becomes 1 and vice versa)
31-12-2020 ECE-GNITS 49
Programming in Embedded C
Branching Instructions
Conditional branching Explanation
Instruction
//if statement
if (expression) Evaluates the expression first and if it is true executes the statements given within the { }
{ braces and continue execution of statements following the closing curly brace (}). Skips
statement1; the execution of the statements within the curly brace { } if the expression is false and
statement2; continue execution of the statements following the closing curly brace (}).
………….; One way branching
}
statement 3;
…………..;
//if else statement
if (expression) Evaluates the expression first and if it is true executes the statements given within the { }
{ braces following if (expression) and continue execution of the statements following the
if_statement1; closing curly brace (}) of else block. Executes the statements within the curly brace { }
if_statement2; following the else, if the expression is false and continue execution of statements
…………….; following the closing curly brace (}) of else.
} Two way branching
else
{
else_statement1;
else_statement2;
……………….;
}
statement 3;
31-12-2020 ECE-GNITS 50
Programming in Embedded C
Branching Instructions
//exiting from loop Loops can be exited in two ways. First one is normal exit where loop is exited when the
break; expression/test for condition becomes false. Second one is forced exit. break and goto
goto label statements are used for forced exit.
break exits from the inner most loop in a deeply nested loop, whereas goto transfers the
program flow to a defined label.
31-12-2020 ECE-GNITS 52
Programming in Embedded C
Loop Control Instructions
Looping Instruction Explanation
//skipping portion of a loop
while (expression) Certain situation demands the skipping of a portion of a loop for some
{ conditions. The ‘continue’ statement used inside a loop will skip the rest of the
…………..; portion following it and will transfer the program control to the beginning of the
if (condition); loop.
continue; //for loop with skipping
………….; for (initialization; test for condition; update variable)
} {
//do while with skipping …………….;
do if (condition)
{ continue;
…………….; …………….;
if (condition) }
continue;
…………….;
}
while (expression);
31-12-2020 ECE-GNITS 53
Programming in Embedded C - Loops
//###########################################################
//using while loop
//###########################################################
char *status_reg = (char *) 0x3000; //Declares memory mapped register
//###########################################################
//using do while loop
//###########################################################
char *status_reg = (char*) 0x3000;
do
{
//###########################################################
//using for loop
//###########################################################
char *status_reg = (char*) 0x3000;
for (;(*status_reg!=0x01););
31-12-2020 ECE-GNITS 54
Programming in Embedded C – Arrays
✓Array is a collection of related elements (data types)
✓Arrays are usually declared with data type of array, name of the array and the
number of related elements to be placed in the array
char arr [5];
&arr[0] 0x8000
arr[0] 0x10
//Selective initialization
arr[0] = 5;
arr[1] = 10;
arr[2] = 20;
arr[3] = 3;
arr[4] = 2;
31-12-2020 ECE-GNITS 56
Embedded Firmware Design & Development
Programming in Embedded C – Pointers
✓Pointer is a memory pointing based technique for variable access and
modification
✓To understand the pointer concept, consider the data memory orgnanisation of
8051
Memory Address
0x00
0x01
0x7E
0x7F
31-12-2020 ECE-GNITS 57
Embedded Firmware Design & Development
input 0x45 10
✓The contentRelationship
of memory location
between variablerepresenting the
name, address and datavariable input (0x45) can be
held by variable
accessed and modified by using a pointer of type same as the variable (char for
the variable input in the example)
✓In Embedded C the same is achieved through
31-12-2020 ECE-GNITS 58
Embedded Firmware Design & Development
input 0x45 10
p 0x00 0x45
✓Arrays are not equivalent to pointers and pointers are not equivalent to arrays
✓The expression array name [] is equivalent to a pointer, of type specified by the
array, to the first element of an array
✓E.g. for the character array char arr[5], arr[ ] is equivalent to a character
pointer pointing to the first element of array arr (This feature is referred as
‘equivalence of pointers and arrays’)
✓The array features like accessing and modifying members of an array can be
achieved using a pointer and pointer increment/decrement operators
✓Arrays and pointer declarations are interchangeable when they are used as
parameters to functions
31-12-2020 ECE-GNITS 60
Embedded Firmware Design & Development
Programming in Embedded C – Characters & Strings
✓Character is a one byte data type and it can hold values ranging from 0 to 255
(unsigned character) or -128 to +127 (signed character)
✓The term character literally refers to the alpha numeric characters (English
alphabets A to Z (both small letters and Capital letters) and number
representation from ‘0’ to ‘9’) and special characters like *, ?, ! Etc
✓String is an array of characters
✓A group of characters defined within a double quote represents a constant
string
✓‘H’ is an example for a character, whereas “Hello” is an example for a string.
String always terminates with a ‘\0’ character
✓The ‘\0’ character indicates the string termination
✓Whenever you declare a string using a character array, allocate space for the
null terminator ‘\0’ in the array length
31-12-2020 ECE-GNITS 64
Embedded Firmware Design & Development
✓A function is a self contained and re-usable code snippet intended to perform a specific task
✓‘Embedded C’ supports two different types of functions namely
✓library functions
✓user defined functions
✓ Library functions are the built in functions which is either part of the standard ‘Embedded
C’ library or user created library files
✓ printf(), scanf (), strcpy(), strcmp() etc are examples of standard library functions
✓ All library functions supported by a particular library is implemented and exported in the
same
✓ A corresponding header (‘.h’) file for the library file provides information about the various
functions available to user in a library file
✓ Users should include the header file corresponding to a particular library file for calling the
functions from that library in the ‘C’ source file
✓ User defined functions are programmer created functions in the source file (Not in a library
file) for various reasons like modularity, easy understanding of code, code reusability etc
31-12-2020 ECE-GNITS 65
Embedded Firmware Design & Development
Programming in Embedded C – Functions
✓ Return type of a function tells – what is the data type of the value returning by the
function on completion of its execution
✓ The general form of function declaration is
✓ The ‘Linkage Type’ specifies the linkage for the function. It can be either ‘external’
or ‘internal’
✓ The ‘static’ keyword for the ‘Linkage Type’ specifies the linkage of the function as
internal whereas the ‘extern’ ‘Linkage
31-12-2020 Type’ specifies ‘external’ linkage for 66the
ECE-GNITS
function
Embedded Firmware Design & Development
Programming in Embedded C – Function Pointer
✓structure is a variable holding a collection of data types (int, float, char, long etc)
✓The data types can be either unique or distinct
✓The tag ‘struct’ declares a variable as structure
✓The general form of a structure declaration is
struct struct_name
{
//variable 1 declaration
//variable 2 to declaration
//……………
//variable n declaration
};
struct employee
{ char emp_name [20];// Allowed maximum length for name = 20
int emp_code;
char DOB [10]; // DD-MM-YYYY Format (10 character)
};
31-12-2020 ECE-GNITS 68
Embedded Firmware Design & Development
Programming in Embedded C – Structure Operations
✓Structure variables are always stored in the memory of the target system with
structure member variables in the same order as they are declared in the structure
definition
✓It is not necessary that the variables should be placed in continuous physical memory
locations
✓For multi byte processors (processors with word length greater than 1 byte (8 bits)), if
the structure elements are arranged in memory in such a way that they can be
accessed with lesser number of memory fetches, it definitely speeds up the operation
✓structure padding is the process of arranging the structure elements in memory in a
way facilitating increased execution speed
✓As an example consider the following structure
typedef struct
{
char x;
int y;
} exmpl;
31-12-2020 ECE-GNITS 70
Embedded Firmware Design & Development
Let us analyze the various possibilities of storing the above structure within the
memory.
Memory
4x + 3 4x + 2 4x + 1 4x
Address
Byte 2 of Byte 1 of Byte 0 of
Data exmpl.x
exmpl.y exmpl.y exmpl.y
Byte 3 of
Data
exmpl.y
Memory
4(x + 1) + 3 4(x + 1) + 2 4(x + 1) + 1 4(x + 1)
Address
31-12-2020 ECE-GNITS 71
Embedded Firmware Design & Development
Programming in Embedded C – Structure Padding (Packed Structure)
Memory
4x + 3 4x + 2 4x + 1 4x
Address
Memory
4(x + 1) + 3 4(x + 1) + 2 4(x + 1) + 1 4(x + 1)
Address
31-12-2020 ECE-GNITS 72
Embedded Firmware Design & Development
Programming in Embedded C – Structure and Bit fields
✓Bit field is a useful feature supported by structures for bit manipulation operation and
setting up flags
✓A set of bits in the structure bit field forms a ‘char’ or ‘int’ variable
✓The general format of declaration of bit fields within structure is illustrated below
struct struct_name
{
data type (char or int) bit_var 1_name : bit_size,
bit_var 2_name : bit_size,
………………………..,
………………………...,
bit_var n_name : bit_size;
};
As an illustrative example let us see how the PSW register of 8051 (which is a bit
addressable 8 bit register) can be represented in Embedded C
struct PSW
{
char P:1, /* Bit 0 of PSW : Parity Flag */
:1, /* Bit 1 of PSW : Unused */
OV:1, /* Bit 2 of PSW : Overflow Flag */
RS0:1, /* Bit 3 of PSW : Register Bank Select 0 bit */
RS1 :1, /* Bit 4 of PSW : Register Bank Select 1 bit */
F0:1, /* Bit 5 of PSW : User definable Flag */
AC :1, /* Bit 6 of PSW : Auxiliary Cary Flag */
C:1; /* Bit 7 of PSW : Carry Flag */
/*Note that the operator ‘;’ is used after the last bit field to*/
/* indicate end of bit field*/
};
✓ Each bit field variable is defined with a name and an associated bit size
representation
✓ If31-12-2020
some of the bits are unused in a packed
ECE-GNITS fashion, the same can be skipped by
74
merely giving the number of bytes to be skipped
Embedded Firmware Design & Development
Programming in Embedded C – Union
✓ Union is a concept derived from structure and union declarations follow the same syntax as that of structures
(structure tag is replaced by union tag)
✓ Though union looks similar to structure in declaration, it differs from structure in the memory allocation
technique for the member variables
✓ Whenever a union variable is created, memory is allocated only to the member variable of union requiring the
maximum storage size.
✓ For structure variables memory is allocated to each member variables
✓ Even if a union variable contains different member variables of different data types, existence is only for a
single variable at a time
✓ The size of a union returns the storage size of its member variable occupying the maximum storage size
✓ The syntax for declaring union is given below
typedef union
{
int y; //Integer variable
char z; //Character variable
} example;
example ex1;
Assuming the storage location required for ‘int’ as 4 bytes and for ‘char’ as 1 byte, the
memory allocated to the union variable ex1 will be as shown below
Memory
ex1.z
Address 4x + 3 4x + 2 4x + 1 4x
31-12-2020 ECE-GNITS 77
Embedded Firmware Design & Development
31-12-2020 ECE-GNITS 78
Embedded Firmware Design & Development
Programming in Embedded C – Constant Declaration
Constant data
Constant data informs that the data held by a variable is always constant and cannot be modified by
the application. Constants used as scaling variables, ratio factors, various scientific computing
constants
E.g. const float PI = 3.1417;
/*Explicit declaration of character pointer pointing to 8 bit memory location, mapped at location 0x3007;
The ‘volatile’ keyword informs the cross compiler that the variable with ‘volatile’ qualifier is subject to
asynchronous change and there by the cross compiler turns off any optimization (assumptions on the
variable) for these variable
The general form of declaring a volatile variable is given below.
//Declaring a volatile variable
volatile data type variable name;
//or
data type volatile variable name;
//Usage:
//Declares volatile variable
volatile char *status_reg = (char *) 0x3000;
while (*status_reg!=0x01); //Wait till status_reg = 0x01
31-12-2020 ECE-GNITS 80
Embedded Firmware Design & Development
Programming in Embedded C – Volatile Qualifier
Volatile pointer
Volatile pointers is subject to change at any point after they are initialized. Typical
examples are pointer to arrays or buffers modifiable by Interrupt Service Routines and
pointers in dynamic memory allocation. Pointers used in dynamic memory allocation can
be modified by the realloc() function. The general form of declaration of a volatile pointer
to a non-volatile variable is given below.
data type* volatile variable name;
E.g. unsigned char* volatile a;
31-12-2020 ECE-GNITS 81
Embedded Firmware Design & Development
31-12-2020 ECE-GNITS 82
Embedded Firmware Design & Development
Programming in Embedded C – Infinite Loops
✓ Infinite loops are created using various loop control instructions like while (),
do while (), for and goto labels
//Infinite loop using while
while (1)
{
} while (1);
for (; ; ;)
{
}
Bitwise OR
Operator ‘|’ performs Bitwise OR operations. Bitwise OR operation is usually performed
for selectively setting of bits and testing the current state of a bit (Bitwise ORing with ‘0’)
Bitwise NOT
Bitwise NOT operations negates (inverts) the state of a bit. The operator ‘~’ (tilde) is used
as the Bitwise NOT operator in C.
31-12-2020 ECE-GNITS 84
Embedded Firmware Design & Development
Programming in Embedded C – Bit Manipulation Operations
Bitwise OR operation combined with left shift operation of ‘1’ is used for selectively setting
any bit in a variable. For example the following operation will set bit 6 of char variable flag.
//Sets 6th bit of flag. Bit numbering starts with 0.
flag = flag | (1<<6);
//OR
flag |= (1<<6); //Equivalent to flag = flag | (1<<6);
Toggling Bits
Toggling a bit is performed to negate (toggle) the current state of a bit. If current state of a
specified bit is ‘1’, after toggling it becomes ‘0’ and vice versa. Toggling is also known as
inverting bits. The Bitwise XOR operator is used for toggling the state of a desired bit in an
operand.
flag ^= (1<<6); //Toggle bit 6 of flag
31-12-2020 ECE-GNITS 85
Embedded Firmware Design & Development
Programming in Embedded C – Bit Manipulation Operations
Extracting /Inserting Bits from/to Packed Variables
Consider a 16 bit int variable with name ‘date’ which holds Date, Month and Year as
shown below
Testing Bits
Bitwise operators can be used for checking the present status of a bit without modifying it for decision
making operations.
31-12-2020 ECE-GNITS 86
Embedded Firmware Design & Development
Programming in Embedded C – Coding Interrupt Service Routines
✓ For Super loop based embedded firmware design, code the ISR as per the support from the
cross-compiler in use for target processor.
✓ The example given below illustrates the coding of ISR in Embedded C for C51 Cross compiler
for 8051 processor
void interrupt_name (void) interrupt x using y
{
/*Process Interrupt*/
}
✓ interrupt_name is the function name for ISR
✓ The attribute ‘interrupt’ instructs the cross compiler that the associated function is an
interrupt service routine
✓ The interrupt attribute takes an argument x which is an integer constant in the range 0 to 31
(supporting 32 interrupts). This number is the interrupt number and it is essential for placing
the generated hex code corresponding to the ISR in the corresponding Interrupt Vector
Address
✓ using is an optional keyword for indicating which register bank is used for the general
purpose Registers R0 to R7 (For more details on register banks and general purpose
registers, refer to the hardware description of 8051)
✓ The argument y for using attribute can take values from 0 to 3 (corresponding to the register
banks
31-12-20200 to 3 of 8051) ECE-GNITS 87
Embedded Firmware Design & Development
Programming in Embedded C – Reentrant Vs Recursive Functions
✓ A function which calls itself repeatedly is called a Recursive Function
✓ Using recursion, a complex problem is split into its single simplest form. The
recursive function only knows how to solve that simplest case
✓ Recursive functions are useful in evaluating certain types of mathematical
function, creating and accessing dynamic data structures such as linked lists or
binary trees
✓ Functions which can be shared safely with several processes concurrently are
called re-entrant functions
✓ When a re-entrant function is executing, another process can interrupt the
execution and can execute the same re-entrant function
✓ The “another process” referred can be a thread in a multithreaded application
or can be an Interrupt Service Routine (ISR)
✓ Re-entrant function is also referred as ‘pure’ function
✓ It is not necessary that all recursive functions are re-entrant. But a Re-entrant
function can be invoked recursively by an application
31-12-2020 ECE-GNITS 88
Embedded Firmware Design & Development
Programming in Embedded C – Dynamic Memory Allocation
The conceptual view of storage of an application and the variables related to the
application in an Operating System based execution environment is represented as
Dynamic Storage
Memory
Alterable Data
31-12-2020 ECE-GNITS 89
Embedded Firmware Design & Development
Programming in Embedded C – Memory Management Functions
malloc()
malloc() function allocates a block of memory dynamically. The malloc() function reserves a block of
memory of size specified as parameter to the function, in the heap memory and returns a pointer of
type void.
pointer = (pointer_type *) malloc (no. of bytes);
Eg: ptr= (char *) malloc(50);
calloc()
The library function calloc() allocates multiple blocks of storage bytes and initializes each allocated
byte to zero.
pointer = (pointer_type *) calloc (n, size of block);
ptr= (char *) calloc (50,1);
free()
The ‘C’ memory management library function free() is used for releasing or de-allocating the memory
allocated in the heap memory by malloc() or calloc() functions
free (ptr);
realloc()
realloc() function is used for changing the size of allocated bytes in a dynamically allocated memory
block
realloc (pointer, modified size);
31-12-2020 ECE-GNITS 90