embeddedsystems teaching resources on my office 5b18, telephone 028 90 366364 my email...

47
EmbeddedSystems Teaching resources on www.eej.ulst.ac.uk My office 5B18, telephone 028 90 366364 My email [email protected]

Upload: augustine-miles

Post on 11-Jan-2016

227 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

EmbeddedSystems

Teaching resources on www.eej.ulst.ac.uk

My office 5B18, telephone 028 90 366364My email [email protected]

Page 2: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Computers: hardware and Software

Understanding what computers, micro-controllers and microprocessors can do

What the hardware of these systems are like What the software (firmware) of these systems

is like How to make the software How to make the hardware

Page 3: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Software

How to average 10 numbers? Get the first number Add the second number to it Add the next number to it Continue until you have added 10 numbers Divide the total by 10.

Page 4: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Programming How to average 10 numbers?

Get the first number

Add the second number to it

Add the next number to the sum

Continue until you have added 10 numbers

Divide the total by 10.

Start

Clear TOTAL and Clear COUNT

Get INPUT

Add input to TOTALAdd 1 to COUNT

Is Total=10

?

Divide TOTAL by 10

Present the ANSWER

Stop

NO

Note the slight difference in the methods. The computer is good at repetitive stuff so it is good to make the first step the same as allThe other steps, so the first number is not treated differently to Subsequent numbers.

Page 5: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Start

Clear TOTAL and Clear COUNT

Get NUMBER

Add NUMBER to TOTALAdd 1 to COUNT

Is Total=10

?

Divide TOTAL by 10

Present the ANSWER

Stop

NO

/******* comments can be made in two ways ***/#include <stdio.h> // we use scanf and printfvoid main(void){ // two slashes produce a comment int number; // used for input int total=0; // used for running total int count=0; /* number of numbers input */ float answer; // compiler must know the type // of ALL variables in a program do{ scanf(“%d”,&number); complicated way to I/p

total=total+number; // '='sign means “will become equal to” count =count+1; // or use count++

}while(count<10);

answer = total/10; // better to use /count!

printf(“\nThe answer is %f “,answer);

}//--end of main –//

Page 6: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Printf and Scanf – standard I/o library routines – not in the C language but supplied in libraries with

each compiler

The quoted strings passed to printf can contain three thingsOrdinary text, escaped characters and format placeholders.

The backslash followed by a character or characters e.g \n This is known as an escape sequence, and in this case it causes the printf function to take a newline after the line of text has been printed.

The other new device is the %f This is called a place holder and is used to indicate where the value of a particular variable should be printed. The fact that an f is used indicates that the variable is expected to be a floating point number. The values to be printed, or names of the variables to be printed, follow the string in a comma-separated list as shown.

Page 7: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Escape sequences

Page 8: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Format Placeholders

Page 9: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Microcontroller e.g a PIC microcontroller from Microchip

Many versions! (check out their website)

Our boards have 16F877A or PIC32MX250F128B or D

16F877 has 5 ports - Port A has 6 bits, B,C,D are 8 bit and E is 3

PIC32MX256F128B/D has 21 i/o lines (it is in a 28 pin package)

Each pin can be input or output (just about)

16F Outputs are roughly 0V or 5V, up to 25mA (typically 3-4 volts)

PIC32MX outputs are roughly 0V or 3.3V up to 7mA

Has timers built in – can work off system clock or external inputs

10 bit ADC – Analogue to Digital convertor. Choose to use it or ordinary i/o but you must select either an analog or digital function on each pin.

Has serial input and output. Fixed pins RC6 and RC7 on 16F, programmable pins on PIC32MX (you can route peripherals to a range of pins using PPS)

Has other chip interfacing capabilites e.g IIC or SPI protocols to link chips together.

Page 10: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Hardware of PIC supported by Software There are 4 or 5 C compilers for the PIC; made by CCS inc, or

the HiTec Corporation

HiTec C provides special keywords to manipulate hardware features as well as a C library of useful functions. It was recently bought over by microchip and they have rebadged the compilers as the C8, C16 and C32 products.

The Standard C language has only 35 keywords and three or four basic data types.

