Escolar Documentos
Profissional Documentos
Cultura Documentos
8051
Agenda
C
What is C?
High-level programming language One of the most popular general purpose programming languages available First developed in 1972 by Dennis Ritchie at AT&T Bell Labs Advantages of C Readability Maintainability Portability
A Word of Caution
A Simple C Program
/*This is my 1st C program Port 1 will be loaded with 0xAA and Port 3 with 0xF6. Everything between the star and forward slash is ignored by compiler*/ #include <stdio.h> void main(void){ P1 = 0xAA; P3 = 0xF6; while(1){ asm{NOP;} used }
//Assembler instruction
Dissecting a C Program
The first line is a comment A comment starts with a /* and ends with a */ Everything in between is ignored Comments can cross more than one line Document code, enhance readability Comments affect only size of text file Shortform notation for commenting out a single line: two slashes, // Comments cannot be nested
Dissecting a C Program
/* Comments do not increase the size of the executable, nor does it affect performance */ /* Comments do not increase the */ /* size of the executable, nor */ /* does it affect performance */ // Comments do not increase the // size of the executable, nor // does it affect performance
Dissecting a C Program
#include <stdio.h> Line 2 is a preprocessor directive Tells the compiler to look for a file and place the contents of that file at the directive stio.h is a header file Contains prototypes and macros for functions and registers
Dissecting a C Program
Angle brackets <stdio.h> tell the preprocessor to look in another directory for the file
Double quotes stdio.h tell the preprocessor to look in the current directory for the file
Dissecting a C Program
Every C program must have one, and only one, main( ) function Can be anywhere in your source code Program execution starts with main( ) Programs always end with main( ) The body of the function main( ) is located between the curly braces { and the }
A C program is composed of basic elements such as: keywords constants variables expressions statements and statement blocks
ANSI C Keywords
auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsinged void volatile while
Expressions
Precedence of Operators
All expressions are evaluated according to the precedence of its operators What do the following expressions reduce to?
2 + 3 * 10 (2 + 3) * 10
Precedence of Operators
All expressions are evaluated according to the precedence of its operators What do the following expressions reduce to?
2 + 3 * 10 (2 + 3) * 10 = 2+(3*10) = 32 =5*10 =50 * has higher precedence than + () has higher precedence than *
Statements
A statement is a complete instruction, ending with a semicolon A statement is made up of one or more expressions
i = 1; j = 6 % 4; return 0; Var1 = (2 + 3) * 10; BinValue = i + j;
Statement Blocks
A group of statements is a statement block beginning with a curly brace ({) and ending with a curly brace (}) A statement block is treated like a single statement by the compiler
for() { s3 = s1 + s2; MulValue = s3 * c; }
Data Types
Defines the size and type of data that a variable holds Only five data types in ANSI C
void char -> int -> long -> float -> double
Represents a single character or an 8-bit number, i.e., A or 7 To define a variable as a char use:
char variablename;
Character Constants
Single characters can be represented using single quotes, such as: A The ASCII value of the character is the value used in the expression x = A; //0x41
Integer numbers are whole numbers Result of integer division is truncation The length of an integer varies from one machine to another, typically 16-bits To define a variable as an int use: int variablename;
Floating point numbers contain both real and fractional parts Has at least 6 digits of precision To define a variable as float use: float variablename; Supported as 32-bit value in MCS51
These four data type modifiers can be applied to data types char and int signed unsigned short long
Sign Bit
The difference between a signed number and an unsigned number is the interpretation of the MSb For signed numbers, the MSb indicates a positive number when 0 and a negative number when 1 For unsigned numbers all bits are used to determine the value The default value of data types is unsigned
Sign Bit
The range of unsigned char is 0 to 255 {0, 1, , 255} The range of signed char is -128 to +127 {0x80, 0x81, , 0xFE,0xFF,0x00,,0x7F}
long and short are used to increase or decrease the size used by the data type short int x; reduces a 16-bit integer to 8bits
Anatomy of a C Function
Function Type Function Name Argument List to Function
char add (char x, char y){ char result; result = x + y; return (result); }
Function Type
The function type is used to signify what type of value the function returns Can be any valid C data type void functions do not return a value The function add( ) returns a char
Function Names
A function name should be chosen to reflect what the function does Function names cannot start with numbers Function names cannot contain asterisk, arithmetic signs, or dot (.) Functions cannot contain minus signs or apostrophes
Function Arguments
Arguments are used to pass information TO a function Multiple arguments are separated by commas A function that does not receive any arguments is considered to be void int status(void){ // This function will return data of type int }
Function Body
function body
function body
The statements in between are the statement block The function completes when the statement block is finished executing
Global Variables
void TestFlags(void){ FlagReg = FlagReg & 0x86; }// end of function void main(void){ FlagReg = FlagReg + 5; TestFlags(); }
//Call function
Local Variables
Defined inside a functions e.g. Temp Variable can be used ONLY by that function
// Globally defined register
void ChangeVal(void){ unsigned char Temp; // Local variable Temp = P1 + 0x21; Online = Temp & 0x0F; }// end of function void main(void){ ChangeVal(); }
//Call function
char add( char x, char y){ char result; result = x + y; return (result); }
void main(void){ char sum; sum = add(5,12); P1 = sum; }
/* This function adds two chars */ //define a LOCAL result variable /* add parameters */ /* return result to caller */
Quiz
Quiz
Quiz
Quiz
for Loop
for Loop
expr1
?-expr2
T F
statement1
statement2
... expr3
while Loop
while Loop
?-expr1
T
F
do-while Loop
do-while Loop
statement1 statement2 ... expr1
T F
break Statement
break Statement
continue Statement
continue allows you to stay in loop but skip over statements within loop General form: continue;
for (i=1;i<6;i++){ if (i==3){ continue; } sum += i; }
continue Statement
continue allows you to stay in loop but skip over statements within loop General form: continue;
for (i=1;i<6;i++){ if (i==3){ continue; } sum += i; }
if Statement
Optional
if Statement
Executes a statement block based on a condition General form: NB!! Not Value = 0x34
if (Value == 0x34){ statement1; statement2; . . . }
True False
Optional
switch Statement
Arrays
An array is a collection of values with the same data type Each value in the array is an element All elements are referenced by the name of the array with an offset Elements are stored in consecutive memory locations
Arrays
data-type indicates what data type the elements in the array will be Array-name is the name of the array Array_size defines how many elements are in the array E.g. char Keyboard[16];
Array name is Keyboard All data in Array is of type char Array has 16 locations (0 to 15)
Arrays
Arrays are accessed using an index Index starts at 0 and ends at arraysize - 1 The elements of the array are:
day[0], day[1], day[2], day[3], day[4], day[5], day[6] Data[0], Data[1], Data[2], Data[3], Data[4], Data[5], Data[6]
Or all together
char day[7]={S,M,T,W,T,F,S}; char Data[6]= {3,5,4,1,0,2};
Arrays
Accessing arrays using an index variable Array with name of List and 10 elements ints
int List[10], i; for(i=0;i<10;i++) { List[i] = i; }
An array of characters is a string Strings must be terminated by a null character \0 Null characters have a value of 0
char Greet[7]={H,e,l,l,o,\0}; char Greet[7]={H,e,l,l,o,0};
as shown above
Or all together
char Greet[]=Hello;
Strings
What is the difference between the two statements? char ch = x; char str[ ] = x;
Pointers
where data-type is the data type of data the pointer is pointing to and name is the pointer name
Pointer functionality is similar to the @ use in assembler Pointers may be operated on just like any other variable
compiler automatically adjusts pointer registers to data size similar to array and index combination
Pointer Initialization
pointers must always be manually initialized & notation used to initialize pointers to single variables array name may be used to initialize array pointers
int Var; //declare a variable
int *VPtr; //declare pointer to int variable
char Array1[] = Hello; //declare and init an array char *APtr; //declare pointer to array
//initialize variable pointer //initialize array pointer //does same as previous line
Pointer Operations
sets the pointer to point to address 0x20 sets the contents of address 0x20 to 0x34 Ptr1 += 5; adds 5 to the pointer to point to address 0x25 *Ptr1=0x67; 0x67 loaded into 0x25 *Ptr1 = *Ptrl + 2; adds 2 to the contents of address (*Ptr1 += 2) 0x25. Will become 0x67 +2 = 0x69 Ptr1=0x20; *Ptr1=0x34;
Pointer Operations
Pointer arithmetic
may increment or decrement pointers may add values to or subtract values from pointers pointer will always be modified by the number of bytes in the data type it is pointing to:
int *IntPtr; char *ChPtr; IntPtr++; bytes ChPtr++; byte
//pointer incremented by 2
//pointer incremented by 1
Pointers vs Arrays
Arrays are always passed by reference (i.e. using the base address of the array) Array names may be used interchangeably with pointer names
array names used without indices are interpreted as the base address of the array
Pointers vs Arrays
Code example:
void Add(char *Ptr1, char Length) { while(Length != 0x00) //check if all elements complete { *Ptr1 += 0x03; //add 3 to array element Length--; //decrement loop count Ptr1++; //move to next element } } void main(void) { char Array[] = {0,1,2,3,4}; //define and initialize array char *APtr = Array; //define and init pointer to array Add(Array,5); Add(APtr,5); Add(&Array[0],5); } //call function using array variable //call function using pointer //call function using array element
Structures
Structure declaration
Structure Tag
Declaring Structures
Member variables
No Variable
Declaring Structures
Member variables
Variable Names
Accessing Structures
Structure members are accessed using dot notation variable-name.memberx Member may be used as a variable of the type of memberx
//character string variable //string length variable
Casting Variables
precede variable to be cast with the desired data type enclosed in parens
Casting Variables
Casting Variables
ASK !!!!!!