You are on page 1of 53

LECTURE 2:

INTRODUCTION TO C PROGRAMMING

LECTURE 2: PIC PROGRAMMING IN C


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 (instruction set 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
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
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 (int)
¨ the default type is an unsigned 8-bit number, giving a range
of values of 0 – 255
¨ Range of a number is determined by the number of different
binary codes that can be represented
Signed Integers
¨ uses the most significant bit (MSB) as the sign bit, so
the range is accordingly reduced by half
¨ MSB 0 represents a positive number, MSB 1
indicates a negative number
¨ Therefore, the range for a 16-bit signed integer is –
32767 to + 32767
¨ The sign bit must be processed separately to get
the right answer from a calculation

15
I/O PROGRAMMING IN C
ØWe use the PORTA-PORTD labels as defined in C program header file

ØBit-addressable I/O Programming

ØTRISB indicate all bit in TRISB & TRISB7 indicates B7 of the TRISB
PORT also the same
PIC16 C Data Operations
n Variable types
n Floating point numbers
n Characters
n Assignment operators

¨ A main function of any computer program is to carry out calculations


and other forms of data processing
¨ Data structures are made up of different types of numerical and
character variables, and a range of 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

18
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;
19
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.

20
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.
Arithmetic & Logical Operations

22
Arithmetic & Logical Operations
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
Examples :
AND condition:
if((a > b)& & ( c = d ))

OR condition:
if((a > b)||(c = d ))
Q5

Examples

Assuming a = 10

( a > 1)

( -a >= 0)

( a == 17)

( a != 3)

26
Integer Constants
ØInteger constants can be decimal, hexadecimal, octal or binary.

ØThe compiler recognizes their format on the basis of the prefix added.
If the number has no prefix, it is considered decimal by default.

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


Logic Operation in C
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;
Data Conversion Program in C
¨ 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
¨ 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 ’

31
Data Conversion Program in C
Packed BCD to ASCII Conversion

ASCII to Packed BCD Conversion

32
PIC16 C Program Basics

nVariables
nLooping
nDecisions

¨ The purpose of an embedded program is


(i) read in data or control inputs,
(ii) process the data
(iii) operate the outputs as required

33
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
35
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


Note: statement and the output set accordingly.
if - execute statement or not
if-else - choose to execute one or two statements
switch - choose to execute one of a number of statements 37
PIC16 C Sequence Control

¨ What is sequence control?


- Sequence control refers to user actions and computer logic that
initiate, interrupt, or terminate transactions. Sequence control
governs the transition from one transaction to the next.

¨ While loops
¨ Break, continue, goto

¨ If, else, switch

38
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 1. The body of the loop


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

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
main( )
{
int count;
count = 0;
while (count < 6) {
printf("The value of count is %d\n",count);
count = count + 1;
}
}

main( )
{
int i;
i = 0;
do {
printf("the value of i is now %d\n",i);
i = i + 1;
} while (i < 5);
}
Break, Continue and Goto
¨ 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 executed or skipped


conditionally.
¨ else - allows an alternate sequence to be executed,
when the if block is skipped
Switch…Case
¨ multichoice selection - which
is provided by the
switch..case syntax
¨ switch..case : tests a variable
value and provides a set of
alternative sequences, one of
which is selected depending
on the test result

44
If..Else and 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
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];
n The first element to be at an index of 0 (height[0])
n 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)
¨ Assigning initial value height 23 45 67
¤ Int height[3] = { 23,45,67};
height[0] height[1] height[2]
¤ Int height[] = {23,45,67}; memory
¤ Char str[3] = {‘a’,’b’,’c’};

¤ Char name[6] = “Ernie”; è equal to char name[6] =


{‘E’,’r’,’n’,’i’,’e’,’/0’};
n ‘/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
Memory Addressing
ØPointers are powerful features of C and (C++) programming that differentiates it
from other popular programming languages like: Java and Python.
ØPointers are used in C program to access the memory and manipulate the address.
Memory Addressing

We can find out the memory address of a variable


by using the address operator &
52
Difference Between Array and Pointer

ØBasic difference between a pointer and an array - an array is a collection


of variables of similar data type whereas the pointer is a variable that stores
the address of another variable.

BASIS FOR COMPARISON ARRAY POINTER

Declaration //In C++ //In C++


type var_name[size]; type * var_name;

Working Stores the value of the variable of homogeneous Store the address of the another variable
data type. of same datatype as the pointer
variable's datatype.

Storage A normal array stores values of variable and Pointers are specially designed to store
pointer array stores the address of variables. the address of variables.

Capacity An array can store the number of elements, A pointer variable can store the address
mentioned in the size of array variable. of only one variable at a time.
END OF CHAPTER
¨ “Without requirements or design, programming is
the art of adding bugs to an empty text file.” -
Louis Srygley

You might also like