0% found this document useful (0 votes)
19 views

LECTURE 2 - Introduction To C Programming

The document discusses different programming languages used for microcontroller programming. It describes how machine language, assembly language and higher-level languages like C are used. It also discusses the advantages of using C over assembly language for microcontroller programming.

Uploaded by

s221091638
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

LECTURE 2 - Introduction To C Programming

The document discusses different programming languages used for microcontroller programming. It describes how machine language, assembly language and higher-level languages like C are used. It also discusses the advantages of using C over assembly language for microcontroller programming.

Uploaded by

s221091638
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

LECTURE 2:

Introduction to C Programming
PIC PROGRAMMING IN C
Microcontroller
Programming
Languages
PROGRAMMING LANGUAGES

 The lowest-level language is called


Machine languages. It means
those languages which are closer to
the understanding of machine rather
than human beings. A machine
language thus comprises a string of
binary 0’s and 1’s.

 Machine language is actually a coded


set of instructions for a particular CPU,
and it is also known as a machine
code.
 A machine language is designed to be
used by a computer without the need
of translation.
2
PROGRAMMING LANGUAGES
The microcontroller executes the program loaded in its Flash
memory.
All instructions that the microcontroller can recognize are together
called the Instruction Set (PIC16F877A has 35 different instructions
in total)

Process of writing executable code was endlessly tiring, the first


‘higher’ programming language called Assembly Language. It
made the process of programming more complicated

Instructions in assembly language are represented in the form of


meaningful abbreviations, and the process of their compiling into
executable code is left over to compiler.
PROGRAMMING LANGUAGES
However, programmers have always needed a programming
language close to the language being used in everyday life. As a
result, the higher programming languages have been created. One
of them is C.
The main advantage is simplicity of program writing.

4
PROGRAMMING LANGUAGES

A rough illustration of what is going on during the process of compiling the


program from higher to lower programming language.
6
ADVANTAGES OF HIGHER PROGRAMMING
LANGUAGES

Higher Programming Languages, such as C

Assembly Language
(a x b = a + a + a + … + a)
Since there is no appropriate instruction for
multiplying two numbers
Major Reasons for Writing Program in C
instead of Assembly

1. It is easier and less time consuming to write in


C than Assembly

2. C is easier to modify and update

3. You can use code available in function libraries

4. C code is portable to other microcontroller with


little or no modification
8
C Program Structure
BASICS OF C PROGRAMMING

Main Idea
To break a bigger problem down into several smaller pieces

Q. Write a program to measure temperature & show results on an LCD display.

Process of measuring is performed by


sensor that converts temperature into
voltage. MCU uses its ADC to convert this
voltage to a number which is then sent to
the LCD.

i. Activate and set built-in ADC


ii. Measure analogue value
iii. Calculate temperature
iv. Send data in the proper form to LCD

C enable us to solve the problem easily by writing 4 functions to be executed!!


Structure of a Simple Program

10
Program Structure
#include <xc.h>
#pragma config FOSC = HS
#pragma config WDTE = OFF
#pragma config PWRTE = ON
#pragma config BOREN = OFF
#pragma config LVP = OFF
#define _XTAL_FREQ 20000000
Structure of every
embedded-control
program written in C.
There will always be
two main parts:

i. Initialization  includes both the device peripherals initialization &


variables initialization, executed only once at the beginning
ii. Main loop  contains all the control functions that define the application
behavior, and is executed continuously
 A main function of any computer
program is to carry out calculations
and other forms of data processing
 Data structures are made up of
PIC16: C Data different types of numerical and
character variables, and a range of
Operations arithmetical and logical operations
are needed
 Microcontroller programs do not
generally need to process large
volumes of data, but processing
speed is often important
Variable Types

• Any number changing its value during program operation is


called a variable.
• Variable - to store the data values used in the program
• Variable labels are attached to specific locations when they
are declared at the beginning of the program
• MCU can locate the data required by each operation in the
file registers
• 4 basic types – integer, character, float & double
Variable Data Types

