DP - Unit-2 - BCAIAI507 - (Elective-IV) Embedded Systems

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

BCAIAI507-(Elective-IV) Embedded Systems

Introduction to Embedded C: Embedded C is a specialized programming language used for developing


software for embedded systems, such as microcontrollers and microprocessors. It is a variant of the C
programming language with specific extensions and conventions tailored to the constraints and
requirements of embedded systems. Embedded C allows developers to write efficient and low-level
code to control hardware and perform real-time tasks.

Difference between C and Embedded C: While C and Embedded C share many similarities, there are
key differences that make Embedded C suitable for embedded system development:
1. Hardware Interaction:
a. C: C is a general-purpose programming language that does not have built-in features
for direct hardware interaction. Hardware control often requires platform-specific
libraries.
b. Embedded C: Embedded C includes features for low-level hardware interaction, such
as direct register manipulation and bit-level operations, which are essential for
embedded systems.
2. Memory Management:
c. C: C assumes the availability of abundant memory and may use dynamic memory
allocation (e.g., `malloc` and `free`) extensively.
d. Embedded C: Embedded C focuses on efficient memory utilization and often avoids
dynamic memory allocation due to the limited memory resources in embedded
systems. Static memory allocation is common.
3. Portability:
e. C: C code can be highly portable across different platforms and operating systems.
f. Embedded C: Embedded C code may be less portable because it is tightly coupled
with the hardware and may include platform-specific code.
4. Standard Library:
g. C: C has a rich standard library that provides functions for various general-purpose
tasks.
h. Embedded C: Embedded C may have a limited standard library, and developers often
rely on custom libraries or write low-level code for specific tasks.
5. Real-Time Capabilities:
i. C: C is not inherently designed for real-time systems, but real-time features can be
implemented using external libraries or system-specific code.
j. Embedded C: Embedded C is designed with real-time systems in mind and includes
features for deterministic execution and real-time task scheduling.

Programming Style in Embedded C: When writing code in Embedded C, developers follow specific
programming style conventions to ensure code readability, maintainability, and compatibility with the
target hardware. Some common programming style guidelines for Embedded C include:
1. Modularity: Divide the code into functions and modules that perform specific tasks. This
improves code organization and reusability.
2. Descriptive Variable Names: Use meaningful and descriptive names for variables, functions,
and macros to enhance code clarity.

Created By- Mr. Deepak Kumar Pathak


Page 1 of 9
BCAIAI507-(Elective-IV) Embedded Systems
3. Comments: Add comments to explain the purpose and functionality of functions, modules,
and complex code sections.
4. Indentation: Use consistent indentation to improve code readability.
5. Avoid Dynamic Memory Allocation: Minimize or avoid dynamic memory allocation to ensure
efficient memory usage in resource-constrained environments.
6. Register Access: When interacting with hardware registers, use macros or inline assembly to
access registers and bits directly, enhancing code efficiency and clarity.
7. Error Handling: Implement error handling mechanisms, such as error codes or return values,
to handle unexpected situations gracefully.
8. Real-Time Considerations: If developing real-time systems, adhere to real-time programming
principles, such as avoiding blocking code and ensuring predictable execution times.
9. Testing and Debugging: Implement thorough testing and debugging procedures, including the
use of hardware debugging tools and simulators.
10. Platform Documentation: Maintain documentation describing the hardware and software
architecture, memory map, and register descriptions, as these are essential for code
development and maintenance.
11. Coding Standards: Follow established coding standards or guidelines specific to the
embedded platform or organization to ensure consistency across projects.

The basic structure of an Embedded C program is similar to that of a standard C program but with
certain conventions and considerations specific to embedded systems. Below is the basic structure of
an Embedded C program:

// Include directives for header files (libraries)


#include <header1.h>
#include <header2.h>
//
// Macros and preprocessor directives
#define MACRO_NAME value
// Global variables and constants
int globalVariable1;
const int constantValue = 42;
// Function prototypes
void function1(void);
int function2(int arg1, int arg2);
// Main function (entry point for the program)
int main(void) {
// Local variables
int localVar1;
// ...
// Initialize hardware peripherals (if required)
// Main program logic
while (1) { // Infinite loop for embedded systems
// Perform tasks and control hardware

Created By- Mr. Deepak Kumar Pathak


Page 2 of 9
BCAIAI507-(Elective-IV) Embedded Systems
// Call functions
function1();
int result = function2(10, 20);
// Implement real-time tasks (if applicable)
// ...
// Delay or control timing (if required)
// ...
// Handle interrupts (if applicable)
// ...
}

return 0; // Terminate the program (not always necessary in embedded systems)


}
// Function definitions
void function1(void) {
// Function logic
}
int function2(int arg1, int arg2) {
// Function logic
return result;
}

