introduction to embedded c progrmming

Download Introduction to Embedded C Progrmming

If you can't read please download the document

Upload: veerakumars

Post on 17-Aug-2015

224 views

Category:

Documents


0 download

DESCRIPTION

Embedded C Programming

TRANSCRIPT

Chapter 3Microcontroller System SoftwareDevelopmentAssoc. Professor Dr. Rosbi bin [email protected]

Dept. of Control & Mechatronics EngineeringFaculty of Electrical EngineeringUniversiti Teknologi Malaysia

3.1 Software Development ProcessSoftware development process for embeddedsystems

Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.1/46

3.2 Arduino Software DevelopmentSoftware development tools for Arduino Integrated Development Environment (IDE)Arduino IDE (on PC)

Target Hardware

Text Editor,GNU C compiler + Assembler+ Linker + Locator

USB cable

Machine Code+Bootloader

Serial Monitor(debugging)

c 2013 Dr. Rosbi Mamat p.2/46

Microcontroller (SEL4533)

3.2 Arduino Software DevelopmentSource codes to machine code translation usingArduino IDEYour source filemyprog.ino

Arduino & Wiringlibraries

+

GNU Clibraries

GNU C compiler + Assembler+ Linker + Locator

Machine CodeMicrocontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.3/46

3.2 Arduino Software DevelopmentArduino IDECompileUpload

Open

Serial Monitor

SaveArea for Writing Program(source code editor)

Area for Error Messages

c 2013 Dr. Rosbi Mamat p.4/46

Microcontroller (SEL4533)

3.3 Arduino Programming LanguageArduino language is based on C/C++ language wewill review the C language.The basic stucture of an Arduino program:comments

function namefunctionstartfunction bodyfunction endMicrocontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.5/46

3.3 Arduino Programming LanguageEach Arduino program must have at least 2functions:setup() is the 1st thing run in the Arduinoprog. This is where things that need to beinitialized should be placed. setup() run once &only once.loop() contains anything that needs to runrepeatedly in the prog. Any instructions in loop()will be run repeatedly until the prog is stopped.

Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.6/46

3.4 A Brief Review of C languageA C program consists of :functions to be executedvariables declaration, definition or allocationC functionssimilar to ASM subroutines or Pascal proceduresa function contains statements that specify thecomputing operations to be done & variablesdeclaration for storing data. Function body areenclosed in braces { }main is a special function program execution beginsat main.

Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.7/46

3.4 A Brief Review of C languageC functionsWhere is the main() function in Arduino progs?In Arduino, main is defined internally you do notneed to write the mainint main(void){:setup();for (;;) {loop();:}return 0;}

Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.8/46

3.4 A Brief Review of C languageCommentsany characters between /* & */ are ignored bycompileranything after // until end of lineblank lines are ignored by compiler

Preprocessor instructionsuse to include the contents of other files with#include or #include ".."use to define constants & macros with #define ...

Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.9/46

3.4 A Brief Review of C languageC variables & data typesvariables are used to store dataall variables must be declared before they are used.Declaration consists of a data type & the symbolic namefor variable:int ADCreading; /*var ADCreading store integer value */float ctrsignal; /* var ctrsignal store real value */

signed int data types for variablesData Types

Size (bytes)

Ranges

char

1

-128 +127

int

2

-32768 +32767

short

2

-32768 +32767

long

4

-2147483648 +2147483647

c 2013 Dr. Rosbi Mamat p.10/46

Microcontroller (SEL4533)

3.4 A Brief Review of C languageC variables & data typesunsigned int data types for variablesData Types

Size (bytes)

Ranges

unsigned char

1

0 255

unsigned int

2

0 65535

unsigned long

4

0 4294967295

real data types for variablesData Types

Size (bytes)

Ranges

float

4

1.18 1038 3.4 1038

double

8

9.46 10308 1.79 10308

Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.11/46

3.4 A Brief Review of C languageConstant numbers in CConstant TypesExamplesDecimal number65Long Decimal number65LHexadecimal number0x41 or 0X41Octal number0101CharacterAReal number65.0, 65E0, 650E-1

Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.12/46

