embedded c c++ programming fundamentals master

110
Embedded C/C++ Programming Fundamentals Prepared by: Eng. Hossam Fadeel MSc

Upload: hossam-fadeel

Post on 14-Jul-2015

633 views

Category:

Engineering


9 download

TRANSCRIPT

Page 1: Embedded c c++ programming fundamentals master

Embedded C/C++ Programming Fundamentals

Prepared by:

Eng. Hossam Fadeel

MSc

Page 2: Embedded c c++ programming fundamentals master

When you see or hear something you

don’t recognize,please ask!

Page 3: Embedded c c++ programming fundamentals master

Good Textbooks Stuff

Page 4: Embedded c c++ programming fundamentals master

Good Textbooks Stuff

Page 5: Embedded c c++ programming fundamentals master

Good Textbooks Stuff

Embedded Systems Academy - Book Recommendationshttp://www.esacademy.com/en/library/book-recommendations.html

Page 6: Embedded c c++ programming fundamentals master

Good Websites Stuff• http://www.cplusplus.com/doc/tutorial/• http://www.tutorialspoint.com/cplusplus/cpp_overview.htm• http://www.cprogramming.com/tutorial/c++-tutorial.html• http://www.learncpp.com/• https://eewiki.net/display/microcontroller/Home• https://www.youtube.com/playlist?list=PLb7yniFBnvZIdfxYIKqNlGsT

f5oZy4dKk• https://www.youtube.com/playlist?list=PLb7yniFBnvZIb5L73SxP-

ot22gpZjezc_• https://www.youtube.com/playlist?list=PLAE85DE8440AA6B83• https://www.youtube.com/playlist?list=PLFF13C1031B9E2F43• https://www.youtube.com/playlist?list=PLAxDCCpR4lyGobK7wM6li

6FHoXSu5ePK9• https://www.youtube.com/channel/UCyHW1j2o7ckYtz-U4uhnC1g• https://www.youtube.com/channel/UCUNpxcO109gQx7yYxAtXHmA

Page 7: Embedded c c++ programming fundamentals master

Good Websites For Free Online Courses

Page 8: Embedded c c++ programming fundamentals master

Good Websites For Free Online Courses

Page 9: Embedded c c++ programming fundamentals master

Good Websites For Free Online Courses

Page 10: Embedded c c++ programming fundamentals master

Designing an Embedded System

with a Microcontroller

Page 11: Embedded c c++ programming fundamentals master

Typical Embedded System Architecture

Page 12: Embedded c c++ programming fundamentals master

Discussion

• What is an Embedded System?

• What is a Microcontroller?

PSoC and Other Micros

Page 13: Embedded c c++ programming fundamentals master

Microcontroller Development Tools

Page 14: Embedded c c++ programming fundamentals master

Microcontroller Development Tools

Page 15: Embedded c c++ programming fundamentals master

Basics of Designing a System

Page 16: Embedded c c++ programming fundamentals master

Parametric Aspects

• Power– Sleep modes– Voltage– Current

• Speed– Clock Frequency

• Reliability– Application demands

• Memory– Size– Type

• Familiarity– Personal Experience

• Available Kits– Evaluation– Development– Reference design

• Price– Device– Volume– Software tools

• IDE• Debug• Compilers• OS

• Support– Documentations

• White Papers• User Guides• Example Codes

– App engineers• Response Times

Page 17: Embedded c c++ programming fundamentals master

Parametric Aspects

Page 18: Embedded c c++ programming fundamentals master

Introduction to Programming Language

Prepared by:

Eng. Hossam Fadeel

Page 19: Embedded c c++ programming fundamentals master

What Is A programming Language?• An artificial language designed to communicate instructions

to a machine, particularly a computer.

• Can be used to create programs that control the behavior of a machine and/or to express algorithms precisely.

• Thousands of different programming languages have been created, mainly in the computer field, with many more being created every year.

Page 20: Embedded c c++ programming fundamentals master

Design Languages Flow

Software flow Hardware flow

Page 21: Embedded c c++ programming fundamentals master

Embedded Systems Programming

• A program is a set of instructions written in a specific sequence for a processor to accomplish specified tasks.

• An instruction is defined as a complete task (such as addition) performed by the microprocessor. Each microprocessor has its own set of instructions.

• To be intelligible to the microprocessor, instructions must be supplied in binary, i.e., as machine language.

