lecture 2: introduction to c programmingportal.unimap.edu.my/portal/page/portal30/lecture... ·...

53
LECTURE 2: INTRODUCTION TO C PROGRAMMING LECTURE 2: PIC PROGRAMMING IN C

Upload: others

Post on 30-Jan-2021

1 views

Category:

Documents


1 download

TRANSCRIPT

  • LECTURE 2:INTRODUCTION TO C PROGRAMMING

    LECTURE 2: PIC PROGRAMMING IN C

  • PROGRAMMING LANGUAGES

    § The lowest-level language is calledMachine languages. It meansthose languages which are closer to theunderstanding of machine rather thanhuman beings. A machine language thuscomprises a string of binary 0’s and 1’s.

    § Machine language is actually a codedset of instructions for a particular CPU,and it is also known as a machinecode.

    § A machine language is designed to beused by a computer without the need oftranslation.

    2

  • PROGRAMMING LANGUAGES

    The microcontroller executes the program loaded in itsFlash memory.

    All instructions that the microcontroller can recognize aretogether called the Instruction Set (instruction set has 35different instructions in total)

    Process of writing executable code was endlessly tiring, the first‘higher’ programming language called Assembly Language. Itmade the process of programming more complicated

    Instructions in assembly language are represented in the form ofmeaningful abbreviations, and the process of their compiling intoexecutable code is left over to compiler.

  • PROGRAMMING LANGUAGES

    However, programmers have always needed a programminglanguage close to the language being used in everyday life.As a result, the higher programming languages have beencreated. 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 ofcompiling the program from higher to lower programming language.

  • 6

  • ADVANTAGES OF HIGHERPROGRAMMING LANGUAGES

    Assembly Language(a x b = a + a + a + … + a)

    Higher Programming Languages, such as C

    Since there is no appropriate instruction formultiplying two numbers

  • Major Reasons for Writing Programin C instead of Assembly

    1. It is easier and less time consuming to write inC than Assembly

    4. C code is portable to other microcontroller withlittle or no modification

    3. You can use code available in function libraries

    2. C is easier to modify and update

    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.

    i. Activate and set built-in ADCii. Measure analogue valueiii. Calculate temperatureiv. Send data in the proper form to LCD

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

    Process of measuring is performed bysensor that converts temperature intovoltage. MCU uses its ADC to convert thisvoltage to a number which is then sent tothe LCD.

  • Structure of a Simple Program

    10

  • Program Structure

    Structure of everyembedded-controlprogram written in C.There will always betwo 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 applicationbehavior, and is executed continuously

    #include #pragma config FOSC = HS#pragma config WDTE = OFF#pragma config PWRTE = ON#pragma config BOREN = OFF#pragma config LVP = OFF#define _XTAL_FREQ 20000000

  • ÿGood understanding of C data types can help programmersto create smaller hex files.

    ÿ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 char – 8 bit (MSB D7 of D7—D0 used to represent the – or + value.Range values from -128 to +127.)

    ÿ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.

    Data Types

  • signed/unsigned int/char

  • Integer (int)

    ® the default type is an unsigned 8-bit number, giving a rangeof values of 0 – 255

    ® Range of a number is determined by the number of differentbinary codes that can be represented

  • Signed Integers

    ® uses the most significant bit (MSB) as the sign bit, sothe range is accordingly reduced by half

    ® MSB 0 represents a positive number, MSB 1indicates a negative number

    ® Therefore, the range for a 16-bit signed integer is –32767 to + 32767

    ® The sign bit must be processed separately to getthe 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 TRISBPORT also the same

  • PIC16 C Data Operations

    nVariable typesnFloating point numbersnCharactersnAssignment operators

    ® A main function of any computer program is to carry out calculationsand other forms of data processing

    ® Data structures are made up of different types of numerical andcharacter variables, and a range of arithmetical and logicaloperations are needed

    ® Microcontroller programs do not generally need to process largevolumes of data, but processing speed is often important

  • Variable Types

    ® Any number changing its value during program operation iscalled 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 areneeded where single or paired operands areprocessed

    ® The result is assigned to one of the operandvariables or a third variable

    ® Assignment operator is the equal sign “=” and isused 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 thecommon ‘=’ character. For example: a = 8Compound assignments are specific to C language andconsist of two characters as shown in the table. Anexpression can be written in a different way as well, butthis one provides more efficient machine code.

    20

  • BITWISE OPERATORS in C

    Unlike logic operations being performed to variables, thebitwise operations are performed to single bits withinoperands.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, orfor statement, relational operators are used

    ® One variable is compared with a set value oranother variable, and the block is executed if thecondition is true

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

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

  • Examples

    Assuming a = 10

    ( a > 1)

    ( -a >= 0)

    ( a == 17)

    ( a != 3)

    Q5

    26

  • Integer Constants

    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

    ÿ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.

  • 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 bitsare 0. Eg:“0000 1001” for 9, “0000 0101” for 5

    ® Packed BCD – a single byte has two BCD numbersin it: one in the lower 4 bits and one in upper 4 bits.Eg: “0101 1001” is packed BCD for 59H. Only1byte of memory is needed to store. Thus, it isefficient in storing data.

  • Data Conversion Program in C

    ® American Standard Code for InformationInterchange (ASCII) codes

    ® The basic set of 7- bit characters includes the upperand lower case letters and the numerals andpunctuation marks found on the standard computerkeyboard

    ® Many newer microcontroller have real-time clock(RTC) where the time and date are kept even whenthe power is off. Very often the RTC provides inpacked BCD. To display them, it must convert themto ASCII.

  • Data Conversion Program in C

    The statement answer = ' Y ' ;will assign the value 0x59 to

    the variable ‘ answer ’

    For example, capital(upper case) A is1000001 (6510 )

    31

  • Data Conversion Program in C

    32

    Packed BCD to ASCII Conversion

    ASCII to Packed BCD Conversion

  • PIC16 C Program Basics

    nVariablesnLoopingnDecisions

    ® 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

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

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

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

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

    ® Declarations appear before executable statements.

    -must begin with a character or underscore

    Definition: Any number changing its value during program operation

  • Variables

    Note: i. the case of alphabetic characters is significant. Using “INDEX”, “index” & “InDex”….all three refer to different variables-case sensitiveii. Header files contain definitions of function & variablesiii. Keywords are reserved identifiers – if, else, int, char, while, …iv. Contents of a variable can changev. Global and local variable

    x is variable

    int x;x= 99;PORTD = x;

    data type

    35

  • Looping

    ® to execute continuously until the processor is turnedoff or reset

    ® the program generally jumps back at the end torepeat the main control loop

    ® implemented as a “ while ” loop

    int x;while(1){

    PORTD = x;x++;

    }

    while loop

    x++; is equivalent to x=x+1;x--; is equivalent to x=x-1;

    note: conditional loop-iterations are halted when condition is trueunconditional loop-repeated a set number of times

  • Decision Making

    ® To illustrate basic decision making is to change anoutput 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 ifstatement and the output set accordingly.Note:

    if - execute statement or notif-else - choose to execute one or two statementsswitch - 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 controlgoverns 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 thestart of a loop, and the statement block is executedonly if the condition is true

    ® doprogram statement;

    while(condition); : the loop block be executed atleast once, particularly if the test condition isaffected within the loop

  • While Loops

    The WHILE test occurs before the block and the DOWHILE after the block

    1. Condition is evaluated(“entry condition”)

    2. If it is FALSE,skip over the loop

    3. If it is TRUE,loop body is executed

    4. Go back to step 1

    1. The body of the loopis executed

    2. Condition is evaluated(“exit condition”)

    3. If it is TRUE,go back to step 1.If it is FALSE,exit loop.

    40

  • While LoopsThe 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 orblock in the middle of its sequence

    ® The block must be exited in anorderly way, and it is useful to havethe option of restarting the block(continue) or proceeding to the nextone (break).

    ® It is achieved by assigning a labelto the jump destination andexecuting a goto..label

    42

  • If…Else

    ® if - allows a block to be executed or skippedconditionally.

    ® else - allows an alternate sequence to be executed,when the if block is skipped

  • Switch…Case

    ® multichoice selection - whichis provided by theswitch..case syntax

    ® switch..case : tests a variablevalue and provides a set ofalternative sequences, one ofwhich is selected dependingon the test result

    44

  • If..Else and Switch..Case

    If..Else

    Switch..Case

    if (expression)statement1;

    elsestatement2;

    If the expression is TRUE,statement1 is executed; statement2 is skippedIf the expression is FALSE,statement2 is executed; statement1 is skipped

    switch (integer expression)case constant1:

    statement1;break;

    case constant2:statement2;break;

    The keyword break should be includedat the end of each case statement. Inthe switch statement, it causes an exitfrom switch shunt.

  • Writing header, configuring I/O pins, using delay function and switch operator

    EXAMPLE

    46

  • Array

    ® List of variables that are all of the same type and canbe referenced through the same name

    ® The individual variable in the array is called an arrayelement

    ® 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])

    Hold multiple values of the same data type

  • Array

    ® Can also being declare as multidimensional array§ Unsigned int height[4][5] – 2 dimensional array 4x5 (4

    rows, 5 columns)

    ® Assigning initial value§ Int height[3] = { 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’};n ‘/0’ is a null terminator indicates the end of string

    4523 67height

    height[1]height[0] height[2]

    memory

    48

  • Array

    i. a = c[0];

    ii. c[1] = 123;

    iii. i[2] =12345;

    iv. k[2] = 123* i[4];

    // copy the value of the 1st element of c into a

    // assign the value 123 to the 2nd element of c

    // assign the value 12345 to the 3rd element of i

    // compute 123 x the value of the 5th element of i

  • Pointer

    ÿ A memory location (variable) that holds the address ofanother memory location

    ÿ Declarationtype *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){

    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

    () means value of

    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 variableby using the address operator &

    52

  • Difference Between Array and Pointer

    BASIS FOR COMPARISON ARRAY POINTER

    Declaration //In C++type var_name[size];

    //In C++type * var_name;

    Working Stores the value of the variable of homogeneousdata type.

    Store the address of the another variableof same datatype as the pointervariable's datatype.

    Storage A normal array stores values of variable andpointer array stores the address of variables.

    Pointers are specially designed to storethe address of variables.

    Capacity An array can store the number of elements,mentioned in the size of array variable.

    A pointer variable can store the addressof only one variable at a time.

    ÿBasic difference between a pointer and an array - an array is a collectionof variables of similar data type whereas the pointer is a variable that storesthe address of another variable.

  • END OF CHAPTER

    ® “Without requirements or design, programming isthe art of adding bugs to an empty text file.” -Louis Srygley