Lecture2 Introduction C Langugue

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 84

VietNam National University

University of Engineering and Technology

EMBEDDED SYSTEM FUNDAMENTALS


(ELT3240, NHẬP MÔN HỆ THỐNG NHÚNG)

Dr. Nguyễn Kiêm Hùng


Email: kiemhung@vnu.edu.vn

Laboratory for Smart Integrated Systems


Introduction to VietNam National University
Week
Embedded Systems 1-2
University of Engineering
Introduction to Cand Technology
Week
Languague 3

CPU: Week
ARM Cortex-M 4

Curriculum Memory
and Interfaces
Week
5-6

Path ARM-based Week


7
Embedded System

Embedded Software Week


8-9

Real-time Week
Operating systems 10-12

Interfacing Embedded Week


With Real-World 13-14

Project Week
Laboratory for Smart Integrated Systems 15
Objectives

In this lecture you will be introduced to:


– Some important C programming concepts widely
used in embedded system design

Laboratory for Smart Integrated Systems 3


Outline
• Overview of C Programming
• First C program: Hello World!
• Data types
• Variables
• Operations
• Control Structures
• Functions
• Summary

Laboratory for Smart Integrated Systems


Two approaches in programming the ARM chips

• Use the functions written by the vendor to access the peripherals.


– These device library functions are copyrighted and cannot be used with
another vendor’s ARM chip.
– You have no control over the functions and it is very hard to customize them for
your project.
– Easy and save time to development

• Create your own custom library to access the peripheral’s special


function registers
– functions can be modified and used with another vendor.
– you have total control over each function
– Difficult and take a lot of time

Laboratory for Smart Integrated Systems


Why C language for Embedded Systems?

• C is a general purpose language


– closely associated with UNIX since this operating system is written in C.

• C is a relatively low-level language


– easily manipulate characters, numbers and addresses using the range of arithmetic and
logical operations normally implemented by actual machines.
– single-thread control flow constructions

• C is relatively small and can be learnt quickly

• A C compiler can be simple and compact.


– because the data types and control structures provided by C are supported directly by
most existing machines the run-time library needed to implement self contained
programs is tiny.

Laboratory for Smart Integrated Systems


Background
• Designed by Dennis Richie (1944-2011) at Bell Labs in the early
1970’s.
– a general purpose programming language
– low-level features make it attractive for systems programming
• UNIX was originally written in C.
• Standardized by American National Standards Institute (ANSI) in 1989
(C89 standard),
• Standardized and revised by ANSI and International Organization for
Standardization (ISO) in 1994 (C95), 1999 (C99).
• Now, C is the most popular programming language..
• How to start?
– The text by Brian Kernighan and Dennis Ritchie is an accepted base reference
but is not suitable for novice programmers.

Laboratory for Smart Integrated Systems


Overview of C Programming
• A C program is composed of one or more
source files, each of which contains some
part of the entire C program – typically some
of external functions.

• Common declarations are often collected into


header files and are included into source
files with a special #include command.

• One external function must be named main;


this function is where your program starts.

• A C compiler processes each source file and


translates it into instructions that are
understood by the computer (object code).
The output of the compiler is usually called
object code or object modules.

• When all the source files are compiled the


object modules are passed to a program
called the linker which resolves external
address references to produce one
executable (.exe).

Laboratory for Smart Integrated Systems


Basic C program structure

Laboratory for Smart Integrated Systems


Microcontroller “header file”

• KeilMDK-ARM provides a derivative-specific“header file” for each


microcontroller, which defines memory addresses and symbolic
labels for CPU and peripheral function register addresses.

Laboratory for Smart Integrated Systems


C Pre-Processor

• Most C programs begin with a few statements that start with a # symbol

• These are interpreted by the C pre-processor

Laboratory for Smart Integrated Systems


The C Pre-processor
• The #define is the simplest and most common of these extensions.
– A definition of the form
#define YES 1
calls for a macro substitution, replacing a name by a string of characters.

• #include “filename”
– to include the contents of other files during compilation
– #include “filename” is replaced by the contents of the file “filename”

• Often a line or two of this form appears at the beginning of each source file.

Laboratory for Smart Integrated Systems 12


Macro substitution
• It is also possible to define macros with arguments, so the replacement text
depends on the way the macro is called.
#define swap(a, b) {int temp; temp = a; a = b; b = temp;}
#define SIZE 5