• Assembler language is a symbolic language which represents instructions with short human-readable mnemonics. For example, in PIC assembler a null operation or ‘no operation’ is represented by the mnemonic ‘NOP’.

• An assembler is a software tool that converts assembler source programs into machine language object files.

– Assemblers contain built-in debugging tools which can detect syntax errors. – For example, ‘MPLAB’ is Microchip's PIC development environment which includes

an assembler that generates assembled files (object files) with .HEX extensions which are used to program PIC chips.

Page 22: Embedded c c++ programming fundamentals master

What is Assembly Language

• It is a low level Language

• It works directly with the microprocessor

– Each statement is [almost] exactly equivalent to one machine instruction.

• Embedded Systems depends on Assembly language

• It is the final product that produced by every compiler

Page 23: Embedded c c++ programming fundamentals master

Why assembly language

• Makes you a better programmer.

• There are some situation when you will have no option except assembly language.

– (Note: some high level programming language have expensive compilers).

– Also when you dealing with minimum resources and When you dealing with speed of program execution.

• Only assembly language can talk directly with the hardware.

Page 24: Embedded c c++ programming fundamentals master

From Machine to High-Level Languages

• Machine Language: binary instructions

– All programs are converted into the machine language of a processor for execution

– use the binary equivalent of the instructions

– Difficult to decipher and write

– Prone to cause many errors in writing

Machine Language

Assembly Language

High-level Language

Ex: 00 0111 0001 0101

Page 25: Embedded c c++ programming fundamentals master

From Machine to High-Level Languages

• Assembly Language: machine instructions represented in mnemonics

– Has one-to-one correspondence with machine instructions

– A program called Assembler converts to machine code

– Efficient in execution and use of memory; machine-specific and not easy to troubleshoot

– Rather slow and inefficient for large and complex programs

Machine Language

Assembly Language

High-level Language

Ex: MOV [90h], 05h

Page 26: Embedded c c++ programming fundamentals master

From Machine to High-Level Languages

• High-Level Languages (such as BASIC, C, and C++)

– Written in statements of spoken languages (such as English)

• machine independent (Can be reuse for other platforms)

• A program called Compiler converts to machine code

• easy to write and troubleshoot

• requires large memory and less efficient in execution

Machine Language

Assembly Language

High-level Language Ex: for (i=0; i<10; i++) sum += a[i];

Page 27: Embedded c c++ programming fundamentals master

Compiler

Page 28: Embedded c c++ programming fundamentals master

Source File:

Compiler Compiler

File1.C File2.C File3.asm

Assembler

Object Object Object

Linker

Relocatable

Locator

Hex fileProgram target

with programmer

Programmed target

Running embedded

program

Information about the memory of the system

combines files and any referenced functions from the libraries

Page 29: Embedded c c++ programming fundamentals master

C Compiler

Assembly

code

Assembler

Object code

C

code

Page 30: Embedded c c++ programming fundamentals master

Program Development Process

Write Source Code

Assembler/Compiler

Simulate (If available)

Download

Test Your Hardware

Page 31: Embedded c c++ programming fundamentals master

Revision on Embedded Programming• Key Points in Embedded Programming:

– Code Speed: • Timing constraints

• Limited Processing Speeds (Your microcontroller is not a 2.5 GHz processor)

– Code Size:• Limited memory (you have limited memory)

• Programming Methods– Machine Code: Bit (0,1)

– Low level language: Assembly

– High level language: C

• Why use C in embedded programming?– Fairly efficient

– Supports access to I/O

– Ease of management of large embedded projects

• Why use assembly?– High speed, low code size

– However, difficult to do a large project in assembly

Page 32: Embedded c c++ programming fundamentals master

Introduction to C/C++ for ES

Page 33: Embedded c c++ programming fundamentals master

Introduction• Before you begin …

– C is a general-purpose programming language.

– C is a high-level language that has the advantages of readability, maintainability, and portability, reusability.

– C is a very efficient language that allows you to get control of computer hardware and peripherals.

– C is a small language that you can learn easily in a relatively short time.

– The ANSI standard for C is the standard supported by all C compiler vendors to guarantee the portability of C.

– Well Structured Language ( i.e. Main function calls many other functions )

– C Language is the common language used in microcontrollers ,embedded systems and other hardware applications.

– Finally , UNIX Operating system is written with C Language

Page 34: Embedded c c++ programming fundamentals master

C++ for Embedded Systems

• Of higher level languages, C++ is the closest to assembly languages

– bit manipulation instructions