Although it also has standard libraries – to calculate cosine for example or provide input and output through a keyboard and screen(console) - or a serial interface to a keyboard and screen.

Page 11: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

HiTec C (c.f www.htsoft.com)or now www.microchip.com

Page 12: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk
Page 13: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Another program

Get the temperature If it is too high (>25)

Switch heater on If it is too low (<22)

Switch heater off Wait a bit Do it again

Start

Get TEMPERATURE

Is it greater than

25?

SwitchHeaterON

NO

YES

SwitchHeaterON

Is it greater than

25?

Delay_milli_seconds(10)

YESNO

Page 14: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

#include <htc.h>#define _XTAL_FREQ 20000000// line above needed to make __delay calls work

__CONFIG(WDTDIS & PWRTDIS & BORDIS & UNPROTECT);//line above needed to set “fuses” in a PICStar

t

Get TEMPERATURE

Is it greater than

25?

SwitchHeaterON

NO

YES

SwitchHeaterON

Is it greater than

22?

Delay_milli_seconds(10)

YESNO

void main (void){ unsigned short int temperature;

PORTC = 0x00; // TRISC = 0xFF; // set PORTC to be I/p PORTB = 0x00; TRISB = 0xFE; do { Temperature = PORTC; // assuming PORTC wired up

if(temperature > 25) { RB0=1; //predefined in Hitec C } // PORTB bit 0 else { if(temperature < 22) { RB0=0; } } __delay_ms(10); //supplied library }while(1);}//-- end of main – never reached!--//

Page 15: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Embedded C vs Ordinary CEmbedded C (running in a single chip microcomputer)

• has few bits of input and a few bits of output as a minimum

• Perhaps uses timers and special built in peripherals such as an ADC, serial port, I2C, SPI, USB, PWM outputs.

• Might not use “console i/o” (after debugging) and does not have access to an OS.

Ordinary C runs on a full computer

• has access to a disk drive and operating system resources

• has access to a sophisticated screen for output and a keyboard and mouse for input.

• May use “text console” or access the operating system resources – the windowing system and the various OS library calls to move about a window.

• Interacts with a user in the normal way

Page 16: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Learning CSimple language of 35 Keywords

Simple structure, can be a single file containing a collection of functions, it will have a single function (named main()) and this might call other functions.

A function is a section of code that does a single simple thing; it has a defined entry point – a start, a defined list of incoming data to work on and a mechanism to send its results somewhere. (unless it is a beep() function)

Page 17: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

The C language

As well as functions you write there are library functions. You can also “include” other files that contain other functions.

Good to partition or split big problems into a number of small functions. Top down design…

As well as “WHAT NEEDS DONE” you also need to think about “WHAT DATA IS BEING MANIPULATED”

(If you focus on this then you have become Object Orientated) – There is a version of C that is suitable for OOPs programming – C++

Algorithms + Data Structures = Programs

Page 18: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Why Use C?

C is a powerful and flexible language.

C is a popular language preferred by professional programmers. As a result, awide variety of C compilers and helpful accessories are available.

C is a portable language. Portable means that a C program written for one computersystem (an IBM PC, for example) can be compiled and run on another system(a DEC VAX system, perhaps) with little or no modification

C is a language of few words, containing only a handful of terms, called keywords,which serve as the base on which the language’s functionality is built.

C is modular. C code can (and should) be written in routines called functions.These functions can be reused in other applications or programs. By passing piecesof information to the functions, you can create useful, reusable code.

Page 19: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Making Programs

Several tool paths exist;

1. Edit a file, give it a .c extension, e.g test.c

2. Compile it, this creates test.obj

3. Link to any previously created .obj files

4. Link it to the standard library (to “bring in” printf.obj)

5. This creates test.exe

6. Run test.exe.

Page 20: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Making ProgramsIn practice it is common to use an IDE to automate these steps

and also manage the source files.

An IDE will have an editor window, a project navigation window, a function list window and a single button/command to create and run test.exe.

Visual C++ can create C based console programs, the IDE has a “make” command [F9]

And a run in a window command.

In practice you should add a line to pause the program so you can read the screen before the window exits.

In the embedded world, microchip provide MPLAB, with similar capabilities, and also a device programmer/downloader.

Page 21: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Your First C Program

#include <stdio.h>

int main(void) {

int i;

printf(“Hello, World!\n”);

scanf(“%d”,&i);

return 0;

}

C is case sensitive, C treats all “white space” the same (spaces, tabs, newlines) unless inside double quotes. Most C statements end in a semicolon.

Line 1 tells the compiler where to find out about functions that you use and didn’t write yourself (printf)

Line 2 is the start of a block of code – known as a function. This function is called main, it is passed nothing and returns a number

Line 3 tells the compiler to allocate a bit of space for a “variable” that will be a whole number and will be referred to as i .

Line 4 calls the special library function called printf. The documentation for printf describes what is passed to it, what it does and what if anything it returns to the caller.

Line 5 scans the keyboard and awaits input

Line 6 sends the number zero back to whoever called main, in this case it is the OS.

Line 7 finishes the body of the main function. Most “blocks” of code have start and end curly brackets

Page 22: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Exercises: (use Codeblocks or Visual C)

Enter and compile the following program. What does this program do? #include <stdio.h>

int radius, area;int main( void ) {

printf( “Enter radius (i.e. 10): “ );scanf( “%d”, &radius );area = (int) (3.14159 * radius * radius);printf( “\n\nArea = %d\n”, area ); return 0;

}

Enter and compile the following program. What does this program do?

#include <stdio.h>

int x, y;

int main( void ){for ( x = 0; x < 10; x++, printf( “\n” ) )for ( y = 0; y < 10; y++ )printf( “X” );return 0;

}

Note: Variables declared outside a function are known and accessible anywhere in the file.

Variables declared inside a function are only visible, known and accessible inside the function.

Although you can pass a variables value to a function by calling it from within your own function (that is how printf knows the value to print)

It is even possible to pass a reference to a variable, rather than its value, this is how scanf works

Page 23: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Exercises: programs with bugs!BUG BUSTER: The following program has a problem. Enter it in your editor andcompile it. Which lines generate error messages?

#include <stdio.h>

int main( void );{

printf( “Keep looking!” );printf( “You\’ll find it!\n” );return 0;

}

BUG BUSTER: The following program has a problem. Enter it in your editor andcompile it. Which lines generate problems?

#include <stdio.h>

int main( void ){

printf( “This is a program with a “ );do_it( “problem!”);return 0;

}

Page 24: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Draw a flowchart , then write a program

Find the average of ten numbers

Input your coursework and exam marks for your semester one subjects and print out your semester average.

NB; %f is used for floating point in printf’s format specifier strings.

There are clues in the earlier slides.

Page 25: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Variables in CA variable is a named data storage location in your computer’s memory. By using a variable’s name in your program, you are, in effect, referring to the data stored there.

Variable names can contain a-z, A-Z, digits and the underscore, the first character must not be a number or one of the C keywords.

Variable names should be meaningful – self documenting code.

The computer works out where to store each variable, what address to place it and what size (how many bytes to allocate to store the variable contents.

We must give the compiler clues as to how many bytes – the type of data to be stored in each variable

Page 26: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Variable sizes in bytes for a typical PC compiler, NB embedded compilers often are differerent!!!

Page 27: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Although compilers differ; what is always true

To give a compiler information about a variable you must “declare” your intentions

// to declare a variable, give a type then the variable name (and a semicolon)int i; /* often worth adding a comment here!... i is used as a loop counter … */char ch;

Also, you can have multiple declarations within a statement but it makes commenting harder.

int i,j,k;

Also you can initialise a variable when you declare it.

int total=0;float sum=0.0; // note how you can specify a floating point constant.

Page 28: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Numbers, characters and stringsNumbers can be whole numbers or floating point numbers of different sizes; signed or unsigned. For example 42, or 42.0. We can also use HEX numeric constants by using a 0x prefix so 0x42 is actually 66 in decimal (4*16+2)

Programs often deal with text. There is only limited support for this in the actual C language, though there are many string functions available, you must #include <string.h> to access them

The data type char is used to hold a single character – actually it just holds an 8 bit number.

The compiler will convert a single character to its 8 bit numeric value – by using SINGLE quotes. Thus if i is declared as a char, you can say i = ’a’; and i ends up with the value 65.

The character set is known as the ASCII character set.

A string does not exist in C, we use arrays instead. An array is a collection of data objects of the same type and given a single collective name. Thus an array of characters is considered a string and there are a dozen library functions written to use an array of characters, with the VERY IMPORTANT CONVENTION that an extra byte is out at the end of the array that contains zero.

Page 29: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

The ASCII character set; in binary the symbol ‘A’ is 100 0001 or 0x41 or 65 in decimal

Page 30: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Text stringsWhilst it is true no string variables exist in C, null terminated char arrays are treated as strings by the functions in the string library.

Also the compiler will convert string constants to a null terminated char array in memory; this uses the DOUBLE QUOTES to tell the compiler what to do.

You have already seen this in the parameters passed to printf (and scanf)

Thus printf(“This is a string”); will work

You cannot assign text to a string or add strings together in C – without using specially written string functions strcpy() and strcat()

Page 31: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Declaring arrays and strings//C uses square brackets with arrays. To declare

int mydata[6]; // the compiler sets aside room for 6 ints

char me[6]; // 6 bytes, 5 for chars and one for the zero terminator

// To declare and initialise, the compiler helps a bit here

int mydata[] = {1,2,99,42,55,77}; // you can keep the [6] if you want

char me[] = “james”; // the compiler stores 6 bytes ‘j’,’a’,’m’,’e’,’s’,’\0’

To use an array element as a single data value, use the square brackets and an index number. x = mydata[2]; makes x=99

NOTE indexing starts at zero mydata[0], mydata[1] then mydata[2] – the third element of the array

Page 32: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

You have seen simple assignments; in C these use the assignment operator, the equal sign.

In the assignment statement values move from the righthand side to the lefthand side of the equal sign.

Thus x=10; causes 10 to move into the variable x.

In C we use the double equal combination for an equality test, no data moves!

If(x==10)printf(“nothing moved”);

Be careful you see the difference between the assignment operator and the equality test

Assignment = a simple statement

Page 33: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

The IF statement (two versions – the single staement and the block of startement version)

If (conditional test is true)do this-only if it was true;… always do this…

If (conditional test is true){do this-only if it was true;do that-only if it was true;

}… now do this (always)

I recommend you always put brackets in – even in the single statement version – at least when you start C it reduces errorsIf (conditional test is true){do this-only if it was true;}… always do this…

Page 34: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

If statements

If (conditional test is true)do this-only if it was true;… always do this…

e.g, actual C

If(count==10)average=sum/count;

Page 35: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

If(count==10) {average=sum/count;printf(“average of %d numbers is %f\n”, count, average);

}

// There is a lot going on here, note the use of two format specifiers and one // escape character in the printf function parameter list.

The other conditional tests are

!=<><=>=

Page 36: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

If – else statementsIf(count<10){ // Note NO semicolon

sum=sum+mydata[count]; // If and if-else are compound

count=count+1; // statements. Only simple}else{

// statements end inprintf(“average is %f\n”,sum/count); // semicolonsreturn 0;

}

// program defensively – keep your logic flow simple, easy to understandYou can also have nested if and multiple elses – too awkward…

Page 37: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

The following code sets a variable c equal to the greater of two variables a and b, or 0 if a and b are equal.

if(a > b){c = a;

}else if(b > a){

c = b;}else{

c = 0;}

Too error prone, find a way to express your code more simply.(switch-case statements)

Page 38: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

The Conditional ExpressionYou do not often need this, I usually look up the syntax if I am going to use it, it

can give you concise code.

A conditional expression is a way to set values conditionally in a more shorthand fashion than If Else. The syntax is:

(/* logical expression goes here */) ? (/* if nonzero (true) */) : (/* if 0 (false) */)

The logical expression is evaluated. If it is nonzero (true), the overall conditional expression evaluates to the expression placed between the ? and :, otherwise, it evaluates to the expression afterthe :

Therefore, the above example (changing its function slightly such that c is set to b when a and b are equal) becomes:

c = (a > b) ? a : b;

So c = a if the test is true or c = b if the test is false

Page 39: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

The Switch Case statementswitch (grade){

case 1:

printf("A\n");break;

case 2:

printf("B\n");break;

case 3:

printf("C\n");break;

case ‘q’:case ‘Q’:

printf("D\n");break;

default:

printf("F\n");break;

}

The SwitchCase construct takes a variable, usually an int, placed after switch, and compares it to the value following the case keyword, the value can be a char constant ‘x’

If the variable is equal to the value specified after case, the construct "activates", or begins executing the code after the case statement. Once the construct has "activated", there will be no further evaluation of cases.

SwitchCase is syntactically "weird" in that no braces are required for code associated with a case. Very important: Typically, the last statement for each case is a break statement. This causes program execution to jump to the statement following the closing bracket of the switch statement, which is what one would normally want to happen.

However if the break statement is omitted,program execution continues with the first line of the next case, if any. This is called a fallthrough.

Page 40: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Loops: there are 3 of these; the FOR loop, the WHILE loop and the DO loop

int a=1;

while(a<100) {printf("a is %d \

n",a);a = a*2;

} // loop is done zero or // more times. // Note no semicolons// the keywords break // and continue can be // used inside while // loops

int a=1;

do{printf("a is %d \n",a);a = a*2;

}while(a<100); // note semicolon!

// loop is done once or more times// again break can be used to exit// to the statement below the loop// prematurely and continue can // be used to jump back up to the// do (start of loop)

Page 41: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

int ix;for(ix = 1; ix <= 100; ix = ix +1){ // or use ix++ to save typing.

printf("%d ", ix);}// the three parts of the FOR loop, initialisation executed once on // entering the loop the test, done at the TOP of the loop at // the first } and the loop end statement, the increment done at the// END of the loop, at the last }

// note that ix++ is shorthand for ix=ix+1, you can also use -- as a // decrement operator. These can be prepended or appended// to the variable. i++ or ++i. This sometimes matters. E.g

i = 5;x = i++; // now x is 5 and I is 6

The for loop is handiest when we know how many times around a loop we want, e.g to execute a loop 100 times. However you can use it in a variety of ways.

Page 42: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

FunctionsThings to know;

How to declare them e.g float sqr(double); or one you have seen

int main(void); // this declaration is in stdio.h! done for us!// note the semicolon is vital here – to let the compiler see which is //the declaration and which is the body of the function

How to use them – pass them data and get resultsx = sqr(y); // pass it a number, the VALUE of yz = sqr(16);p = sqr(4*y + x); // pass it a number, the value of the expression

How to write them. Note NO SEMICOLON belowfloat sqr(double dd){ //dd is not a local variable that takes the

return(dd*dd); // value of the incoming number}

Page 43: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

Directives; not really part of the compiler – the file is preprocessed before being compiled

#include <string.h> // angle brackets = system#include part1.c // no brackets = user folderNote no semicolons!, the files are just inserted#define PI 3.1428 // a simple text subsitutionConvention is to use UPPER CASE. (used a lot)

#ifndef GOTLCD#define “putch(“ “putch(LCD,”

#endif

So if GOTLCD has been previously #definedThen a text substitution will be carried out

#pragma Some none standard feature that your compiler allowsA different compiler will ignore a #pragma line if it doesn’t understand it.

Page 44: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

SummaryYou have seen.• Basic data types• Arrays and strings• simple statements such as assignment expression• Conditional expression• Compound statements; if, while, do, for, switch,case, break,

continue• Function usage• Preprocessor directives

Still to see; • casts, • accessing memory, (pointers)• passing variable references into functions instead of values. • Some more library functions, strings and files.

Read the 129 page “C_Programming__WikiBook.pdf” for next week

Page 45: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

www.eej.ulst.ac.uk/~ian/modules/EEE527 45

C Syntax Aide Memoire (cog sheet!)

1. White space doesn’t matter, case does – most C is lower case.2. Commenting can be /* a block with start and stop comment symbols */ or a single line //

text…<cr>3. Names must begin with a letter or underscore, but don’t use underscores, the libraries use

them.4. Names should not contain funny symbols other than underscores. Use sensible names!5. Use #define for symbols used throughout your code, you need only edit them in one place6. Arithmetic uses +, -, *, / also % for remainders and &, | and ^ for AND, OR and XORs of the

bits.7. ++ and -- increment and decrement. It is so common to write x=x+c; you can write x+=c; //or

-,*,/ etc8. You can shift left and right using << and >>, you can do a one’s complement with ~ but be

careful! 9. Types are char, int, float. You can declare a variable as a const type, it can’t change.10. You can have signed and unsigned ints and chars, short or long ints and floats can be

doubles.11. Variables need declared before use, inside functions they’re local, outside they’re

global 12. Casting forces the complier to convert a variable’s type in an expression, y=(float)x /z;//e.g

x was int13. Functions need declared before use, give their return type and the types in their parameter

list.14. Simple variables in a parameter list only have their value, a number, passed to the function.15. Declare functions before use, use them in main for example like y=sqrt(x); and list their

body after main (or before if you like, but adopt a consistent style). Give no semicolon when defining body.

16. Conditional tests. Use == as an equality test, also !=,for not equal, <, less than etc… <=, >,>=.

17. You can OR,AND and NOT tests with ||,&& and ! Use brackets! E.g if( (x == 9) && (y != 5) ){…

18. if( test is true){do these statements;} // the simple if statement, if there is one statement omit the { }

19. if( test is true){do these statements;}else{do these statements;} // note no semicolon after )

Page 46: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

www.eej.ulst.ac.uk/~ian/modules/EEE527 46

C Syntax Aide Memoire (cog sheet!)20. Conditional expression is rarely used c = (do a test) ? Assign this if true : assign this if

false; 21. switch(test an int){ case value1: do this; break; case value2: dothis; break; default: do this;}  Loops; there are 3 of these, note carefully while is used twice, with or without a semicolon22. do{these statements;}while(test is true); // there IS a semicolon after the while conditional

test23. while(test is true){do these statements;} // NO semicolon after while conditional test24. for(initialisation;test;increment){do these statements;} // test done at top, increment at

bottom25. You can exit a loop prematurely using break; , or go back to the beginning of a loop with

continue; Arrays use square brackets, you can give its size as a number or string, or list of items26. int x[4]; // i.e x[0] to x[3] note 4 elements it is a mistake to refer otherwise use x[4] in your

code27. char s[ ]=”OK”; // note s[0]=’O’, s[1]=’K’ and s[2]=0x00 (can be written as ‘\0’) strings end in a

zero28. float f[ ]={42.0, 42.99, 69}; // this declares 3 elements. Pointers and addresses; get the address of a variable by using &, e.g a = &x; or scanf(“%d”,&x);29. Declare a pointer by appending a to the type (better style to move it near the variable

name)30. int ptr1; or char ptr2; Note we often use pointers to move inside strings and arrays31. To use the contents of what a pointer is pointing at use the indirection operator, also a 32. e.g if(ptr2 == 0x00){… //ptr2 is pointing at a memory location or variable containing zero33. You can declare a void pointer and later “cast” it to the right type. (see how to use malloc() )39. String functions use #include <string.h> then you get strlen, strcmp, strcpy, strstr, sprint see

libc.pdf40. malloc allocates memory, e.g to get somewhere for strings or buffers to live, if they are not

declared. E.g p = (int *)malloc (sizeof(int) * BUFSIZE); // if p is an int pointer… note use of sizeof()

41. ++ -- + += - -= / /= * *= % %= | |= & &= ^ ^= = == != < <= > >= << <<= >> >>= ~ && || . , ; ? : ( ) [ ] { } /* */ // \ “ ‘ -> !

Page 47: EmbeddedSystems Teaching resources on  My office 5B18, telephone 028 90 366364 My email IJ.McCrum@ulster.ac.uk

www.eej.ulst.ac.uk/~ian/modules/EEE527 47

++ -- + += - -= / /= * *= % %= | |= & &= ^ ^= = == != < <= > >= << <<= >> >>= ~ && || . , ; ? : ( ) [ ] { } /* */ // \ “ ‘ -> !

You should know enough C to know what each of the above is used forNow try lecture 1 to see how C is converted into machine code