C PROGRAMMING FOR EMBEDDED SYSTEMS
EL-GY 6483 REAL TIME EMBEDDED SYSTEMS
C FOR EMBEDDED
Copyright By PowCoder代写 加微信 powcoder
Language Programmers C 60%
C++ 21% Assembly 5%
Java 3% C# 2% MATLAB/Labview 4% Python 1% .NET 1% Other 4%
C FOR EMBEDDED
Some differences in programming for embedded systems:
• Compiling for a different target architecture
• Limited memory, processing power on target
• Can have input from external peripherals
• Reliability constraints
LIFECYCLE OF A C PROGRAM FOR EMBEDDED
HOW C CODE BECOMES AN EXECUTABLE
DATA TYPES
BITWISE OPERATIONS
Bitwise operation Symbol (in C) AND &
NOT ~ Left Shift << Right Shift >>
EXAMPLE: CHECK A BIT
To check a bit, AND it with the bit you want to check:
bit = number & (1 << x);
That will put the value of bit x into the variable bit.
BIT FIELDS
To create a mask of certain bits.
BIT OPERATIONS: EXERCISE
Answer the following question for C, using bitwise operators:
IMPLIED DECLARATION
• int n = 0x7F2;
• int n = 0b1010;
• int n = (1<<3);
0x05 & 0x01 = ?
0x05 | 0x02 = ?
0x05 ^ 0x01 = ?
0x05 << 2 = ?
0x05 >> 1 = ?
0xF4 & 0x3A = ? (1<<19) | (1<<12) = ?
ASSIGNMENT OPERATIONS
INCREMENT/DECREMENT OPERATIONS
POINTERS EXAMPLE
ANOTHER POINTER EXAMPLE
POSSIBLE??
FUNCTION POINTERS, POSSIBLE??
Yes, but can be tricky.
POSSIBLE?? - YES
PASSING BY VALUE VS. REFERENCE
PASSING BY VALUE VS. REFERENCE
MEMORY MANAGEMENT
Source: ”What and where are the stack and heap?” Answer by Snow Crash, http://stackoverflow.com/questions/79923/ what-and-where-are-the-stack-and-heap
MEMORY MANAGEMENT
int foo() {
char *pBuffer; //<--nothing allocated yet (excluding the pointer itself, which is
//allocated here on the stack). bool b = true; // Allocated on the stack.
//Create 500 bytes on the stack
char buffer[500];
//Create 500 bytes on the heap
pBuffer = new char[500]; }//<-- buffer is deallocated here, pBuffer is not
}//<--- oops there's a memory leak, I should have called delete[] pBuffer;
Source: ”What and where are the stack and heap?” Answer by Snow Crash, http://stackoverflow.com/questions/79923/ what-and-where-are-the-stack-and-heap
MEMORY MANAGEMENT
Some coding standards (e.g. for high-reliability embedded systems) forbid dynamic memory allocation. Why?
• We specify volatile variables when using interrupts and I/O ports
• Tells compiler that variables can be changed outside of the code
A programmer writes the following function to get the square of a volatile integer parameter pointed to by*p.
However, when he tests it, it returns ‘6’ – which is not a square of an integer value!
Why does this happen, and how can he modify his code so that it will always return a valid square?
int square(volatile int *p) {
return *p * *p;
TYPE QUALIFIERS
When might we declare const volatile int n;
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com