– pointers (indirect addressing)

• Most microcontrollers have available C++ compilers

• Believe it or not, it is just ordinary C++ with little additions !

Page 35: Embedded c c++ programming fundamentals master

Advantages over assembly language

• Knowledge of the processor instruction set is not required (portable code; suitable for any µP).

• Register allocation and addressing of memory and data is managed by the compiler.

• Programs get a formal structure and can be divided into separate functions (Reusable code).

• Test time is drastically reduced, this increases efficiency.

• C libraries contain many standard routines such as numeric conversions.

Page 36: Embedded c c++ programming fundamentals master

Assembly versus C

The selection depends on:Project: Small or largeResources: Memory(RAM and ROM)Time to market: short or longUpdating of program: Yes or No.………………………………….etc

Page 37: Embedded c c++ programming fundamentals master

C++ Coding Standards• Program writing is like building a house.

• The following recommendations were taken from a C++ Standards document and have been adapted for the Embedded C++.– Names- make them fit their function

• Use mixed case names to improve the readability:

ErrorCheck is easier than ERROCHECK or errorcheck

• Prefix names with a lowercase letter of their type also to improve the readability

g Global gLog

r Reference rStatus();

s Static sValueIn;

– Braces {} : May be written like this If (condition) {…………………….}Or preferred methodIf (condition){…………………….}

Page 38: Embedded c c++ programming fundamentals master

C Program Structure

• A C program is built from three components:

1. Directives are directives handled directly by the preprocessor (#include ….. )

2. Declarations are instructions for the compiler to record the type and associated memory locations of symbols

3. Statements are the executable instructions in a program

Page 39: Embedded c c++ programming fundamentals master

The Structure of C Program• Preprocessor directive

– The preprocessor goes through a program and prepares it to be read by the compiler.

– Any line in source code with a leading # is taken as a preprocessing directive

– The two most common preprocessor directives are : #define, #include and #pragma

• Declarations– Establishes the names of variables, functions and types used in the

program.

– Have global variables and local variables

Page 40: Embedded c c++ programming fundamentals master

The Structure of C Program– Definition

• Establishes the contents of a variable or function. Ex: X = 10;

– Expression• It is a combination of operators and operands that yields a single

value.

• Ex: X = A – B ;

Y =3 + C * 2 ;

– Statement• Control the flow of program execution.

• Ex:while (PRTxDR == 0x02)

{ // statements}

if (counter == 10){

// statements}

Page 41: Embedded c c++ programming fundamentals master

The Structure of C Program• Function

– It is a collection of declarations, definitions, expressions and statements that perform a specific task.

– Ex: C function declaration

#pragma fastcall16 send_byte

void send_byte( char val);

• Main function: – all C program must contain a function named main where program

execution begin.

Page 42: Embedded c c++ programming fundamentals master

General C/C++ Program Structure

42

Comments are set between /* and */ or //

Page 43: Embedded c c++ programming fundamentals master

General C/C++ Program Structure

43

The C pre-processor replaces this directive with the contents of the m8c.h and PSoCAPI.h headers file from the C library.

Page 44: Embedded c c++ programming fundamentals master

General C/C++ Program Structure

44

Every C program must have one main function and may contain additional functions as well.

Page 45: Embedded c c++ programming fundamentals master

General C/C++ Program Structure

45

Each variable must be explicitly defined as a specific type.

Page 46: Embedded c c++ programming fundamentals master

Starting to write programs

whenever this constant will repeated

The return statement causes the main function to finish

Page 47: Embedded c c++ programming fundamentals master

Variables in C

• An important aspect of the C language is how it stores data.

• Here we will discuss:

– Data types

– Declarations

– Assignments

– Data type ranges

– Type conversions

Page 48: Embedded c c++ programming fundamentals master

Variables in C• The following table shows the meaning of the basic data types

and type modifiers:Type Meaning Modifier

Character Character data char

Integer Signed whole numbers int

Float Floating point numbers float

Double Double precision floating point numbers double

Signed Positive and negative numbers signed

Unsigned Positive only numbers unsigned

Long Double the length of a number long

Short Halves the length of a number short

C represents all negative numbers in the 2’s complement format. For example to convert the signed number 29 into 2’s complement:

Page 49: Embedded c c++ programming fundamentals master

Data typesType Bit width Description Range

bit 1 To define a bit of data 0 - 1

Char 8 Character or small integer. signed: -128 to 127unsigned: 0 to 255

Short Int 16 Used to define integer numbers signed: -32768 to 32767unsigned: 0 to 65535

Long int 32 Used to define integer numbers signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295

Float 32 Define floating point number 1.175e-38 to 3.40e+38

Double 32 Used to define largest integer numbers

1.175e-38 to 3.40e+38Note: in other C ref 64 bit

bool 8 Boolean value. true or false

* (pointer) width of memory

Use for addressing memory Range of memory

For more details refer to “C Language Compiler User Guide”

Page 50: Embedded c c++ programming fundamentals master

Variable Declaration• Variables can be declared inside a function or outside of all

functions.

• Variables are declared as following:

• Global variables are declared outside functions and are visible from the end of declaration to the end of the file.

• Local variables are declared inside a function and is visible only from the end of declaration to the end of the function.

type variable_name; Ex: float price;

Where type is one of C’s valid data types and variable_name is the name of the variable.

Page 51: Embedded c c++ programming fundamentals master

Variable Assignment• Assignment of values to variables is simple:

• Since a variable assignment is a statement, we have to include the semicolon at the end.

• Example:– count =100;

– Int x=10;

– float PI=3.14;

• typedef: used to create a new name for an exsisting type.

– Example:

variable_name = value ;

typedef old_name new_name

Page 52: Embedded c c++ programming fundamentals master

Variable Assignment

• typedef are typically used for two reasons:

1. To create portable programs. (to make program works on Different

μP data width bus)

2. help to document your code. (If your code contains many variables

used to hold a count of some sort)

typedef short int myint; // int 8-bit for 8-bit processor

typedef int counter;

typedef int myint; // int 16-bit for 16-bit processor

Someone reading your code would recognize that any variable declared as counter is used as a counter in the program.

Page 53: Embedded c c++ programming fundamentals master

Type conversions (casting/parsing)– To convert from long to int the programmer has to manually type

cast the value

– To do type casting, the value to cast has to be preceded by the target type enclosed in parantheses

int Val16bit; // short integer (16 bits)long Val32bit; // long integer (32 bits)Val16bit = (int) Val32bit; // type casting

// the higher 16 bits are lost

– Information may be lost by type casting

– The range of a value should be checked before doing manual type casting

(type) value

Page 54: Embedded c c++ programming fundamentals master

Variable Storage Class• auto

– The auto specifier indicates that the memory location of a variable is temporary.

– auto is the default for function/block variables

• auto int a is the same as int a because it is the default, it is almost never used

• extern– Declares a variable that is defined somewhere else.

– Useful when splitting software in multiple files.

Page 55: Embedded c c++ programming fundamentals master

Variable Storage Class• static

– Variable stored in static memory.

– It retain their previous value on re-entry to a block of code. So it eat up your memory.

– In the example the variable count is initialized once and thereafter increment every time the function test is called.

• register– used to define local variables that should be

stored in a register instead of RAM (variable should be stored in a processor register).

– Register should only be used for variables that require quick access

The storage class is optional – if not specified the compiler uses a default storage class.

Page 56: Embedded c c++ programming fundamentals master

Operators• An expression is a combination of operators and operands.

• Operators act on operands.

• Types of operators: – Arithmetic Operators

– Logical (or Relational) Operators

– Bitwise Operators

– Assignment Operators

– Precedence of operators

Page 57: Embedded c c++ programming fundamentals master

Operators• Arithmetic Operators:

– Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiply both operands A * B will give 200

/ Divide numerator by denumerator B / A will give 2

% Modulus Operator and remainder of after an integer division

B % A will give 0

++ Increment operator, increases integer value by one A++ will give 11

-- Decrement operator, decreases integer value by one A-- will give 9

Page 58: Embedded c c++ programming fundamentals master

Operators• Logical (or Relational) Operators:

– Assume variable A holds 10 and variable B holds 20 thenOperator Description Example

== Checks if the value of two operands is equal or not, if yes then condition becomes true.

(A == B) is not true.

!= Checks if the value of two operands is equal or not, if values are not equal then condition becomes true.

(A != B) is true.

> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.

(A > B) is not true.

< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.

(A < B) is true.

>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.

(A >= B) is not true.

<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.

(A <= B) is true.

&& Called Logical AND operator. If both the operands are non zero then then condition becomes true.

(A && B) is true.

|| Called Logical OR Operator. If any of the two operands is non zero then then condition becomes true.

(A || B) is true.

! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

!(A && B) is false.

Page 59: Embedded c c++ programming fundamentals master

Operators• Bitwise Operators:

– Bitwise Operators: Bitwise operator works on bits and perform bit by bit operation.

– Assume if A = 60; and B = 13; Now in binary format they will be as follows: A = 0011 1100 , B = 0000 1101

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in both operands.

(A & B) will give 12 which is 0000 1100

| Binary OR Operator copies a bit if it exists in eather operand. (A | B) will give 61 which is 0011 1101

^ Binary XOR Operator copies the bit if it is set in one operand but not both.

(A ^ B) will give 49 which is 0011 0001

~ Binary Ones Complement Operator is unary and has the efect of 'flipping' bits.

(~A ) will give -60 which is 1100 0011

<< Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.

A << 2 will give 240 which is 1111 0000

>> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.

A >> 2 will give 15 which is 0000 1111

Page 60: Embedded c c++ programming fundamentals master

Operators• Assignment Operators

Operator Description Example

= Simple assignment operator, Assigns values from right side operands to left side operand

C = A + B will assigne value of A + B into C

+= Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand

C += A is equivalent to C = C + A

-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand

C -= A is equivalent to C = C -A

*= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand

C *= A is equivalent to C = C * A

/= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand

C /= A is equivalent to C = C / A

%= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand

C %= A is equivalent to C = C % A

<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator C &= 2 is same as C = C & 2

^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2

|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2

Page 61: Embedded c c++ programming fundamentals master

Flow of Control, Conditional Constructs, Loops

This session will make you advance to control your code so control your world. The goal is to take you from the basic to learn more about Conditional Constructs and loops.

Page 62: Embedded c c++ programming fundamentals master

C - Flow Control Statements• Flow Control – Making the program behave in a particular

manner depending on the input given to the program

• Why do we need flow control?– Not all program parts are executed all of the time( i.e. we want the

program to intelligently choose what to do).

• Topics will discussed here are:– If

– If-else

– For

– While

– Do-while

– Nesting loops

– Switch

Page 63: Embedded c c++ programming fundamentals master

IF statement• The if else statement decides on an action based

on if being true

• The form of the statements is– IF (condition1)

{

Statements1;

}

Else if (condition2)

{

Statements2;

}

Else

{

Statements3;

}

Page 64: Embedded c c++ programming fundamentals master

SWITCH statement• The switch case statement Compares a single

variable to several possible constants

• The form of the statements is– Switch (variable)

{

Case value1:

Statements1;

Break;

Case value2:

Statements2;

Break;

Default:

Statements3;

Break;

}

Page 65: Embedded c c++ programming fundamentals master

WHILE statement

• The while statement tests a certain condition and repeats a set of statements until the condition is false

• The for of the statement

– While(condition)

{

statements;

}

Page 66: Embedded c c++ programming fundamentals master

DO statement

• The Do while statement is same as while, except the test runs after execution of a statement, not before

• The form of the statement

– Do

{

statements

}

while(condition)

Page 67: Embedded c c++ programming fundamentals master

FOR statement

• The For statement Executes a limited loop.

• The form of the statement

– For(initial value ; condition ; change)

{

Statements;

}

Page 68: Embedded c c++ programming fundamentals master

CONTINUE statement

• The Continue statement skip the rest of the statements in the current loop

• The form of the statement

– Continue;

No Print for Value 5 Where it Skipped

Page 69: Embedded c c++ programming fundamentals master

BREAK statement

• The Break statement is Used with a switch or in a loop to terminate the switch or loop

• The form of the statement is

– Break;

Page 70: Embedded c c++ programming fundamentals master

GOTO statement

• Goto statement Transfers execution to a label

• The form of the statement is:

– goto label ;

Page 71: Embedded c c++ programming fundamentals master

Functions• Using functions we can structure our programs in a more

modular way.

• A function is a group of statements that is executed when it is called from some point of the program. The following is its format:– type name ( parameter1, parameter2, ...) { statements }

Page 72: Embedded c c++ programming fundamentals master

Functions

• Functions with no type. The use of void.

Page 73: Embedded c c++ programming fundamentals master

The compiler preprocessor• Compilers translate high level programming language

instructions into machine language.

• Three different components are responsible for changing C instructions into their machine language equivalents.1. Preprocessor

2. Compiler

3. Linker

• The Preprocessor: – The preprocessor goes through a program and prepares it to be read

by the compiler.

– C Preprocessor Directives• #include directives include the contents of another file

• #define directives define symbolic constants

• #pragma directives describe details of the target hardware

Page 74: Embedded c c++ programming fundamentals master

Calling Assembly Functions From C• There are 4 conditions to meet when using the fastcall16 interface:

– The function must be tagged with a C #pragma fastcall16 directive.

– The function should have a C function prototype.

– The assembly function name must be the C function name prefixed with an underscore character (_).

– The assembly function name must be exported

• For example, an assembly function that is passed a single byte as a parameter and has no return value looks like this:

Page 75: Embedded c c++ programming fundamentals master

Inline Assembly• Besides writing assembly functions in assembly files, inline

assembly allows you to write assembly code within your C file.

• The syntax for inline assembly is:– asm ("<string>");

• For example:– asm ("mov A,5");

Page 76: Embedded c c++ programming fundamentals master

Interrupts• Interrupt handlers can be written in C. In order to employ

them, you must first inform the compiler that the function is an interrupt handler.– #pragma interrupt_handler <name>

• For an interrupt function, the compiler generates the retiinstruction instead of the ret instruction, then saves and restores all registers used in the function.

• For example:

#pragma interrupt_handler timer_handler...void timer_handler(){...}

Page 77: Embedded c c++ programming fundamentals master

Library Functions• Use #include <associated-header.h> for each function

described in the Library Functions.

• ImageCraft C Compiler Guide page 23.– String Functions

– Mathematical Functions

– API Software Library Functions

Page 78: Embedded c c++ programming fundamentals master
Page 79: Embedded c c++ programming fundamentals master
Page 80: Embedded c c++ programming fundamentals master
Page 81: Embedded c c++ programming fundamentals master

• LAB 1_a: Using LCD to Print “Hello World”.

• LAB 1_b: Using LCD to Print and Flash “Hello World” every 2 sec.

• LAB 1_c: Using LCD to Print “Hello World” when pressing button.

• LAB 4: Using LCD to Print Mathematical Operations “Addition: X+Y = Z” then “Abstraction: X-Y = Z” then “ Multiplication: X*Y = Z” then “ Division: X/Y = Z”.

• LAB 5: Using Conditional Statements and buttons combination to Print Mathematical Operations “Addition: X+Y = Z” then “Abstraction: X-Y = Z” then “ Multiplication: X*Y = Z” then “ Division: X/Y = Z”.

• LAB 6: Make delay of 1 sec using assembly (inline assembly and calling assembly function).

• LAB 7: Do Some thing continually and when press a button make interrupt that Prints “I am Interrupt)

Page 82: Embedded c c++ programming fundamentals master

Advanced C Topics

Page 83: Embedded c c++ programming fundamentals master

Arrays• An array is a series of elements of the same type placed in contiguous

memory locations that can be individually referenced by adding an index to a unique identifier.

int foo [5] = { 16, 2, 77, 40, 12071 };

int bar [5] = { 10, 20, 30 };

int baz [5] = {};

Page 84: Embedded c c++ programming fundamentals master

Arrays

• Accessing the values of an array

foo [2] = 75; x = foo[2]; 12

int foo[5]; // declaration of a new arrayfoo[2] = 75; // access to an element of the array.

Some other valid operations with arrays: 1234

foo[0] = a; foo[a] = 75; b = foo [a+2]; foo[foo[a]] = foo[2] + 5;

Page 85: Embedded c c++ programming fundamentals master

Multidimensional arrays• Multidimensional arrays can be described as "arrays of arrays".

• Think of it as [row][col]

• Example:

int jimmy [3][5];

The way to reference the second element vertically and fourth horizontally in an

expression would be:jimmy[1][3]

Page 86: Embedded c c++ programming fundamentals master

Initializing Arrays

Can initialize an array just like a normal variable

Example:

String

char szTemp[] = “Some string”;

Values

int nTemp[] = {5,15,20,25};

Letters

char szTemp[] = {‘A’,’B’,’C’,’D’};

Double Dimensioned

char szTemp[2][] = { {‘A’,’B’,’C’,’D’,’E’},

{‘U’,’V’,’X’,’Y’,’Z’} };

Page 87: Embedded c c++ programming fundamentals master

Pointers• Variables have been explained as locations in the memory which can be

accessed by their identifier (their name).

– This way, the program does not need to care about the physical address of the data in memory.

• The memory is like a succession of memory cells, each one byte in size, and each with a unique address.

– These single-byte memory cells are ordered in a way that allows data representations larger than one byte to occupy memory cells that have consecutive addresses.

– Each cell can be easily located in the memory by means of its unique address.

• When a variable is declared, the memory needed to store its value is assigned a specific location in memory (its memory address).

• Generally, C++ programs do not actively decide the exact memory addresses where its variables are stored.

Page 88: Embedded c c++ programming fundamentals master

Pointers• Address-of operator (&)

– The address of a variable can be obtained by preceding the name of a variable with an ampersand sign (&), known as address-of operator. For example:

– This would assign the address of variable myvar to foo; by preceding the name of the variable myvar with the address-of operator (&), we are no longer assigning the content of the variable itself to foo, but its address.

– The actual address of a variable in memory cannot be known before runtime.

foo = &myvar;

Page 89: Embedded c c++ programming fundamentals master

Pointers– let's assume, in order to help clarify some concepts, that myvar is placed

during runtime in the memory address 1776.In this case, consider the following code fragment:

– The values contained in each variable after the execution of this are shown in the following diagram:

myvar = 25;foo = &myvar; bar = myvar;

First, we have assigned the value 25 to myvar (a variable whose address in memory we assumed to be 1776).

The second statement assigns foo the address of myvar, which we have assumed to be 1776.

Finally, the third statement, assigns the value contained in myvar to bar.

Page 90: Embedded c c++ programming fundamentals master

Pointers• Dereference operator (*)

– As just seen, a variable which stores the address of another variable is called a pointer. Pointers are said to "point to" the variable whose address they store.

– An interesting property of pointers is that they can be used to access the variable they point to directly. This is done by preceding the pointer name with the dereference operator (*). The operator itself can be read as "value pointed to by".

– Therefore, following with the values of the previous example, the following statement:

– This could be read as: "baz equal to value pointed to by foo", and the statement would actually assign the value 25 tobaz, since foo is 1776, and the value pointed to by 1776 (following the example above) would be 25.

baz = *foo;

It is important to clearly differentiate that foo refers to the value 1776, while *foo (with an asterisk * preceding the identifier) refers to the value stored at address 1776, which in this case is 25.

Page 91: Embedded c c++ programming fundamentals master

Pointers• Notice the difference of including or not including

the dereference operator

• The reference and dereference operators are thus complementary:– & is the address-of operator, and can be read simply as "address of"

– * is the dereference operator, and can be read as "value pointed to by"

baz = foo; // baz equal to foo (1776)baz = *foo; // baz equal to value pointed to by foo (25)

Page 92: Embedded c c++ programming fundamentals master

Pointers• Declaring pointers

– Due to the ability of a pointer to directly refer to the value that it points to, a pointer has different properties when it points to a char than when it points to an int or a float.

– Once dereferenced, the type needs to be known. And for that, the declaration of a pointer needs to include the data type the pointer is going to point to.

– The declaration of pointers follows this syntax: type * name;

where type is the data type pointed to by the pointer. This type is not the type of the pointer itself, but the type of the data the pointer points to. For example:

int * number;char * character; double * decimals;

Page 93: Embedded c c++ programming fundamentals master

Pointers• Let's see an example on pointers:

Notice that even though neither firstvalue nor secondvalue are directly set any value in the program, both end up with a value set indirectly through the use of mypointer. This is how it happens:

First, mypointer is assigned the address of firstvalue using the address-of operator (&). Then, the value pointed to bymypointer is assigned a value of 10. Because, at this moment, mypointer is pointing to the memory location offirstvalue, this in fact modifies the value of firstvalue.

Page 94: Embedded c c++ programming fundamentals master

Pointers• Another Example

Each assignment operation includes a comment on how each line could be read: i.e., replacing ampersands (&) by "address of", and asterisks (*) by "value pointed to by".

Notice that there are expressions with pointers p1 and p2, both with and without the dereference operator (*). The meaning of an expression using the dereference operator (*) is very different from one that does not. When this operator precedes the pointer name, the expression refers to the value being pointed, while when a pointer name appears without this operator, it refers to the value of the pointer itself (i.e., the address of what the pointer is pointing to).

Page 95: Embedded c c++ programming fundamentals master

Pointers and Arrays

int myarray [20]; int * mypointer;

mypointer = myarray;The following assignment operation would be valid:

After that, mypointer and myarray would be equivalent and would have very similar properties. The main difference being that mypointer can be assigned a different address, whereas myarray can never be assigned anything, and will always represent the same block of 20 elements of type int. Therefore, the following assignment would not be valid: myarray = mypointer;

The main difference being that pointers can be assigned new addresses, while arrays cannot.

Page 96: Embedded c c++ programming fundamentals master

Pointer initialization• Pointers can be initialized to point to specific locations at the

very moment they are defined:

• When pointers are initialized, what is initialized is the address they point to (i.e., myptr), never the value being pointed (i.e., *myptr).

int myvar; int * myptr = &myvar;

Page 97: Embedded c c++ programming fundamentals master

Pointer arithmetics

char *mychar; short *myshort; long *mylong;

Suppose now that we define three pointers in this compiler:

and that we know that they point to the memory locations 1000, 2000, and 3000, respectively.

Therefore, if we write:

++mychar; ++myshort; ++mylong;

mychar, as one would expect, would contain the value 1001. But not so obviously, myshort would contain the value 2002, and mylong would contain 3004, even though they have each been incremented only once. The reason is that, when adding one to a pointer, the pointer is made to point to the following element of the same type, and, therefore, the size in bytes of the type it points to is added to the pointer.

Page 98: Embedded c c++ programming fundamentals master

To Continue Go to

http://www.cplusplus.com/doc/tutorial/pointers/

Page 99: Embedded c c++ programming fundamentals master

PSoC® 1 - Dynamic Reconfiguration with PSoC® Designer™

Page 100: Embedded c c++ programming fundamentals master

Introduction• Dynamic reconfiguration is a unique feature of PSoC Designer

that allows a designer to easily create a project that uses more resources of the chip than are statically available. – This is done by time multiplexing the resources inside of a PSoC Chip.

• Every programmable semiconductor device, including PSoC 1, has limited resources. However, the technique of dynamic reconfiguration developed by Cypress allows PSoC 1 devices to reuse analog and digital resources to achieve greater levels of functionality.

• Only one function may be active at any point in time.

Page 101: Embedded c c++ programming fundamentals master

Introduction• The PSoC Designer software development tool allows a user

to easily implement dynamic reconfiguration in firmware.

• Multiple hardware configurations for the device are defined with an intuitive graphical user interface (GUI).

• A user switches between and interacts with these hardware configurations at a firmware API level.

Page 102: Embedded c c++ programming fundamentals master

Creating Configurations in PSoC Designer

After a loadable configuration is added, a new folder appears under Loadable

Configurations.

Page 103: Embedded c c++ programming fundamentals master

Guidelines for Configuration Organization

Base Configuration First Overlay Configuration Second Overlay Configuration

Page 104: Embedded c c++ programming fundamentals master

Guidelines for Configuration Organization

Third Overlay Configuration Fourth Overlay Configuration

Page 105: Embedded c c++ programming fundamentals master

Configuration Purposes

Page 106: Embedded c c++ programming fundamentals master

Dynamic Reconfiguration API Functions

The functions that are primarily used are the LoadConfig and

UnloadConfig functions. These are used to load and unload overlay

configurations.

Page 107: Embedded c c++ programming fundamentals master

Dynamic Reconfiguration Software Flow

Page 108: Embedded c c++ programming fundamentals master

File Changes and Dynamic Reconfiguration

• There are files that are generated for a project when dynamic reconfiguration is activated by adding an overlay to a project.

• The psocdynamic.asm file adds one function for each configuration in the project. Each function is named Is[ConfigName]Loaded. An array of bytes in RAM is declared when dynamic reconfiguration is used in a project.

• This array of bytes is named ACTIVE_CONFIG_STATUS. It is declared near the bottom of the psocconfig.asm file. Each bit of each byte corresponds to one of the configurations. If the corresponding bit is HIGH, the configuration is loaded. If it is LOW, the configuration is not loaded.

Page 109: Embedded c c++ programming fundamentals master

File Changes and Dynamic Reconfiguration

• The psocdynamicint.asm file determines how interrupts are handled when using dynamic reconfiguration. This is explained in Appendix C: Interrupts and Dynamic Reconfiguration..

• The psocdynamic.h file exports all dynamic reconfiguration functions for use in C code. Each configuration gets three functions that are exported in the file as follows:

Code 1. Exported C Function Declarations

extern void LoadConfig_an2104( void);

extern void UnloadConfig_an2104( void);

extern char Isan2104Loaded( void);

Page 110: Embedded c c++ programming fundamentals master