// Additional functions and tasks (if needed)


```

Explanation of the Embedded C Program Structure:


1. Include Directives: These directives are used to include header files (libraries) required for the
program. These headers provide definitions for functions, macros, and constants used in the
program.
2. Macros and Preprocessor Directives: You can define macros and use preprocessor directives
to configure and customize the program. Common directives include `#define` for defining
macros.
3. Global Variables and Constants: Declare global variables and constants that will be used
throughout the program. Be mindful of memory constraints in embedded systems.
4. Function Prototypes: Declare function prototypes to inform the compiler about the functions
you intend to define later in the program. This allows you to call functions before their actual
definitions.
5. Main Function: The `main` function is the entry point of the program. It contains the main
program logic. In embedded systems, it often contains an infinite loop (`while (1)`) that
continuously executes the program's tasks.
6. Local Variables: Declare local variables within functions as needed. These variables have
limited scope and are often used for temporary storage.
7. Initialization: Initialize hardware peripherals and configure the system as necessary. This
includes configuring I/O pins, setting up timers, and initializing communication interfaces.

Created By- Mr. Deepak Kumar Pathak


Page 3 of 9
BCAIAI507-(Elective-IV) Embedded Systems
8. Main Program Logic: Inside the `while (1)` loop, implement the main program logic. This is
where you control hardware, execute tasks, and respond to external events or inputs.
9. Function Definitions: Implement the functions declared earlier. Function definitions contain
the actual code that performs specific tasks.
10. Additional Functions and Tasks: You can define additional functions and tasks as needed to
modularize your code and improve code organization.

Constants: Constants are fixed values that do not change during program execution. In Embedded C,
you commonly use the following types of constants:
1. Integer Constants: These are whole numbers, either decimal, octal (prefix '0'), or hexadecimal
(prefix '0x'). For example:
a. `int integerConstant = 42;`
b. `int octalConstant = 052; // Octal (42 in decimal)`
c. `int hexConstant = 0x2A; // Hexadecimal (42 in decimal)`
2. Floating-Point Constants: These are real numbers with a fractional part and/or exponent. For
example:
float floatConstant = 3.14;
double doubleConstant = 2.71828;
3. Character Constants: Single characters enclosed in single quotes. For example:
char charConstant = 'A';
4. String Constants: Sequences of characters enclosed in double quotes. For example:
char* stringConstant = "Hello, World!";
5. Enumeration Constants: Enumerations define a set of named integer constants. For example:
enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
enum Days currentDay = Wednesday;
2. Preprocessor Constants: Constants defined using `#define` in preprocessor directives. For
example:
#define MAX_VALUE 100
int value = MAX_VALUE;

Variables: Variables are used to store and manipulate data during program execution. In Embedded
C, variables are typically declared using data types specific to the target hardware:
 Integer Variables: Used to store whole numbers (int, short, long, etc.).
int integerVar = 42;
 Floating-Point Variables: Used for real numbers (float, double, etc.).
float floatVar = 3.14;
 Character Variables: Store single characters.
char charVar = 'A';
 Pointer Variables: Hold memory addresses and are used for various purposes, including
accessing hardware registers.
int* ptr; // Pointer to an integer
 Array Variables: Used to store multiple values of the same data type.
int numbers[5] = {1, 2, 3, 4, 5};

Created By- Mr. Deepak Kumar Pathak


Page 4 of 9
BCAIAI507-(Elective-IV) Embedded Systems

 Structure and Union Variables: Organize multiple variables of different data types into a
single entity.
struct Point {
int x;
int y;
};
struct Point p1 = {10, 20};

Common Data Types in Embedded C:


1. int:
 Description: The `int` data type represents signed integers.
 Memory Representation: The size of an `int` can vary depending on the architecture of
the embedded system. It is typically 16 bits (2 bytes) or 32 bits (4 bytes). For example, in
a 16-bit system, an `int` can store values from -32,768 to 32,767.
2. unsigned int:
 Description: The `unsigned int` data type represents unsigned (non-negative) integers.
 Memory Representation: Similar to `int`, the size of an `unsigned int` can vary. It typically
ranges from 16 bits to 32 bits.
3. char:
 Description: The `char` data type represents characters or small integers.
 Memory Representation: `char` is usually 8 bits (1 byte) in size. It can store characters