3.4 A Brief Review of C languageCharacter constant in C (must be enclosed in ):

Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.13/46

3.4 A Brief Review of C languageIdentifier symbolic names given to variables,functions, constants or labels.Valid identifier must:start with a letter or underscore (_)consists of letters, numbers or _ onlynot one of these C keywords:

C identifier is case sensitive !autobreakcasecharconstcontinuedefaultdodoubleelseenumMicrocontroller (SEL4533)

externfloatforgotoifintlongregisterreturnshortsigned

ADCreading , adcreading

sizeofstaticstructswitchtypedefunionunsignedvoidvolatilewhilec 2013 Dr. Rosbi Mamat p.14/46

3.4 A Brief Review of C languageC statementsspecify actions to be performed, such as assignmentoperation or function calls.are free-form i.e. can start & finish at any columnmust be terminated with semicolon (;)are executed in sequenceblock of statements are enclosed in { & } & notterminated by a semicolona statement with only a semicolon is an empty statement& does not peform any operationfor (i = 0; i < 100; i++);/* empty statement */Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.15/46

3.4 A Brief Review of C languageArithmetic operators

Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.16/46

3.4 A Brief Review of C languageRelational operators

Assignment operators

Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.17/46

3.4 A Brief Review of C languageBitwise operators

Logical operators

Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.18/46

3.4 A Brief Review of C languageMemory accessing operators

Other operators

Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.19/46

3.4 A Brief Review of C languageProgram control structures for decision making &controlling program flow such as doing selections,iterations & loops.if . . . else creates conditional jumpTRUE

FALSEcondition?if (condition)statements; TRUEstatements

FALSEcondition?

if (condition)statementT;elsestatementF; statementT

statementF

condition = 0 FALSE, condition , 0 TRUEc 2013 Dr. Rosbi Mamat p.20/46

Microcontroller (SEL4533)

3.4 A Brief Review of C languageif . . . else if . . . else for multiple alternativesconditional jumpsif (condition1)statement1;else if (condition2)statement2;else if (condition3)statement3;:elsestatementn;switch (condition){case condition1:statement1; break;case condition2:statement2; break;case condition3:statement3; break;default:statementn;}Microcontroller (SEL4533)

TRUEcondition1?

statement1

FALSETRUEcondition2?

statement2

FALSETRUEcondition3?

statement3

FALSEstatementn

c 2013 Dr. Rosbi Mamat p.21/46

3.4 A Brief Review of C languageIteration & loops with while & do . . . while:while (condition){statement1;statement2;:statementn;}

FALSEcondition?TRUEstatements

do{

statements

statement1;statement2;:statementn;} while (condition)

condition?TRUEFALSE

c 2013 Dr. Rosbi Mamat p.22/46

Microcontroller (SEL4533)

3.4 A Brief Review of C languageSyntax of for loop:Initializationpart

Update part

for (expr_init; condition; expr_update)statementsConditionalpart

Actions of for keyword:Initialization part is executed once at the start of theloopConditional part is tested, if TRUE the statements areexecutedUpdate part is executed at the end of each loop iterationMicrocontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.23/46

3.4 A Brief Review of C languagefor loop:initializationfor (expr_init; condition; expr_update)statements

condition?

FALSE

TRUE

||expr_init;while (condition){statementsexpr_update;}

statements

update

c 2013 Dr. Rosbi Mamat p.24/46

Microcontroller (SEL4533)

3.4 A Brief Review of C languageC functionsGeneral form of a functionoutput_type name (par_type parameters){statementsreturn(out_value);}

parameters

:

name

output/return value

output_type the type of the functions returnvalue/ouput (int, char, float etc.). If no outputkeyword void is used.name is the name of the function. Follow the rules foridentifier for writing name.Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.25/46

