Introduction Embedded Systems Introduction to C Embedded Programming language Why C instead ASM 1. C is a high level language, it is easier to write and read than assembly codes. 2. You don't have to think about hardware logic with C, this is taken care of in the background. 3. C codes can be compiled for different microcontrollers without significant modifications of code. 1 3 Introduction In this lecture we will cover the fundamentals of the C programming language as it applies to embedded microcontroller applications. 2 The C Language The C language is function based programming language. Function consists of: 1. A Return Type 2. The Function Name 3. Followed by parentheses enclosing arguments or an empty pair of parentheses if there are not arguments required. f ( x) = x int cube (int x) = x 3 3 y = Integers f (x) y = cube(3) 4 1
while(1); The C Language A C program itself is a function. All C program MUST have a main() function. This function must be included in every program because this is the function which is run when the program is executed. An embedded C program in its simplest form: // do forever 5 The C Language #include <stdio.h> This is a preprocessor command. All preprocessor commands are identified by the # sign. The #include command tells the preprocessor to open filestdio.handcompile itasapartoftheprogram. Nextlineisvoidmain(). It is always necessary to define the type of function, its return type and of course whether the function has any arguments. The type void indicates that this main() function does not return an output and the empty brackets indicates that the function takes no inputs. An open brace indicates the beginning of the block of statements within the function and the function closes with a closing brace. 7 The C Language C Preprocessor Commands #include <avr/io.h> // AVR Header File #include <avr/io.h> // AVR Header File int n; DDRB = 0xFF; DDRA = 0x00; while(1) // do forever PORTB = PINA; 6 Preprocessing, this is the first stage of any C program during compilation. Preprocessor commands are used to combine header files to the mainfiles. During the preprocessing stage, symbols, macros and constants are defined. With the help of preprocessor commands programs become easier to develop and modify. The preprocessor is directed using # symbol at the beginning of the command. All preprocessor commands start with a #. 8 2
C Preprocessor Commands #include : This directive is used to include external c files and headers that are needed for the compilation of a specific project. The#include is used in the following way,#include <filename>. #include <avr/io.h> // General header files #include <avr/interrupt.h> Variables Types Variables are simple keywords which are defined by the values. Values can be changed. Variables are like a boxes with some size where values like apples canbeputin.sovariablescanbeofvariousformsandsizes. A variable type is defined by a reserved word which indicates the type and size of variable identifier: unsigned char Peabody; #include "uart.h" // User s own header files #include "lcd.h" int dogs, cats; long int total_dogs_and_cats; 9 11 C Preprocessor Commands Variables Types #define: This directive allows the programmer to construct constants and macro commands needed for a project. The #define is used in the following way, #define identifier value #define BAUD_RATE 9600UL #define F_CPU 3686400UL // Named constant // Frequency of the clock There are other preprocessor directives that are used in C but not as widelyusedastheonesabove. 10 12 3
Variables Types Constant A Constant value is understandable as being non-changeable value like the (pi=3.141592...) value in math. Usually you use constants in your programs, but don't realize that they are constants. For instance: x = x + 3; The number 3 is a constant which will be compiled directly in addition operation. Constants canalsobeacharacterorstring. It is usually recommended to declare constants by using identifier with reserved word const: const int No = 44; 13 15 Global & Local Variables unsigned char globley; void function_z (void) unsigned int tween; tween = 12; globley = 47; main_loc = 12; unsigned char main_loc; Variables Scope // global variable // a function //local variable //OK //OK //ERROR // local variable #include <avr/io.h> unsigned char z; DDRB = 0xff; DDRA = 0x00; while(1) z = PINA; I/O Operations // Declare z // Set all pins on port B for output // Set all pins on port A for input globley = 34; tween = 12; while(1); //OK //ERROR // do forever PORTB = z + 1; 14 16 4
Operators These are symbols that tells the compiler which type of operation is to be performed. Assume that an unsigned char y = 0xC9 Note: There are certain rules that governs the order in which operations are performed. Once a variable has been declared, operations can be performed on them. Below are some of the typical arithmetic operations that are usually carried out on variables. Multiplication(*) Division(/) Modulo(%) Addition (+) Subtraction/ Negation(-) 17 Operation x = ~y; x = y <<3; x = y >>4; x = y ^1; x =y 0x10; Results x = 0x36 x = 0x48 x = 0x0C x = 0xC8 x = 0xD9 19 Bitwise Operation These operators perform functions that will affect an operand onthebitlevel. These operators work on non-floating point operands such as char and int. There are six bitwise operators: OnesComplement(~) LeftShift(<<) RightShift(>>) AND(&) ExclusiveOR-(XOR)(^) OR(InclusiveOR)( ) 18 Logical and Relational Operators: These are binary operations that gives a Boolean result. This means that expressions with these operators return TRUE or FALSE values. ZeroistakenasFALSEandanon-zerovalueistakenasTRUE. Logical operators are: Negation or NOT(!) logicaland && logical OR 20 5
Relational Operators: These operators are used in operations where a comparison is to be made. In essence these operators ask about the relationship of two expressions in order to gain a TRUE or FALSE reply. These operators include: Is Equal to (== ) Is Not Equal to (!=) Less Than ( <) Less Than or Equal to (<= ) Greater Than (> ) Greater Than or Equal to (>= ) Here is an example; ( x ==y ) FALSE Assume that x = 3and y = 5. ( x!=y) TRUE 21 ( x >y ) FALSE Bit masking is a operation where single bits of a variable or register are changed. Bit masking is a common way to control microcontroller s peripherals (I/O) since single bits in microcontroller s registers represent some change to the state of the system, for example, enabling interrupts. Logical operators AND (&), OR ( ), XOR ( ˆ ) and COMPLEMENT ( ) are utilised to change single bits in a register without modifying the rest bits of the register value. In addition, SHIFT (<<, >>) operators are used to simplify changing the known bit in the register. 23 Note that the equality operator is == and not =. The equality sign alone( = ) is an assignment operator. Ifyouwanttocomparetwovaluesforequalitythen == shouldbe used instead of =.For instance if wewish to assign the valueof a tobwewritea=b. Ifwewanttocheckifthevalueofbisequaltoa,wewritea==b. The following code example shows how bit values are changed to attain the required register value. Set and clear single bit PORTA = PORTA 0x20; // Set bit 5 (bits 0, 1,..., 7) DDRA = DDRA & ~0x20; // Clear bit 5 DDRA = DDRA (1 << 5); // Set bit 5 using shift operator Set and clear multiple bits PORTD = PORTD 0x50; // Set bits 4 and 6 DDRD = DDRD & ~0x50; // Clear bits 4 and 6 PORTD = (PORTD << 4); // Shifting PORTD 4 bits to left 22 24 6
Increment operators: This operator modifies the value of a variable by increasing it by 1. Increment operators can be applied to variables as prefix or postfix, for example, x=x+1;isthesameas ++x; // pre increment operation x++; // post increment operation Decrement operators: This operator modifies the value of a variable by decreasing it by 1. Decrement operators can be applied to variables as prefix or postfix, for example: y=y-1 isthesameas --y y-- // pre increment operation // post increment operation 25 27 Letstakeaquicklookatanexample; Leta=1;and b=3*a++; Whatisthevalueofaandbrespectively? b=3anda=2. Nowleta=1;and b=3*++a; Whatisthevalueofaandbrespectively? b=6anda=2. 26 Compound Assignment Operators: These operators are used as a method to reduce the amount syntax required during the construction of a program. Here are some examples: (i) a+=3; //a=a+3 (ii) b-=3; //b=b 3 (iii)c*=5; //c=c*5 (iv)d/=a; //d=d/a (v)porta =0x20; //PORTA=PORTA 0x20 (vi)ddra&=~0x20;//ddra=ddra&(~0x20) NB, these expressions are processed from right to left. 28 7
Operator Precedence Rules Name Level Operators Order of evaluation Primary 1 [ ] ( ) -> L to R Unary 2 + sizeof ( )! ++ R to L Binary 3 * / % L to R Arithmetic 4 + - L to R Shift 5 << >> L to R Relational 6 < <= > >= L to R Control statements are used to control the flow of execution of a program. Among these statements are if/else, switch/case, and loop sentence likewhile,dowhile,and for. If/else statements are used to guide or branch an operation in either one of two directions. Theloopstatements(while,dowhile and for) areusedto controlthe repetition of a block of instructions. switch/case statements are used to make a decision from a block of severalinstructionsinorder to allow theprogram to flow inaconcise manner. 29 31 Name Level Operators Order of evaluation Equality 7 ==!= L to R Bitwise 8 & L to R Bitwise 9 ^ L to R Bitwise 10 L to R Logical 11 && L to R Logical 12 L to R Conditional 13?: R to L Assignment 14 &= -= = <<= >>= R to L The While Loop This is one of the most basic control elements of a program. The format in which the whilestatement is used is as follows: while(expression) or while(expression) statement; statement1; statement2;. 30 32 8
#include <stdio.h> unsigned char c; c = 1; printf("start of program \n"); while(c <= 100) printf("c = %d\n", int(c)); c++; printf("end of program \n"); while(1); This loop is often used where data is to be read. The test then verifies the data, and loops back to read again if it was unacceptable. The format of the do/whilestatement is as follows. do or do statement; statement1; while (expression); statement2; while(expression); 33 35 The do/while Loop This is very similar to the while loop except that the expression is tested after the loop body has been executed one time. This means that the instructions in a do/while loop areexecuted atleastoncebeforethedecisionismade onwhetherornottoremainintheloop. In the while construct, the test is made before the instructions in the loop are executed even once. 34 #include <stdio.h> unsigned char c; c = 0; printf("start of program \n"); do printf("c = %d\n", int(c)); c++; while(c < 100); printf("end of program \n"); while(1); 36 9
TheForLoop A for loop construct is usually used to execute a statement or a statement block for a specific number of times. This construct takes three arguments each separated by semi-colons. 1. The first is run before the loop is entered. This is usually the initialisation of the loop variable. 2. Thesecond isatest, theloopisexitedwhenthisreturnsfalse. 3. The third is a statement to be run every time the loop body is completed. The for loop is extremely flexible and allows many types of program behaviour to be specified simply and quickly. The if/else statements are used to guide or branch the operation of the program based on the evaluation of a conditional statement. An if/else statement has the form; If (expression) statement1; statement1; else statement1; statement2; 37 39 #include <stdio.h> unsigned char c; c = 0; printf("start of program \n"); for(c = 1; c <= 100; c++) printf("c = %d\n", int(c)); printf("end of program \n"); while(1); 38 The following test decides whether a student has passed an exam with a pass markof40 if(result>=40) printf("pass\n"); else printf("fail\n"); Other case is with if/else if sentence structure: if(expression1) statement1; else if(expression2) statement2; else if(expression3) statement3;... else(expression n) statement n; 40 10
#include <stdio.h> unsigned char c; c = 0; printf("start of program \n"); for(c = 0; c < 100; c++) printf("end of program \n"); while(1); if(c < 33) printf("0<c<33 "); else if ((c>32) && (c<66)) printf("33<c<66"); else printf("66<c<100"); 41 A switch/case statement is written in the following way. switch (expression) case constant1: statement1; statement2; case constant2: statement3; statement4; case constant3: statement5; statement6; default: statement7; 43 The switch case statement is used to execute a statement, or a group of statements selected by the value of an expression. This control statement is used in cases where; Only one variable (expression) is tested, all branches must depend upon the value of that variable (expression). The variable must be an integer type. Each possible value of the variable(expression) controls a branch. 42 unsigned char displayled(unsigned char blink) unsigned char display = 0; switch(blink) case 1 : display = 0b00000001; case 2 : display = 0b00000010; case 3 : display = 0b00000100; case 4 : display = 0b00001000; default : display = 0b00000000; return display; 44 11
Posted on website Assignment 2 Due: Tuesday October-3-2017 @2:30pm 45 12