Good understanding of C data types can help programmers


to create smaller hex files.
Unsigned char – 8-bit data type that takes a value in the range of 0-255.
One of the most widely used data type for PIC16.
Remember…C compiler used signed char as the default.

Signed char – 8 bit (MSB D7 of D7—D0 used to represent the – or + value.


Range values from -128 to +127.)

Unsigned int –16-bit data type that takes a value in the range of 0-65535.
Used to define 16-bit variables such as memory addresses.
Also used to set counter values more that 256.
Remember…C compiler used signed int as the default.

Signed int – 16 bit (MSB D15 of D15—D0 used to represent the – or + value.
Range values from -32 768 to +32767.)
signed/unsigned int/char
Integer Number Format
Integer number can be written either in decimal, hexadecimal, octal or binary
form.

The compiler recognizes their format based on the prefix added.


If the number has no prefix, it is considered decimal by default.

FORMAT PREFIX

Decimal

Hexadecimal 0x or 0X

Octal 0 (number zero)

Binary 0b or 0B
Assignment Operations

A range of arithmetic and logic operations are needed


where single or paired operands are processed

The result is assigned to one of the operand variables


or a third variable

Assignment operator is the equal sign “=” and is used


to give a variable the value of an expression. i=0;
x=35;
sum=a+b;
ASSIGNMENT OPERATORS
Simple operators assign values to variables using the common ‘=’
character. For example: a = 8
Compound assignments are specific to C language and consist of
two characters as shown in the table. An expression can be written
in a different way as well, but this one provides more efficient
machine code.
BITWISE OPERATORS in C
Unlike logic operations being performed to variables, the bitwise
operations are performed to single bits within operands.

Bitwise operators are used to modify the bits of a variable.


Exercises
• Assuming a = 0x27 and b = 0b11000011
What is the result of the following
operation

i. PORTB = a<<3;
ii. Z = b>>4;
iii. PORTD = a & b;
iv. PORTC = b & 0xF0;
Arithmetic & Logical Operations
Arithmetic & Logical Operations
Exercises
1. Find the content of PORTB after the
following C code in each case:
a. PORTB=0x37 & 0xCA;
b. PORTB=0x37 | 0xCA;
c. PORTB=0x37 ^ 0xCA;

2. To set high certain bits we must OR them


with _______.

3. Find the contents of PORTC after execution


of the following code:
PORTC = 0;
PORTC = PORTC | 0x99;
PORTC = ~PORTC;
Conditional Operations

• Where a logical condition is tested in a while, if, or for statement,


relational operators are used
• One variable is compared with a set value or another variable, and
the block is executed if the condition is true

AND condition:
if((a > b) && ( c == d ))

OR condition:
if((a > b)||(c == d ))
Exercises
• Assuming a = 10, define result either
TRUE or FALSE

( a > 1)

( -a >= 0)

( a == 17)

( a != 3)
Constant’s Number
Integer constants can either be in decimal, hexadecimal, octal or binary form.
The compiler recognizes the constant number by a keyword const.
Number declaration is similar as assigning value to variable.

FORMAT PREFIX EXAMPLE

Decimal const MAX = 100

Hexadecimal 0x or 0X const MAX = 0xFF

Octal 0 const MAX = 016

Binary 0b or 0B const MAX = 0b11011101


Data Conversion
Program in C :BCD
Binary Coded Decimal (BCD) number system

Unpacked BCD – the lower 4 bits of the number


represent the BCD number and the rest of the
bits are 0. Eg:“0000 1001” for 9, “0000 0101” for
5

Packed BCD – a single byte has two BCD


numbers in it: one in the lower 4 bits and one in
upper 4 bits. Eg: “0101 1001” is packed BCD for
59H. Only 1byte of memory is needed to store.
Thus, it is efficient in storing data.
Data Conversion Program in C: ASCII
American Standard Code for Information Interchange (ASCII) codes