3.4 A Brief Review of C languageC functionspar_type parameters the declaration of variablesthat are passed to the function to do the work. If morethan 1 parameters, separate them with ,.If the output_type is not void, the last statement in thefunction is return(out_value).Example:./* calc the area of a rectangle */float calc_area_rect (float width, float length){float area;area = width * length;return(area);}void main(void){float area;area = calc_area_rect(2.5, 6.0);}

/* call function to do the work */

c 2013 Dr. Rosbi Mamat p.26/46

Microcontroller (SEL4533)

3.4 A Brief Review of C languageArray in C.Arrays are used to store large numbers of data of thesame type & only 1 variable is used to reference them.The format for declaring an array:

data_type name [array_size]data_type char, int, float, etc.name name of array that will be used to access thearray. Follow the rules of identifier.array_size the number of item the array can store.array can be initialized when declaring. In this casearray_size can be ommited.each item/element of an array is referenced using thename & index: name[0] is the 1st item & name[array_size-1]is the last item.Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.27/46

3.4 A Brief Review of C languageArray in C.Exercise: what are the values of sum, average & the arrayslength & len elements after this program is executed ?How many bytes of memory are used to store the array len?void main(void){int i, sum, average;int length[] = {7, 6, 4, 7, 2, 10};int len[6];sum = 0;for (i = 0; i < 6; i++){sum += length[i];len[5 i] = length[i];}average = (length[5] + length[3])/2;length[3] += 3;length[2] = length[2] + average;}Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.28/46

3.4 A Brief Review of C languagePointers in C.A pointer is a variable which can store an address of avariable of function.A pointer refers to a location in memory, & its typeindicates how the data at this location is to beinterpreted.The unary operator & gives the address of a variable.The unary operator * is the indirection / dereferencingoperator; it accesses the variable the pointer points to.2 arithmetic operations can be performed on pointers:An integer can be added to or subtracted from apointer.One pointer can be subtracted from another pointerof the same type.Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.29/46

3.4 A Brief Review of C languagePointers in C.Example:RAM (before)

char c;char *cptr;int x;int *iptr;

/* pointer to an integer */

cptr = &c;*cptr = 0x45;++cptr;

/* cptr = 0x1000/* c = 0x45/* cptr = 0x1001

*/*/*/

iptr = &x;*iptr = c;++iptr;

/* iptr = 0x1002/* x = 0x0045/* iptr = 0x1004

*/*/*/

/* pointer to a char

*/

Address

Contents

Variables

0x1000

0x90

c

0x1001

0x78

0x1002

0x56

0x1003

0x34

x

RAM (after)0x1000

0x45

0x1001

0x78

0x1002

0x00

0x1003

0x45

c

x

c 2013 Dr. Rosbi Mamat p.30/46

Microcontroller (SEL4533)

3.4 A Brief Review of C languagePointers in C.Example: Code fragment to copy 5 bytes from RAMstarting at address 0x0C00 & store in an array.#define RAM_start (char *) 0x0C00char * ptr2ram;char ramcopy[5];int i;

/* declare a ptr to RAM*//* array to store copy of RAM */

ptr2ram = RAM_start;for (i=0; i< 5; i++){ramcopy[i] = *ptr2ram;++ptr2ram;}

/* ptr2ram points to 0x0C00/* do it 5 times

Microcontroller (SEL4533)

*/*/

/* copy a byte to array*//* update ptr to next location*/

c 2013 Dr. Rosbi Mamat p.31/46

3.5 Program Design & ConstructionProgram development cycle:

Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.32/46

3.5 Program Design & ConstructionPlanning the logic of a program involves planningthe steps of the program, deciding what steps toinclude and how to order them algorithm.Algorithm is the recipe how to solve a problem withcomputer programs. Without algorithm, there is noprogram. Without program, there is no solution.Some of the tools used in planning the logic &expressing algorithm: language statement, pseudo code& flowcharts.

Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.33/46

3.5 Program Design & ConstructionSome important symbols in flowchart:Terminator

Process

Subroutine

Add Sugar

Calc average

STARTEND

Decision

Continuation

Input/Output

AA

yes

Need sugar?

no

c 2013 Dr. Rosbi Mamat p.34/46

