T3 Embedded Programing 07072022
T3 Embedded Programing 07072022
This slide is a part of BGSV Embedded Academy (BEA) program and only
used for BEA training purposes.
This slide is Bosch Global Software Technology Company Limited’s internal
property. All rights reserved, also regarding any disposal, exploitation,
reproduction, editing, distribution as well as in the event of applications for
industrial property rights.
This slide has some copyright images and text, which belong to the
respective organizations.
T3
EMBEDDED
PROGRAMMING
Objectives &
Assumptions
Remind general programming principles
Remind key embedded system knowledges
How to program for embedded system effectively
Code optimization & Secure coding
Know and practice Object-oriented programming
5
Agenda
8
Programing principles
Programing language classification
Programing languages
Machine
Structure Compiler Web
language
Assembly Interpret
Object AI
language er
10
Programing principles
Compiler vs Interpreter
Source code
?
Result
Execution
Data
Source code
Result
?
Data
11
Programing principles
Programing Domains
Scientific Applications
Fortran, ALGOL60
Business Applications
COBOL
Artificial Intelligence
LIPS, Prolog
System Programing
PL/S, BLISS, Extended ALGOL
Web Software
XHTML, JavaScript, PHP
12
Programing principles
Language Evaluation Criteria and Characteristics
REABILITY WRITABILITY REALIABILITY
Simplicity * * *
Data types * * *
Syntax * * *
Abstraction * *
Type checking *
Exception *
handling
Cost of learning.
Cost of writing.
Cost of compiling, executing, optimization, maintaining, portability…
13
Programing principles
Compilations steps
Source code Copy all contains of header files (.h, .hpp) into target file
Preprocessi (.c, .cpp)
(.c, .h, .cpp, .hpp)
ng Macros replace (#define)
Conditional compilation (#if, #ifdef, #ifndef, #else,
(.c, .cpp) #endif)
15
Programing principles
Compilation Phases
Lexical analyzer
Syntax analyzer
Sematic analyzer
Intermediate code
generator
Code optimizer
Code generator
16
Programing principles
Q1
#define MAX(a,b) (a>b)?a:b
inline int ReturnMaxNumber (int a, int b) {if a > b return a; else return
b;}
int ReturnMaxNumber (int a, int b) {if a > b return a; else return b;}
Which statement about Macro function and Inline function are
Incorrect?
A. Macro function is replaced in Preprocesor phase, while Inline function is replaced in Compiler
phase.
B. When running, both Macro function and Inline function will not do context saving and make
function call jumping. So they both run faster than normal function.
C. Both may take more memory code size compare to normal function.
D. Both Macro function and Inline function will harder for debugging compare to normal
17 function.
Programing principles
Inline function vs Macro
inline return_type function_name #define MACRO_NAME
(parameters) Macro_definition
{
// inline function code
}
A. (.a, .lib) is static library file; (.so, .dll) is dynamic library file.
C. Both Static library and dynamic library can be created from multiple source files.
20
Programing principles
Q3
int X = 0; int Y = 0;
X += X++;
Y = ++Y + Y++;
printf("Value of X: %d\n",X); printf("Value of Y: %d\n",Y);
A. X = 1; Y = 3
B. X = 2; Y = 4
C. X = 1; Y = 2
D. Wrong syntax of Y
21
Programing principles
Q4
int X[5] = {0,1,2,3,4};
int Y = 5[X];
printf("Value of Y: %d\n",Y);
What are output value of Y?
A. 5
B. 0
D. Unknown value
22
Agenda
Embedded system is combination of Computer HW and SW, and perhaps with additional
part (mechanical, electronic) designed to perform a dedicated function.
24
Embedded Programing
Basic elements of traditional Embedded system
Communication
Sensors
Actuator
Microcontroller with SW
25
Embedded Programing
Embedded system characteristics basic
26
Embedded Programing
Embedded system programing: Which common elements
inside Embedded SW?
HW
27
Embedded Programing
What skills required for Embedded programmer?
HW knowledge: must familiar with microcontroller, circuits, boards, schematic,
oscilloscope probe, VOM,…
Peripheral interfaces knowledge: SPI, I2C, 1-Wire, UART,…
Efficient code.
Robust code.
Minimal resources.
Reusable code.
Debug skil
28
Embedded Programing
Embedded system programing: Constraints affect design
choices
Processin Which constrains are most importance
g power
for below example product:
29
Embedded Programing
Why C is most common language for Embedded
programing?
“Low level” of high level language.
Processer independence.
30
Embedded Programing
Real Time System (RTS)
A RTS has timing constraints. The function has deadline for completion.
The function of a Real time system specified by ability to make calculations/decisions in
timely manner.
A RTS is not simply about the speed. It is about deadline. Guarantee that the deadlines
of the system always meet.
Understand worse
Handle the cases when
case performance
deadlines cannot meet.
requirements.
31
Embedded Programing
Real Time Operation System (RTOS)
Real time task scheduling
Resource management
Scheduling: decide which task should be execute, which task should be suspensed
32
Embedded Programing
Preemptive vs Non-Preemtive
33
Embedded Programing
Task and Timing
34
Embedded Programing
Task and runnable
Tasks are managed by
TASK_10ms
OS
{
SetContext_Runnable1();
Runnable1_Run();
ReleaseContext_Runnable1(); Runnables are
managed by RTE
SetContext_Runnable2();
Runnable12_Run();
ReleaseContext_Runnable2();
…..
}
35
Agenda
37
Embedded Programming
Bitwise Operators (2)
unsigned char a = 0xFF;
char b = 0xFF;
A. 127 ; 127
B. 127 ; -1
C. -1 ; -1
D. 127; 0
38
Embedded Programing
Pointer remind
Determine type and value
int a[] = {1, 5, 6, 7}; of:
7. &p = ?
int* p = a; 1. a = ?
_______ 8. *p = ?
| | 2. &a = ?
9. p + 1 = ?
|___________|
3. *a = ?
| p | 0x010 10. *p + 1 = ?
|___________| 4. &a + 1 = ? 11. &p + 1 = ?
| ... |
|___________| 5. a++ = ? 12. *(p + 1) = ?
| a | 0xF00
6. p = ? 13. p++ = ?
|___________|
| |
|_ _ _ _ _ _ _ |
39
Embedded Programming
const and pointer
int* a; // Pointer to int
const int* b; // Pointer to const int
int* const c; // Const pointer to int
const int* const d; // Const pointer to const int
1. a++; 5. *a = 1;
2. b++; 6. *b = 1;
Why we need to use them?
3. c++; 7. *c = 1;
4. d++; 8. *d = 1;
40
Embedded Programing
Pointer to function
Do not know the work of client side, make
program more portable.
Make the program easier to extend.
Syntax:
<returnType>* <pointerName> ([type1 param1,
type2 param2, …])
Example:
void (*p)(int, int, int, int, int, int)
= nullptr;
p = DrawTriangle;
41
Embedded Programing
Switch..case vs multiple if..else
Switch(a)
{ If(a == 1) …
Case 1: break; Else if (a == 2) …
Case 2: break; Else if (a == 3)…
Case 3: break;
}
Jump (&a + a)
42
Code optimization hints
Hint 1: Inline function/Macro function
sint16 g_mtl_Abs_si16(Sint16 x)(if (x) > 0 return (x); else return (–x);)
INLINE Sint16 g_mtl_Abs_si16(Sint16 x)(if (x) > 0 return (x); else return (–
x);)
#define g_mtl_Abs_mac(x) (((x) >= (0)) ? (x) : (-(x)))
43
Code optimization hints
Hint 2: Use switch instead of multiple if-else
if(x == 1){A();} else if (x == 2) {B();} else if (x == 3) {C();} else {D();}
switch (x)
{ case 1: A(); break;
case 2: B();break;
case 3: C(); break;
default: D(); break;}
44
Code optimization hints
Hint 3: Use integer type for loop index/array member
access
for(unsigned byte i = 0; i >= 100; i++){ArrayBuffer[i] = 0;}
45
Code optimization hints
Hint 4: Use bit shift instead of division/multiplex
unsigned integer a, b;
a = a/2; b = b*4;
unsigned integer a, b;
a = (unsign integer) (a>>1); b = (unsign integer) (b<< 2);
46
Code optimization hints
Hint 5: Use integer type instead of float/double number
float a = 1.9;
if (a > 1.5f) { /* do something */}
float a = 1.9;
int b =(int)(a*10);
if (b > 15) { /* do something */}
Use when: always
Optimize: Run faster.
47
Code optimization hints
Hint 6: Avoid to use multiple/division operator
int a = 2; int b = 2;
a = a*2;
int a = 2;
a = a + a;
48
Code optimization hints
Hint 7: Use local variable instead of global variable
extern int a; A();
void A(void){ if(a > 1) {/* Do something */}}
Use when:
Optimize: Run faster. Take more RAM.
49
Code optimization hints
Hint 8: Use if branch for higher probability
if (a == NULL_PTR){
/* Null pointer. Do nothing */
} else { A();}
if (a != NULL_PTR){
A();
}
Use when: always for most of Microcontroller architechture.
Optimize: Run faster. Take more RAM.
50
Code optimization hints
Hint 9: Function is called only as often as needed
Com_ReceiveSignal(1, &l_SignalData_ui8);
if (l_SignalData_ui8 == 1) { A(); }
if(NewMsgReceived_b == TRUE){
Com_ReceiveSignal(1, &l_SignalData_ui8);
if (l_SignalData_ui8 == 1) { A(); }}
Use when: always.
Optimize: Run faster.
51
Code optimization hints
Hint 10: Reduce number of loop
for (int i = 0; i < 1000; ++i){
if(ArrayA[i] > 0) {Flag = TRUE;}
}
52
Code optimization hints
Hint 11: Use better/smarter algorithm! (1)
53
Secure programming
Overflow Compiler
optimization
Undefined behaviour
Use of uninitialized
Unspecific behaviour variable
Divide by zero
Type casting
Use object after Race condition
destroyed
Null pointer Infinite loop
54 54
Secure programming Example 2
Undefined behaviour (1) #include <limits.h>
int Example(void) {
Example 1 int b = INT_MAX-1;
int * varA = NULL; //line byte c;
1 a = (byte)b;
*varA = 0; //line if(b + 100 < b)
2 { return 1; }
return 2;
int varB; //line }
3 Example 3
int Add (int a, int
varA = &varB; //line
b)
4
{
return (a +
printf("%i\n", *varA) ; //line5
b);
printf("%i\n", varB) ; //line
6 }
Secure programming
Undefined behaviour (2)
int g = 0;
int main (void){
Int a = funcA() ;
Int b = funcB();
if(a > b)
/*………*/
}
int funcA (void){ g++;
return (g);}
int funcB (void) ){ g--;
return (g);}
56
Agenda
1. Introduction
2. Class and Object
3. Inheritance
4. Function signature, overloading, overriding
5. Constructor, Destructor
6. Copy constructor
7. Operator Overloading
8. Virtual Function, Template Function
58
1. Introduction
Additional Object-Oriented features to C
REMEMBER
C++ is C with classes adding object-oriented features, such as classes,
and other enhancements to the C programming language
8
2. Class and Object
REMEMBER
9
2. Class and Object
Circle, square, triangle are real
object. They are classfied as
“shape”
-> “Shape” is not real, it is just a Shape
definition
The variables is called member int x
data (attributes) int y
10
2. Class and Object
Start with keyword
“class”
Syntax
class Shape
“Shape” is class name
{
int x;
int y; x,y with type int is an
member data (attribute)
void Rotate();
void Sound(); “Rotate” and “Sound”
}; are 2 member functions
(methods)
Remember the
semicolon
11
2. Class and Object
“public” keyword is
class Shape an access specifier.
There are 3 type of
{
access specifiers:
public:
public
x
Synta
int x;
int y; protected
void Rotate(); private
void Sound();
};
REMEMBER
15
3. Inheritance
Coming back to the story, C++ provides better program
design: The same attributes,
Shape
functionality of circle,
int x square and triangle will
int y be put in Shape class.
void Rotate() When the requirement is
void Sound() updated. Just add class
Triangle and define new
member function inside it
Syntax
class Shape
{ specifier: one is for data
member; one is for
public:
inheritance.
int x;
int y;
void Rotate();
void Sound(); Name of derived class
};
18
3. Inheritance
Practice
REMEMBER
The access scope for data members/function of derived classed is
specify by mode of inheritance.
19
3. Inheritance
REMEMBER
21
4. Function signature, overloading, overriding
REMEMBER 02_inheritance_hiding_baseclass.cpp
22
5. Constructor
class Shape Constructor have the
{ same name with class
public: name
Shape(); Shape() is a constructor
int x;
int y; Constructor should be in
public access specifier
a
y
x
t
void Rotate();
REMEMBE
void Sound();
}; RConstructor is just a
member function. Its
If we do not have difference from other
? constructor, what will member function is
happened? that it is called
What is the purpose of automatically when the
? constructor? object is created.
23
5. Constructor
REMEMBER
The sequence when an object of derived class is created:
24
5. Destructor 02_inheritance_override.cpp
02_inheritance.cpp
class Shape Destructor have “~” and
{ the same name with
public: class name
~Shape(); ~Shape() is a destructor,
should be public.
int x;
int y; REMEMBE
R
a
y
x
t
Destructor is just a
void Rotate();
member function. Its
void Sound(); difference from other
}; member function is
that it is is called
If we do not have destructor,
? what will happened?
automatically when
the object is destroyed
What is the purpose of (out of scope/delete).
? destructor?
25
6. Copy constructor
class Shape Copy constructor syntax:
{ method has same name
public: of class. Parameter is
Shape(const Shape &
same type of class with
obj); constant reference
int x;
int y; REMEMBE
RCopy constructor is
a
y
x
t
called when copying
void Rotate(); an object content to
void Sound(); another object content
}; (during object
If we do not have copy initialization), like in
? constructor, what will this example:
happened? Shape myShape(2);
Shape yourShape(myShape);
What is the purpose of copy
? constructor?
Shape herShape= myShape;
func1(myShape);
26
7. Overloading operator
Does the object of CDate
? class support:
CDate today;
class CDate CDate tomorrow =
{ today++;
public:
int m_nDay;
d
h
o
e
e
a
c
t
int m_nMonth; REMEMBE
int m_nYear; R
… To use the operator on
} object , we need to
overload its operator.
27
7. Overloading operator
class CDate Prefix increment operator
{
public:
int m_nDay;
int m_nMonth;
int m_nYear;
CDate operator ++ void main()
() {
CDate operator ++ CDate today;
(int) today++;
} CDate tomorrow =
++today;
Postfix increment }
operator
28
7. Overloading operator 04_Operator1.cpp
29
7. Overloading operator
REMEMBE REMEMBE
ROperator can be Name ROperator cannot Name
overloaded be overloaded
++ Increment . Member selection
-- Decrement .* Pointer-to-member
selection
* Pointer dereference
:: Scope resolution
-> Member selection
?: Conditional ternary
! Logical NOT operator
& Address-of sizeof Gets the size of an
object/class type
~ One’s complement
+ or - Unary
plus/negation
Conversion, binary, Conversion, binary,
comparison, comparison,
subscript, function subscript, function
operators operators
30
8. Virtual function, polymorphism
Human
GoShopping(){
print(“Go shopping”) };
Girl Boy
public: GoShopping(){ public: GoShopping()
print(“I love it”) { print(“I hate
}; it”) };
virtual GoShopping(){
print(“Go shopping”) };
Girl Boy
public: GoShopping(){ public: GoShopping()
print(“I love it”) { print(“I hate
}; It”) };
REMEMBE Virtual keyword
R adds polymorphism
With polymorphism, you do not
need to know the alice and tom
are Boy or Girl. You just need to
know that they are Human.
33
8. Virtual function, polymorphism
Human
virtual GoShopping() = 0;
Girl Boy
public: GoShopping(){ public: GoShopping()
print(“I love it”) { print(“I hate
}; It”) };
REMEMBE Method without
R method . It implementation with
GoShopping is a virtual “=0”
becomes pure virtual method.
GoShopping method does not need
implementation. Human now
becomes an abstract class.
34
8. Virtual function, polymorphism 03_polymorphism_boy_girl.cpp
Human
virtual GoShopping(){
print(“Go shopping”) };
Girl alice;
Girl Boy Boy tom;
public: GoShopping(){
public: GoShopping(){
print(“I hate
Human& h1 = alice;
print(“I love it”) }; It”) }; Human& h2 = tom;
h1.GoShopping();
REMEMBE //I love it
R
Method 1 to apply h2.GoShopping();
polymorphism: //I hate it
A reference (base class type)
refers to an object of derived
class
35
8. Virtual function, polymorphism 03_01_Virtual.cpp
Human
virtual GoShopping(){
print(“Go shopping”) };
Girl alice;
Boy tom;
Girl Boy
public: GoShopping(){
Human* h1 =
public: GoShopping(){ print(“I hate &alice;
print(“I love it”) }; It”) };
Human* h2 = &tom;
REMEMBE h1->GoShopping();
R //I love it
Method 2 to apply h2->GoShopping();
polymorphism: //I hate it
A pointer of base class type
points to an address of an
derived class object.
36
8. Template Function
x
Synta
if (value1 > value2)
return value1;
else
return value2;
};
37
8. Template Class
template <typename T>
class CMyFirstTemplateClass
{
public:
x
Synta
void SetVariable (T& newValue) { m_Value = newValue; };
T& GetValue () {return m_Value;};
private:
T m_Value;
};
38
Recommended learning resources / references
The C++ Tutorial | Learn C++ (learncpp.com)
C++ Programming Language - GeeksforGeeks
C++ Programming Tutorials Playlist - YouTube
Example references:
Amazon.com: C++ in One Hour a Day, Sams Teach Yourself: 9780789757746: Rao, Siddhartha: B
ooks
Thank you!
89