The basic set of 7- bit characters includes the upper and lower case
letters and the numerals and punctuation marks found on the
standard computer keyboard

Many newer microcontroller have real-time clock (RTC) where the


time and date are kept even when the power is off. Very often the
RTC provides in packed BCD. To display them, it must convert them
to ASCII.
Data Conversion Program in C

For example, capital


(upper case) A is
1000001 (6510 )

The statement answer = ' Y '


; will assign the value 0x59
to the variable ‘ answer ’
Data Conversion Program in C

Packed BCD to ASCII Conversion

ASCII to Packed BCD Conversion


PIC16: C Program Basics

• Variables
• Looping
• Decisions

• The purpose of an embedded program is


(i) read in data or control inputs,
(ii) process the data
(iii) operate the outputs as required
Variables
-must begin with a character or underscore

Definition: Any number changing its value during program operation

A variable name (identifier) is a label attached to the memory location where the variable value is
stored.

In C, the variable label is automatically assigned to the next available location

The variable name and type must be declared at the start of the program block

Only alphanumeric characters (a–z, A–Z, 0–9) and underscore, instead of space, can be used.

Declarations appear before executable statements.


Variables

x is variable
data type

int x;
x= 99;
PORTD = x;

Note: i. the case of alphabetic characters is significant. Using “INDEX”, “index” & “InDex”
….all three refer to different variables-case sensitive
ii. Header files contain definitions of function & variables
iii. Keywords are reserved identifiers – if, else, int, char, while, …
iv. Contents of a variable can change
v. Global and local variable
Program Looping
• to execute continuously until the processor is turned off or reset
• the program generally jumps back at the end to repeat the main control
loop
• implemented as a “ while ” loop

while loop

int x;
while(1)
{
PORTD = x;
x++; x++; is equivalent to x=x+1;
} x--; is equivalent to x=x-1;

note: conditional loop-iterations are halted when condition is true


unconditional loop-repeated a set number of times
Decision Making
• To illustrate basic decision making is to change an output depending on
the state of an input

int x;
PORTD=0x00;
while(1)
{
x=RC0;
if(x==1) RD0=1;
}
If statement for the decision making

The value is then tested in the if


statement and the output set
Note:
if - execute statement or not
accordingly.
if-else - choose to execute one or two statements
switch - choose to execute one of a number of statements
• What is sequence control?
- Sequence control refers to user actions and
computer logic that initiate, interrupt, or
terminate transactions. Sequence control
PIC16: C governs the transition from one transaction to
Sequence the next.
• While loops
Control • For loop
• Break, continue, goto
• If, else, switch
While Loops

• while(condition)
provides a logical test at the start of a loop, and the statement
block is executed only if the condition is true
• do
program statement;
while(condition);
the loop block be executed at least once, particularly if the test
condition is affected within the loop
While Loops

1. Condition is evaluated no 1. The body of the loop


(“entry condition”) is executed
2. If it is FALSE, 2. Condition is evaluated
skip over the loop yes (“exit condition”)
3. If it is TRUE, 3. If it is TRUE,
loop body is executed
yes go back to step 1.
4. Go back to step 1 If it is FALSE,
exit loop.
no

The WHILE test occurs before the block and the DO


WHILE after the block

40
While Loops
The WHILE test occurs before the block and the DO WHILE after
void main( )
{
int count;
count = 0;
while (count < 6)
{
printf("The value of count is %d\n",count);
count = count + 1;
}
}
void main( )
{
no
int i;
yes i = 0;
do {
yes
printf("the value of i is now %d\n",i);
no i = i + 1;
} while (i < 5);
}
For loop
• Useful for counter-controlled loop
• for(initialization;test
condition;update)
• Initialize at the start of a loop,
perform a logical test, execute
the statement block if the
condition is true and then update
expression.
• Process repeated until logical test
produced false result