int main()
{
typedef enum {FALSE, TRUE} Boolean;
int buff[SIZE] = {1,3,5,2,4};
int i;
Boolean flag;

do {
flag = FALSE;
for (i=0; i<SIZE; ++i) {
if ( buff[i-1] < buff[i] ) {
swap(buff[i-1], buff[i]);
flag = TRUE;
}
}
} while ( flag == TRUE );
for (i=0; i<SIZE; i++)
printf(" %i,", buff[i]);
printf("\n");
}

Laboratory for Smart Integrated Systems 13


Nested #include
• #include declarations may be nested
– an include file may contain further #include declarations and so on...

• Larger programs, comprising several separate source files may


contain multiple #include references to the same file. To prevent
multiple copies the declarations in included files are usually
processed conditionally
#define _COND_INCLUDE_H

#ifndef _COND_INCLUDE_H

#define swap(a, b) {int temp; temp = a; a = b; b = temp;}


#define SIZE 5

#endif /* _COND_INCLUDE_H */

Laboratory for Smart Integrated Systems 14


C statement types
• Simple variable assignments
– Includes input/output data transfers
• Arithmetic operations
• Logical/shift operations
• Control structures
– IF, WHEN, FOR, SELECT
• Function calls
– User-defined and/or library functions

Laboratory for Smart Integrated Systems


Statement vs. Statement Group
• In C, the semicolon is a statement terminator.

• The braces { and } are used to group declarations and statements together into a
compound statement or block, so they are syntactically equivalent to a single
statement.

• The braces that surround a function are one obvious example.

• Braces around multiple statements after an if, else, while or for are another.

• Variables can actually be declared inside any block; but they are usually grouped
together at the start of the function.

• There is never a semicolon after the right brace that ends a block.

Laboratory for Smart Integrated Systems


Outline
• Overview of C Programming
• First C program: Hello World!
• Data types
• Variables
• Operations
• Control Structures
• Functions
• Summary

Laboratory for Smart Integrated Systems


First C program: Hello World!

standard library module

main function

Comment

function body

• PRINTF function is one of the functions provided in the C Standard Library


fsl_debug_console.h
 not part of the C programming language
• #include <fsl_debug_console.h> declares printf and other UART functions.
• The Linker locates the function and inserts its address so the complete program
can be executed.

Laboratory for Smart Integrated Systems


Outline
• Overview of C Programming
• First C program: Hello World!
• Data types
• Variables
• Operations
• Control Structures
• Functions
• Summary

Laboratory for Smart Integrated Systems


C Data Types
Data type Size Range of Values
char k; 1 byte 0 to 255
unsigned char k;
uint8_t k;
signed char k; 1 byte -128 to 127
int8_t k;
short k; 2 byte -32,768 to 32,767
signed short k;
int16_t k;
unsigned short k; 2 bytes 0 to 65,535
uint16_t k;
int k; 4 bytes -2,147,483,648 to 2,147,483,647
signed int k;
int32_t k;
unsigned int k; 4 bytes 0 to 4,294,967,295
uint32_t k;

• By default variables are considered as signed unless the unsigned keyword is used with the exception of char.
• intx_t and uintx_t (ISO C99 standard) defined in stdint.h

Laboratory for Smart Integrated Systems


C Data Types
• Always match data type to data characteristics!
• Variable type indicates how data is represented
– Number of bits determines range of numeric values
– signed/unsigned determines which arithmetic/relational
operators to be used by the compiler
– non-numeric data should be “unsigned”
• Header file “stdint.h” defines alternate type names for standard C
data types
• Eliminates ambiguity regarding number of bits
• Eliminates ambiguity regarding signed/unsigned

Laboratory for Smart Integrated Systems


Constant/literal values
• Decimal is the default number format
int m, n;//16-bit signed numbers
m = 453; n = -25;
• Hexadecimal: preface value with 0x or 0X
m = 0xF312; n = -0x12E4;
• Octal: preface value with zero (0)
m = 0453; n = -023;
Don’t use leading zeros on “decimal” values. They will be interpreted as octal.
• Character: character in single quotes, or ASCII value following “slash”
m = ‘a’; //ASCII value 0x61
n = ‘\13’; //ASCII value 13 is the “return” character
• String (array) of characters:
unsigned char k[7];
strcpy(k,“hello\n”); //k[0]=‘h’, k[1]=‘e’, k[2]=‘l’, k[3]=‘l’, k[4]=‘o’,
//k[5]=13 or ‘\n’ (ASCII new line character),
//k[6]=0 or ‘\0’ (null character –end of string)