using ASCII or other character encodings, or it can be used to represent small integers
from -128 to 127 or 0 to 255 when declared as `signed char` or `unsigned char`,
respectively.
4. float:
 Description: The `float` data type represents single-precision floating-point numbers.
 Memory Representation: Typically, a `float` occupies 32 bits (4 bytes) in memory and
follows the IEEE 754 floating-point standard, which includes a sign bit, an exponent, and
a fraction (mantissa).
6. double:
 Description: The `double` data type represents double-precision floating-point numbers.
 Memory Representation: A `double` typically occupies 64 bits (8 bytes) in memory and
uses the IEEE 754 double-precision standard.
7. short:
 Description: The `short` data type represents short integers.
 Memory Representation: The size of a `short` can vary but is usually 16 bits (2 bytes). It
can store values from -32,768 to 32,767 (signed) or 0 to 65,535 (unsigned).
8. long:
 Description: The `long` data type represents long integers.
 Memory Representation: The size of a `long` can vary depending on the architecture. It is
often 32 bits on 32-bit systems and 64 bits on 64-bit systems.
Memory Representation: The memory representation of data types in Embedded C is influenced by
the target hardware's architecture. Here are some considerations:

Created By- Mr. Deepak Kumar Pathak


Page 5 of 9
BCAIAI507-(Elective-IV) Embedded Systems
1. Endianness: Different architectures can have different byte orders, which affect how multi-byte
data types (e.g., `int`, `float`) are stored in memory. The two common byte orders are little-endian
(least significant byte first) and big-endian (most significant byte first).
2. Alignment: Some architectures require data types to be stored at specific memory addresses
aligned to their size (e.g., 4-byte data aligned to 4-byte boundaries). Misaligned data access can
result in performance penalties or errors.
3. Memory Size: The size of data types can vary between architectures. For example, an `int` might
be 16 bits on one architecture and 32 bits on another.
4. Floating-Point Representation: Floating-point data types (`float` and `double`) use standardized
representations (IEEE 754) for consistency across platforms. However, the precision and range
may still vary.
5. Compiler Settings: The compiler used to build the Embedded C program can also influence
memory representation. Compiler-specific optimizations and settings may affect how data types
are stored and accessed in memory.

Keywords: Keywords are reserved words in the C language that have predefined meanings. You
cannot use keywords as identifiers (variable names, function names, etc.). Examples of keywords
include `int`, `float`, `if`, `for`, `while`, and `return`.

Identifiers: Identifiers are names given to variables, functions, arrays, and other program elements.
Identifiers must adhere to certain rules:
- Must start with a letter (uppercase or lowercase) or an underscore `_`.
- Subsequent characters can include letters, digits, or underscores.
- Identifiers are case-sensitive.