void main( )
{
int count;
for (count=0;count < 6;count++)
{
printf(“count = %d\n",count);
}
}
42
Break,
Continue and
Goto
 To break the execution of
a loop or block in the
middle of its sequence
 The block must be exited
in an orderly way, and it
is useful to have the
option of restarting the
block (continue) or
proceeding to the next
one (break).
 It is achieved by assigning
a label to the jump
destination and executing
a goto..label

42
If…else

• if - allows a block to be no yes no


executed or skipped
conditionally. yes
• else - allows an alternate
sequence to be executed,
when the if block is
skipped
Switch…Case
yes

no
• multichoice selection - yes
which is provided by the
switch..case syntax no
yes
• switch..case : tests a
variable value and no
provides a set of
yes
alternative sequences,
one of which is selected no
depending on the test
result

44
If..else vs Switch..Case
If..Else
if (expression) If the expression is TRUE,
statement1; statement1 is executed; statement2 is skipped
else If the expression is FALSE,
statement2; statement2 is executed; statement1 is skipped

Switch..Case
switch (integer expression) The keyword break should be included
case constant1: at the end of each case statement. In
statement1; the switch statement, it causes an exit
break; from switch shunt.
case constant2:
statement2;
break;
EXAMPLE
Writing header, configuring I/O pins, using delay function and switch operator

46
PIC16: Array
and Pointer
Array
Hold multiple values of the same data type

 List of variables that are all of the same type and can be referenced
through the same name
 The individual variable in the array is called an array element
 Used to handle groups of related data
 Declaration for one-dimensional array
type var_name [size]
 type – valid C data type (char, int, long)
 var-name – the array name
 size – specifies how many elements are in the array
 Example: int height[50];
 The first element to be at an index of 0 (height[0])
 The last element to be at an index size-1(height[49])
Array
• Can also being declare as multidimensional array
• unsigned int height[4][5] – 2 dimensional array 4x5 (4 rows, 5 columns)
memory
• Assigning initial value height[0] height[1] height[2]

• int height[3] = { 23,45,67};


height 23 45 67
• int height[] = {23,45,67};
• char str[3] = {‘a’,’b’,’c’};
• char name[6] = “Ernie”;  equal to char name[6] = {‘E’,’r’,’n’,’i’,’e’,’/0’};
• ‘/0’ is a null terminator indicates the end of string

48
Array

i. a = c[0]; // copy the value of the 1st element of c into a

ii. c[1] = 123; // assign the value 123 to the 2nd element of c

iii. i[2] =12345; // assign the value 12345 to the 3rd element of i

iv. k[2] = 123* i[4]; // compute 123 x the value of the 5th element of i
Pointer

 A memory location (variable) that holds the address of another


memory location
 Declaration
type *var-name;
 Type – valid C data types
 Var-name – name of the pointer
 * - indicates that the variable is a pointer variable
 Example
void main(void)
() means value of
{
int *a;
int height[4] = {1,2,3,4};
a = &height; // assigned a to the first address of array  (a) = height[0]
a++; // set the pointer a to next array address  (a) = height[1]
printf(“%d”,*a); // print the array value as pointed by pointer a  result is 2
}
 Suitable for accessing look-up table
50
Basic difference between a pointer and an array
Difference Between - an array is a collection of variables of similar
Array and Pointer data type whereas the pointer is a variable that
stores the address of another variable.

BASIS FOR
ARRAY POINTER
COMPARISON

Declaration //In C //In C


type var_name[size]; type * var_name;

Working Stores the value of the Store the address of the


variable of homogeneous another variable of same
data type. datatype as the pointer
variable's datatype.

Storage A normal array stores values Pointers are specially


of variable and pointer array designed to store the
stores the address of address of variables.
variables.
Capacity An array can store the A pointer variable can
number of elements, store the address of only
mentioned in the size of one variable at a time.
array variable.

You might also like