Laboratory for Smart Integrated Systems


C is a strongly typed language
• A strongly-typed programming language is one in which each type of data (such as
integer, character, hexadecimal, packed decimal, and so forth) is predefined as part
of the programming language.
• All constants or variables defined for a given program must be described with one
of the data types.
• Certain operations may be allowable only with certain data types.
• The compiler enforces the data typing and use compliance.
• An advantage of strong data typing is that it imposes a rigorous set of rules on a
programmer and thus guarantees a certain consistency of results.
• A disadvantage is that it prevents the programmer from inventing a data type not
anticipated by the developers of the programming language and it limits how
"creative" one can be in using a given data type.

Laboratory for Smart Integrated Systems


Type Conversions
• When operands of different types appear in expressions they are converted to a
common type according to a number of rules.
• Often, this happens automatically (although sometimes the compiler will issue a
warning message – depends on warning level).
#include <stdio.h>

int main()
{
int a;
char buff[80];
int sum;

printf("Enter Number: ");


scanf("%i", &a);
printf("Enter String: ");
scanf("%s", &buff);

sum = a + buff[0];

printf("Sum: %i\n", sum);


}

• If string = “hello” and a = 10 then sum is 114 (why?)

Laboratory for Smart Integrated Systems


Explicit Type Conversion
• Type conversions can be forced (coerced ) in any expression
with a construct called a cast.
#include <stdio.h>

int main()
{
int a = 0;
float b = 0.0f;
int sum;

printf("Enter Integer: ");


scanf("%i", &a);
printf("Enter Float: ");
scanf("%f", &b);

sum = a + (int)b; /* cast */

printf("Sum: %i\n", sum);


}

Laboratory for Smart Integrated Systems


Outline
• Overview of C Programming
• First C program: Hello World!
• Data types
• Variables
• Operations
• Control Structures
• Functions
• Summary

Laboratory for Smart Integrated Systems


Program variables
• A variable is an addressable storage location to be used by
the program
– Each variable must be declared to indicate size and type of
information to be stored, plus name to be used to reference the
information
int x,y,z; //declares 3 variables of type “int”
char a,b; //declares 2 variables of type “char”
– Space for variables may be allocated in registers, RAM, or
ROM/Flash (for constants)
– Variables can be automatic or static

Laboratory for Smart Integrated Systems


Variable Assignment Operator
• Contents of a memory location is changed by an assignment statement.
– ‘=‘ denotes an assignment; e.g.

a = b; /* variable assignment */

a = 6; /* constant assignment */

h = 0xffff; /* constant specified as 16-bit hexadecimal */

c = ‘x’; /* char constant */

s = “I am a string”; /* string constant */

• Constants and variables can be combined with arithmetic, logical, and relational
operators to form compound statements.

a = a + 1;

a = b * 10 + 2;

Laboratory for Smart Integrated Systems


External variables

• Defined outside of the present source module the


keyword extern
• Referenced by any function from any file in the
software system
• Only global declarations can be designated extern

extern short ExtGlobal; /* an external global variable*/


void main(void){
ExtGlobal = 1000;
}
Laboratory for Smart Integrated Systems
Automatic variables

• Declare within a function/procedure


• Variable is visible (has scope) only within that
function
– Space for the variable is allocated on the system stack
when the procedure is entered
• De-allocated, to be re-used, when the procedure is exited
– If only 1 or 2 variables, the compiler may allocate them
to registers within that procedure, instead of allocating
memory.
– Values are not retained between procedure calls

Laboratory for Smart Integrated Systems


Automatic variables: Example
void delay () {
Int i,j; //automatic variables –visible only within delay()
for (i=0; i<100; i++) { //outer loop
for (j=0; j<20000; j++) { //inner loop
} //do nothing
}
} Variables must be initialized each
time the procedure is entered since
values are not retained when the
procedure is exited.

MDK-ARM (in my example): allocated registers r0,r2 for variables i,j

Laboratory for Smart Integrated Systems


Static variables
• Static variables are a third class of storage, in addition to the extern
and automatic variables.
• Declare either within or outside of a function:
– Internal static variables are local to the function in which they are declared but
unlike automatics they remain in existence rather than coming and going each
time the function is invoked. This means that internal static variables provide a
private, permanent storage in a function.
• insert key word static before the variable definition. Emxample:
static unsigned char bob;
static intpressure[10];
– External static variables are visible within the remainder of source file within
which they are declared, but not within any other file.
• Use “normal” declarations. Example:
int count;