Microcontroller (SEL4533)

3.5 Program Design & ConstructionPseudo codes & their flowchart structures:Pseudo Codesstep_1step_2. . .. . .step_n

Flow Chartsstep_1

step_2

..

condition thentrue_partelsefalse_partendif

step_n

if

Microcontroller (SEL4533)

no

yesCondition?

false_part

true_part

c 2013 Dr. Rosbi Mamat p.35/46

3.5 Program Design & ConstructionPseudo codes & their flowchart structures:Pseudo Codes

while condition dorepeated_partendwhile

Flow Charts

condition?

yes

repeated_part

no

repeatrepeated_partuntil condition

Repeated_part

no

condition?yes

Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.36/46

3.5 Program Design & ConstructionExample: Write/draw the algorithm for making a cup ofcoffee.The algorithm in language statements form:1.2.3.4.5.

boil waterput coffee in the cupif want sugar then add sugarif want cream then add creampour hot water into the cup

Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.37/46

3.5 Program Design & ConstructionExample: The algorithm in flowchart:STARTboil waterput coffeeYes

sugar?

add sugarNoYes

cream?add creamNo

pour hot waterENDc 2013 Dr. Rosbi Mamat p.38/46

Microcontroller (SEL4533)

3.5 Program Design & ConstructionExample: The algorithm in pseudo codes:boil waterput coffee in the cupif wantSugar is true thenadd sugarelsedont add sugarendifif wantCream is true thenadd creamendifpour hot water into the cup

Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.39/46

3.5 Program Design & ConstructionExample: The coffee making algorithm is expressed ingeneral statements. This is the Top Down approach ofsolving problem. Some of these statements may requirefurther detailing for implementation. For example the boilwater process can be further detailed out as:boil water

put water in the kettlelight the firerepeatwaituntil water is boiling

This process of further detailing is called step-wiserefinement.Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.40/46

3.5 Program Design & ConstructionSructured Programming: is a logical programmingmethod that enforces a logical structure on theprogram being written to make it more efficient &easier to understand & modify.A Structured Program has the following charac.:Includes only combinations of the 3 basic structures sequence, selection, & loop.

Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.41/46

3.5 Program Design & ConstructionA Structured Program:Structures can be connected to one another only attheir entry or exit pointsAny structure can be nested within another structureDoes not requires goto or jump statement

Example: a structured flowchart with pseudo code:

Yes

Nocond1?No

Yescond2?stmt

while cond1 is true doif cond2 is true thenstmtendifendwhile

c 2013 Dr. Rosbi Mamat p.42/46

Microcontroller (SEL4533)

3.5 Program Design & ConstructionExercise: This is an unstructured (spaghetti) flowchart.Why is this unstructured? Write the pseudo or C code forit. Convert the flowchart to a structured one & write thestructured pseudo or C code.

stmt1Yes

Nocond1?Nostmt2

Microcontroller (SEL4533)

Yescond2?stmt3

c 2013 Dr. Rosbi Mamat p.43/46

3.6 Debugging with Arduino IDESerial Monitor can be used to display values &messages for debugging Arduino programs.

Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.44/46

3.6 Debugging with Arduino IDESerial Monitor commands for using it:Serial.begin(9600) to enable input/output toserial monitor. Must be written in setup()Serial.println(val) to display val value to serialmonitor with newline added.Serial.print(val) as above but without newline.Serial.print(Error) display message Errorwithout newline.

Make sure USB cable is connected to PC & the samebaud rate value (9600) is selected in serial monitor!

Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.45/46

3.6 Debugging with Arduino IDEExample: displaying values & messages fordebugging Arduino programs.int debugMode = true;int result;

// set to false to turn off// variable to be monitored

void setup() {Serial.begin(9600);}void loop() {:if (debugMode) {Serial.println(In Debug"); // these messg will beSerial.print(Result = "); // printed onlySerial.println(result);// in debug mode}:}

Microcontroller (SEL4533)

c 2013 Dr. Rosbi Mamat p.46/46