Here's an example that uses constants, variables, data types, and identifiers in an Embedded C
program:
#include <stdio.h>
#define MAX_VALUE 100
int main(void) {
int integerVar = 42;
float floatVar = 3.14;
char charVar = 'A';

printf("Integer: %d\n", integerVar);


printf("Float: %.2f\n", floatVar);
printf("Character: %c\n", charVar);
return 0;
}
This program defines constants (`MAX_VALUE`), declares variables of different data types
(`integerVar`, `floatVar`, `charVar`), and uses identifiers (`main`, `printf`) to demonstrate their
usage.f`)

Created By- Mr. Deepak Kumar Pathak


Page 6 of 9
BCAIAI507-(Elective-IV) Embedded Systems

Arrays in Embedded C: Arrays are collections of elements of the same data type, grouped together
under a single name. They are particularly useful in embedded systems for storing and processing data
efficiently. Here are key considerations for using arrays in embedded C:
1. Declaration: Arrays are declared with a specified data type and a size that determines the
number of elements it can hold.
- Example: int sensorReadings[10]; // Declares an integer array with 10 elements
2. Initialization: Arrays can be initialized at the time of declaration or later in the code.
- Example: int temperatures[5] = {25, 28, 30, 27, 26}; // Initialize with values
3. Accessing Elements: Elements in an array are accessed using an index, which starts from 0.
- Example: int value = sensorReadings[2]; // Accesses the third element (index 2) in
the array
4. Iterating Through Arrays: Loops are commonly used to iterate through array elements.
- Example:
- for (int i = 0; i < 10; i++) {
- // Access and process sensorReadings[i]
- }
5. Array Size:
 It's essential to manage array size carefully in embedded systems to avoid memory
overflow or waste.
 Arrays should be sized according to the specific requirements of the application.
6. Memory Efficiency: In embedded systems with limited memory, consider using smaller data
types (e.g., `uint8_t`, `int16_t`) to minimize memory usage if appropriate.

Strings in Embedded C: Strings in C are represented as arrays of characters (`char`). Embedded C


often deals with character arrays to handle text and messages. Key considerations for using strings in
embedded C include:
1. Declaration: Strings are declared as character arrays terminated by a null character `'\0'`.
Example: char message[20]; // Declares a character array to hold a string of up to 19
characters
2. Initialization: Strings can be initialized using string literals.
- Example: char greeting[] = "Hello, Embedded C!"; // Initialize with a string
3. String Functions: Embedded C includes standard string manipulation functions from the
`<string.h>` library. These functions allow you to perform operations like copying,
concatenating, and comparing strings.
Example:
#include <string.h>
char source[] = "Embedded";
char destination[20];
strcpy(destination, source); // Copy source to destination
4. Null Termination:
 Ensure that strings are null-terminated to avoid buffer overflows.
 Always leave space for the null terminator when defining the array size.
5. Memory Efficiency:

Created By- Mr. Deepak Kumar Pathak


Page 7 of 9
BCAIAI507-(Elective-IV) Embedded Systems

 Be mindful of memory usage when working with strings in embedded systems.


 Consider using fixed-size buffers to limit memory consumption.
6. String Length: Calculate the length of a string using the `strlen` function from `<string.h>`.
Example:
#include <string.h>
char text[] = "Embedded C";
int length = strlen(text); // Computes the length of the string

In Embedded C programming, operators are used to perform various operations on variables and
values. These operators can be classified into several categories, including arithmetic, relational,
logical, assignment, bitwise, and more.
Types of Operators in C:
1. Arithmetic Operators: These operators perform basic arithmetic operations.
Examples: `+` (addition), `-` (subtraction), `*` (multiplication), `/` (division), `%` (modulus).
2. Relational Operators: Relational operators are used to compare values.
Examples: `==` (equal to), `!=` (not equal to), `<` (less than), `>` (greater than), `<=` (less than
or equal to), `>=` (greater than or equal to).
3. Logical Operators: Logical operators are used for logical operations.
Examples: `&&` (logical AND), `||` (logical OR), `!` (logical NOT).
4. Assignment Operators: These operators assign values to variables.
Examples: `=` (assignment), `+=` (addition assignment), `-=` (subtraction assignment), `*=`
(multiplication assignment), `/=` (division assignment), `%=` (modulus assignment), and
others.
5. Increment/Decrement Operators: These operators are used to increment or decrement
variables.
Examples: `++` (increment), `--` (decrement).
6. Bitwise Operators (Focus of Explanation): Bitwise operators perform operations at the bit
level.
Examples: `&` (bitwise AND), `|` (bitwise OR), `^` (bitwise XOR), `~` (bitwise NOT), `<<` (left
shift), `>>` (right shift).

Bitwise Operators in Embedded C: Bitwise operators are essential in embedded systems for tasks like
setting and clearing individual bits in hardware registers, managing flags, and performing bitwise
calculations. Let's explain each bitwise operator:
1. Bitwise AND (`&`): Performs a bitwise AND operation between corresponding bits of two
operands. It sets a bit to 1 only if both corresponding bits are 1.
Example: uint8_t result = 0b1010 & 0b1100; // result is 0b1000
2. Bitwise OR (`|`): Performs a bitwise OR operation between corresponding bits of two
operands. It sets a bit to 1 if at least one of the corresponding bits is 1.
Example: uint8_t result = 0b1010 | 0b1100; // result is 0b1110
3. Bitwise XOR (`^`): Performs a bitwise XOR (exclusive OR) operation between corresponding
bits of two operands. It sets a bit to 1 if the corresponding bits are different.
Example: uint8_t result = 0b1010 ^ 0b1100; // result is 0b0110
4. Bitwise NOT (`~`): Inverts (flips) all the bits of a single operand.

Created By- Mr. Deepak Kumar Pathak


Page 8 of 9
BCAIAI507-(Elective-IV) Embedded Systems
Example: uint8_t result = ~0b1010; // result is 0b0101

5. Left Shift (`<<`): Shifts the bits of the left operand to the left by a specified number of
positions, filling in with zeros on the right.
Example: uint8_t result = 0b1010 << 2; // result is 0b00101000
6. Right Shift (`>>`): Shifts the bits of the left operand to the right by a specified number of
positions, filling in with zeros on the left.
Example: uint8_t result = 0b1010 >> 2; // result is 0b000010
Bitwise operators are particularly useful for manipulating individual bits in register settings,
implementing protocols, and performing other low-level operations common in embedded systems
development.

Created By- Mr. Deepak Kumar Pathak


Page 9 of 9

You might also like