Laboratory for Smart Integrated Systems 32


Static variables: example (1)
unsigned char count; //global variable is static –allocated a fixed RAM location
//count can be referenced by any function
void math_op() {
int i; //automatic variable –allocated space on stack when function entered
static int j; //static variable –allocated a fixed RAM location to maintain the value
if (count == 0) //test value of global variable count
j = 0; //initialize static variable j first time math_op() entered
i= count; //initialize automatic variable i each time math_op() entered
j = j + i; //change static variable j –value kept for next function call
} //return & deallocatespace used by automatic variable i
void main(void) {
count = 0; //initialize global variable count
while (1) {
math_op();
count++; //increment global variable count
}
}

Laboratory for Smart Integrated Systems 33


Static variables: example (2)
#include <stdio.h>

/* function prototype */
int a(void);

int a(void)
{
static int i = 10;
i++;
return(i);
}

int main()
{
int p, n;

for (n=1; n < 10; n++) {


p = a();
printf("Invocation %i, return value %i\n", n, p );
}
}

Laboratory for Smart Integrated Systems


Register variables
• The fourth and final class of storage is register. A register declaration
advises the compiler that the variable will be heavily used . If possible, register
variables are placed in the processor’s registers as these provide the fastest access.

int checkspace(f,c)
register int f;
register char c;
{
if (c == ' ')
f++;
return(f);
}

int main()
{
char buff[MAXLINE];
register int i;
int n,j=0;

n = getline(buff, MAXLINE);
for (i=0; i<n; i++)
j = checkspace(j,buff[i]);
printf("Number of spaces: %i\n", j);
}

Laboratory for Smart Integrated Systems


Constant vs. Volatile Variable
• const: applying the keyword const in a declaration indicates to the compiler that
the object is to be treated as a constant and may not be altered. For example,

const int size = 10;

• volatile: applying the keyword volatile in a declaration indicates to the compiler


that the contents of the object is subject to unpredictable alterations and should
not be optimised. For example, it may be a variable which will be changed by an
interrupt service routine, or an I/O register which will be changed by an I/O device.
For example,

volatile unsigned char io_register


/* byte sized I/O register */

Laboratory for Smart Integrated Systems 36


Constant vs. Volatile Variable
• volatile:

#define GPIO_PORTA_DATA_R (*((volatile unsigned long *)0x400043FC))


void Collect(void){ short i;
for(i=0;i<100;i++){ /* collect 100 measurements */
data[i] = GPIO_PORTA_DATA_R; /* collect ith measurement */
}
}

Laboratory for Smart Integrated Systems 37


Pointers and Addresses
• Pointers are probably the most difficult concept in C.
• A pointer is a variable that contains the address of another variable.
• Pointers are very common in C because they usually lead to more compact and
efficient code.
• Since a pointer contains the address of an object, it is possible to access the object
indirectly through the pointer.
• Consider the code fragment:

int x = 6; /* integer variable x */


int y ; /* integer variable y */
int *px; /* variable px is pointer to an integer */

px = &x ; /* assign address of x to variable px */


y = *px ; /* assign contents of x to y */

Laboratory for Smart Integrated Systems


Pointers
Memory Memory Memory Memory
Address Contents Address Contents

n n
n+1 x main’s variables n+1 x
Pointer
n+2 y n+2 y

n+3 n+3

• a • a = n+1
function’s local
• b copies • b = n+2
• •

When variables are passed-by-value When variables are passed-by-reference


copies of the input arguments are made the input arguments are memory addresses
when the function is called. These are local (obtained using &). These are locally copied (as
copies; they are extinguished when the function before), but they are used locally to change the
value of the variables they ‘point’ at.
terminates.
When we declare a pointer we must say what
type of variable it points at (using *).

Laboratory for Smart Integrated Systems 39


Arrays
• An array is a set of data, stored in consecutive memory
locations, beginning at a named address
– Declare array name and number of data elements, N
int n[5]; //declare array of 5 “int” values
– The array name is actually a pseudonym for the address of the
first element.
• i.e. name is a pointer to the first element.
– Elements are “indexed”, with indices [0 .. N-1]
n[3] = 5; //set value of 4tharray element
Note: Index of first element is always 0.
indice

• We can also access elements through a pointer, e.g.


p = x+9;

Laboratory for Smart Integrated Systems


Arrays
#include <stdio.h>

int main() {

int x[8];
int i;
int *p; /* p is pointer to an int */

for (i=0; i<8; i++)


x[i] = i;

for (i=0; i<8; i++)


printf("element %i = %i\n", i, x[i]);

for (i=0; i<8; i++) {


p = x + i;
*p = 8-i;
}

for (i=0; i<8; i++)


printf("element %i = %i\n", i, x[i]);

Laboratory for Smart Integrated Systems 41


Structures
• A structure is a collection of one or more variables, possibly different types,
grouped together under a single name for convenient handling.
• Structures help to organise data because they permit a group of related variables
to be treated as a unit instead of separate entities.
• The structure can be defined using the C statement “struct”.

struct clock { /* structure of the clock record */


unsigned char hour; /* hour */
unsigned char min; /* minute */
unsigned char sec; /* second */
unsigned short msec; /* milliseconds */
} timer;

• An optional name called a structure tag may follow the word struct (as with
clock here). The tag can be used to refer to the structure.

Laboratory for Smart Integrated Systems 42


struct variables
• The right brace that terminates the struct can be followed by a list of variables, just as for
any basic type. That is,

struct { . . . } x, y, z;

is syntactically analogous to

int x, y, z;

• A structure declaration that is not followed by a list of variables allocates no storage; it


simply describes a template for the structure. However, if the structure is tagged, this name
can be used in variable declarations.

struct clock timer;

• The members of a structure can be referred to using the “.” operator, as in

timer.sec = 60;

Laboratory for Smart Integrated Systems


typedef
• The keyword typedef enables new data type names to be created. For example,

typedef struct clock time_t;


/* time_t is synonym for struct clock */
time_t timer; /* better timer var declaration */

• typedef is often used to define shorthand type names, for example, Keil often
include the header <stdint.h> in their programs, here is fragment:
/* exact-width signed integer types */
typedef signed char int8_t;
typedef signed short int int16_t;
typedef signed int int32_t;
typedef signed long long int int64_t;

• To make type identifiers stand out in a program the convention that names are
terminated with _t is sometimes adopted (t == type)

Laboratory for Smart Integrated Systems


Accessing Structure elements
• Can access individual fields within a structure using dot notation, e.g.
– clock.hours = 1;

• Can also access fields within a structure via a pointer, e.g.


– pclock->hours = 1; /* pclock is a pointer to clock */

Laboratory for Smart Integrated Systems


Struct Example
#include <stdio.h>

int main() {

typedef struct {
int hours;
int mins;
int secs;
} time;

time clock;
time *ptime; /* pointer to time struct */

/* accces struct field via dot notation */


clock.hours = 1;
clock.mins = 10;
clock.secs = 59;

printf("The time is %i : %i : %i \n", clock.hours, clock.mins, clock.secs);

/* access struct field via pointer */


ptime = &clock;
ptime->hours = (clock.hours+1)%12;
ptime->mins = (clock.mins+1)%60;
ptime->secs = (clock.secs+1)%60;

printf("The time is %i : %i : %i \n", clock.hours, clock.mins, clock.secs);

Laboratory for Smart Integrated Systems


Structures and Peripherals I
• Embedded processors often contain parallel I/O, USART, Timers etc…
– Each of these peripherals have an associated set of registers which allows it to be
configured and used (e.g. GPIO port E, in Labs 1 and 2).

• The register set for each peripheral is defined as a struct


– When the compiler sees a struct declaration it reserves memory space. By arranging for
this space to map onto the peripheral registers we can neatly reference each of the
registers.

• We use this statement to output a count (i) to the LEDs in Lab 2


– GPIOE->ODR = i << 8;

Output Data Register (ODR) is a field defined within a struct


See next slide
GPIOE is a pointer to the struct

Laboratory for Smart Integrated Systems


Structures and Peripherals II
• GPIO port A-E pins can be
configured in a variety of modes
– Configured by writing to the port
control register.
• The registers themselves are
memory mapped into the ARM
cortex address space.

• Access to the ODR actually


resolves to a memory address.

• How to arrange for this?

Laboratory for Smart Integrated Systems


Structures and Peripherals II

Note: cf line 1127 of stm32f10x_cl.h

Note: cf line 371 of stm32f10x_cl.h

http://dics.voicecontrol.ro/dicsEE-IP/chapter/Setting%20GPIO%20manually

Laboratory for Smart Integrated Systems


Outline
• Overview of C Programming
• First C program: Hello World!
• Data types
• Variables
• Operations
• Control Structures
• Functions
• Summary

Laboratory for Smart Integrated Systems


Arithmetic operations
• C supports with standard arithmetic operators
inti, j, k; // 32-bit signed integers
uint8_t m,n,p; // 8-bit unsigned numbers
i= j + k; // add 32-bit integers
m = n -5; // subtract 8-bit numbers
j = i* k; // multiply 32-bit integers
m = n / p; // quotient of 8-bit divide
m = n % p; // remainder of 8-bit divide
I = (j + k) * (i-2); // Arithmetic Expression

*, /, % are higher in precedence than +, -(higher precedence applied 1st)


Example: j * k + m / n = (j * k) + (m / n)

Laboratory for Smart Integrated Systems


Second C Program: Add Two integers

Note: Retarget.c redefines fgetc( ) for scanf( )

• The & operator gives the address of an object


– we use &a to pass scanf the address of variable a

• The % operator identifies a format specification (%i refers to integer)

Laboratory for Smart Integrated Systems


Bit-wise Operations in C
• These bit-wise operators are widely used in software engineering for
embedded systems and control

Laboratory for Smart Integrated Systems


Bit-wise Operations in C
• Bit-parallel (bitwise) logical operators produce n-bit results of the
corresponding logical operation:

Laboratory for Smart Integrated Systems


Bit-wise Operations in C
int main (void)
{
volatile unsigned char temp; /* declare volatile otherwise the optimizer will remove it. */
temp = 0x35 & 0x0F; /* ANDing : 0x35 & 0x0F = 0x05 */
temp = 0x04 | 0x68; /* ORing : 0x04 | 0x68 = 0x6C */
temp = 0x54 ^ 0x78; /* XORing : 0x54 | 0x78 = 0x2C */
temp = ~0x55; /* Inverting : ~0x55 = 0xAA */
while (1);
return 0;
}

Laboratory for Smart Integrated Systems


Setting and Clearing (masking) bits

int main(void)
{
unsigned char var1;
while(1)
{
var1 = var1 | 0x10; /* Set bit 4 (5th bit) of var1 */
delay();
var1 = var1 & 0xEF; /* Clear bit 4 (5th bit) of var1 */
}
return 0;
}

The following program toggles only bit 4 of var1 continuously without disturbing the
rest of the bits?

Laboratory for Smart Integrated Systems


Setting and Clearing (masking) bits

int main(void)
{
unsigned char var1;
while(1)
{
var1 = var1^0x10; /* Toggle bit 4 (5th bit) of var1 */
delay();
}
return 0;
}

The following program toggles only bit 4 of var1 continuously without disturbing the
rest of the bits?

Laboratory for Smart Integrated Systems


Setting and Clearing (masking) bits
• Peripherals (e.g. GPIO ports, ADC etc.) are often configured
and controlled by a set of registers. Individual bits of the
register may need to be read (or written).
• If a register bit (or group) is written (to 1 or 0) then it is
usually the case that the other bits are left unchanged.

When reading a register we can


identify individual bits using a so-
called MASK which is bit-wise
AND’ed with the register
contents.
(Eg. Line 32 tests bit 7 of the
GPIOB registe).

Laboratory for Smart Integrated Systems


Testing bit with bit-wise operators in C

while(1)
{
if (var1 & 0x20) /* check bit 5 (6th bit) of var1 */
var2 = 0x55; /* this statement is executed if bit 5 is a 1 */
else
var2 = 0xAA; /* this statement is executed if bit 5 is a 0 */
}

Write a C program to monitor bit 5 of var1. If it is HIGH, change value of var2 to


0x55; otherwise, change value of var2 to 0xAA.

Laboratory for Smart Integrated Systems


Bit-wise shift operation in C

1. 0b00010000 >> 3 /* it equals 00000010. Shifting right 3 times */


2. 0b00010000 << 3 /* it equals 10000000. Shifting left 3 times */
3. 1 << 3 /* it equals 00001000. Shifting left 3 times */

Laboratory for Smart Integrated Systems


Bit-wise shift operation in C
• Shift operations are also useful for creating masks

Line 24 sets bit 6 of the Reset and Clock Control APB2ENR register
(leaving the other bits unchanged).

Laboratory for Smart Integrated Systems


Outline
• Overview of C Programming
• First C program: Hello World!
• Data types
• Variables
• Operations
• Control Structures
• Functions
• Summary

Laboratory for Smart Integrated Systems


C control structures
• Control order in which instructions are executed
(program flow)
• Conditional execution
― Execute a set of statements if some condition is met
― Select one set of statements to be executed from several
options, depending on one or more conditions
• Iterative execution
― Repeated execution of a set of statements
 A specified number of times, or
 Until some condition is met, or
 While some condition is true

Laboratory for Smart Integrated Systems


Relational Operators
• Test relationship between two variables/expressions
• Compiler uses
signed or
unsigned
comparison, in
accordance with
data types
Example:
unsigned char a,b;
int j,k; if (a < b) –
unsigned if (j > k)
- signed

Laboratory for Smart Integrated Systems


Boolean operators
• Boolean operators &&(AND) and ||(OR) produce
TRUE/FALSE results when testing multiple
TRUE/FALSE conditions
if ((n > 1) && (n < 5)) //test for n between 1 and 5
if ((c = ‘q’) || (c = ‘Q’)) //test c = lower or upper case Q
• Note the difference between Booleanoperators &&,
|| and bitwise logical operators &, |

if ( k && m) //test if k and m both TRUE (non-zero values)


if ( k & m) //compute bitwise AND between m and n,
//thentest whether the result is non-zero (TRUE)

Laboratory for Smart Integrated Systems


Common error
• Note that ==is a relational operator, whereas = is an
assignment operator.

if ( m == n) //tests equality of values of variables m and n


if (m = n) //assignsvalue of n to variable m, and then
//tests whether that value is TRUE (non-zero)

The second form is a common error (omitting the second equal


sign), and usually produces unexpected results, namely a
TRUE condition if n is 0 and FALSE if n is non-zero.

Laboratory for Smart Integrated Systems


If-Else

#include <stdio.h>

int main()
{
int a;

printf("Enter Number: ");


scanf("%i", &a);
if (a < 0)
printf("Negative number input");
else
printf("Positive number input");
}

Laboratory for Smart Integrated Systems


Else-if

#include <stdio.h>

int main()
{
int a;

printf("Enter Number: ");


scanf("%i", &a);
if (a < 0)
printf("Negative number input\n");
else if (a = 0)
printf("Zero number input\n");
else
printf("Positive number input\n");
}

Laboratory for Smart Integrated Systems


Switch
#include <stdio.h>

int main()
{
unsigned int a;

printf("Enter Number: ");


scanf("%i", &a);
switch (a) {
case 0: printf("zero\n");
break;
case 1: printf("one\n");
break;
case 2: printf("two\n");
break;
case 3: printf("three\n");
break;
default: printf("more than three\n");
break;
}
}

Laboratory for Smart Integrated Systems


While

#include <stdio.h>

int main()
{
int a;
unsigned int b;

printf("Enter Positive Number: ");


scanf("%i", &a);
while (a < 0) {
printf("Invalid Input...");
printf("Enter Positive Number: ");
scanf("%i", &a);
}
b = a;
}

Laboratory for Smart Integrated Systems


do-while
#include <stdio.h>

int main()
{
int a;
unsigned int b;

do {
printf("Enter Positive Number: ");
scanf("%i", &a);
}
while (a < 0);
b = a;
}

Laboratory for Smart Integrated Systems


for
#include <stdio.h>
#define SIZE 26

int main()
{
char buff[SIZE];
unsigned int idx;

for (idx = 0; idx < SIZE; idx++)


buff[idx] = 0x60+idx+1;
buff[SIZE] = '\0'; /* add string terminator */

printf("%s\n", buff);
}

• What will this program print?

Laboratory for Smart Integrated Systems


Break
int main()
{
int n;
char line[MAXLINE];

while ( ( n = getline(line, MAXLINE) ) > 0 ) {


while (--n >= 0)
if (line[n] != ' ' && line[n] != '\t'
&& line[n] != '\n')
break;
line[n+1] = '/0';
printf("%s\n", line);
}
}

• getline returns the length of the line.

• The inner while loop starts at the last character of line (recall --n (pre)
decrements n before using the value), and scans backwards looking for the first
character that is not a space, tab or newline. The loop is broken when one is
found, or when n becomes negative (i.e. when the entire line has been scanned).

Laboratory for Smart Integrated Systems


Outline
• Overview of C Programming
• First C program: Hello World!
• Data types
• Variables
• Control Structures
• Functions
• Summary

Laboratory for Smart Integrated Systems


Scope
• Variables in main are private or local to main; because they are declared within
main no other function can have direct access to them.

• The same is true of variables in other functions; for example the variables in
getline are completely unrelated to those in main.

• Each local variable comes into existence when the function is called, and
disappears when the function exits; for this reason the variables are known as
automatic variables.

• As an alternative to automatic variables it is possible to define global variables


which can be accessed by any function.

• Because global variables remain in existence permanently they can be used to


share data between functions.
Laboratory for Smart Integrated Systems
Data sharing using global variables
#include <stdio.h>
#define MAXLINE 1000

/* globals */
char line[MAXLINE]; /* input line */

int main()
{
int len;
extern char line[]; /* extern declaration not strictly
necessary, but good practice */

while ( ( len = getline() ) > 0 ) {


while (--len >= 0)
if (line[len] != ' ' && line[len] != '\t'
&& line[len] != '\n')
break;
printf("%s\n", line);
}
}

• A small change to while condition


– while ( len = getline() > 0)
results in len always = 1; Why is that?

Laboratory for Smart Integrated Systems


Functions
• Functions partition large programs into a set of smaller
tasks
– Helps manage program complexity
– Smaller tasks are easier to design and debug
– Functions can often be reused instead of starting over
– Can use of “libraries” of functions developed by 3rd parties,
instead of designing your own
• A function is “called” by another program to perform a task
– The functionmay return a result to the caller
– One or more arguments may be passed to the function/procedure

Laboratory for Smart Integrated Systems


Functions
• A function has the form:-
return type function_name (argument list, if any)
{
declarations and statements
}

• A minimal function is
– void dummy(void) { }

• A program is just a set of individual function definitions.

• Communication between functions is either


– by arguments and values returned by functions
– via external variables

• Function definitions can occur in any order within the source file or be split over
multiple files, so long as no individual function is split.

Laboratory for Smart Integrated Systems


Function Declarations
/* function prototype */
int getline(char s[], int lim);

int getline(char s[], int lim)


{
int c, i=0;

while (i<lim-1 && (c=getchar())!=EOF && c!='\n') {


s[i] = c;
i++;
}
if (c == '\n') {
s[i] = c;
i++;
}
s[i] = '\0';
return(i);
}

int main()
{ … etc.

• Functions are essentially a design (abstraction) tool


– they allow us to structure large tasks into smaller (more manageable) parts,
the detail of which can be hidden from those calling the function.

Laboratory for Smart Integrated Systems


Function Arguments

• Function arguments are passed by value


– the function receives a private, temporary copy of each argument, not its
address.
– this means that function cannot affect the original argument of the calling
function.
– Within the function, each argument is in effect a local variable.

• When an array name appears as an argument to a function, the


location of the array is passed; elements are not copied.
– arrays are passed by reference.

• Any variable may be passed by reference using the & operator to


obtain the address of the variable.

Laboratory for Smart Integrated Systems


pass-by-value vs pass-by-reference
• Lets write void swap(int a, int b)
{
int main()
{
swap(a, b) int temp; int x = 1, y = 2;

as a function. temp = a; swap(x,y);


printf("x = %i, y = %i\n", x, y);
a = b;
b = temp; }
• This doesn’t work...why? }

void swap(int *a, int *b) int main()


• Fixed...how? { {
int temp; int x = 1, y = 2;

swap(&x,&y);
temp = *a; printf("x = %i, y = %i\n", x, y);
*a = *b; }
*b = temp;
}

Laboratory for Smart Integrated Systems


Summary
• This week focused on aspects of C programming
• In particular, we looked at how to map registers
(used to control peripherals) to physical
addresses.
– You will see this topic arises quite often in the exam.

Laboratory for Smart Integrated Systems


References
1. Brian Kernighan and Dennis Richie, “The C Programming Language”,
Bell Telephone Laboratories, 1978.

– A good reference but not written for those new to C


– Contains some statement syntax which is not widely used (and is not covered in
this short introductory course.

2. Harvey M Deital and Paul J Deital, C: How to Program.

– A tutorial introduction.
• http://www.deitel.com/Books/C/CHowtoProgram7e/tabid/3635/Default.aspx

– ‘C’ Resources
• http://www.deitel.com/ResourceCenters/Programming/C/tabid/199/Default.aspx

Laboratory for Smart Integrated Systems


Review Questions

Laboratory for Smart Integrated Systems

You might also like