Top Banner
Microcontroller Theory and Applications with the PIC18F M. RAFIQUZZAMAN, Ph.D. PROFESSOR ELECTRICAL AND COMPUTER ENGINEERING California State Polytechnic University Pomona, California USA
119
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • Microcontroller Theory and

    Applications with the PIC18F

    M. RAFIQUZZAMAN, Ph.D.PROFESSOR

    ELECTRICAL AND COMPUTER ENGINEERING

    California State Polytechnic University Pomona, California USA

  • MICROCONTROLLER THEORY AND APPLICATIONS

    WITH THE PIC18F

  • 88....................................................................Chapter 10

    59....................................................................Chapter 9

    47....................................................................

    Chapter 8

    30....................................................................Chapter 7

    20....................................................................Chapter 6

    17....................................................................Chapter 5

    10....................................................................Chapter 4

    6....................................................................Chapter 3

    1....................................................................Chapter 2Page

    TABLE OF CONTENTS

  • CHAPTER 2

    2.1

    Single- chip Microcomputer : CPU, memory, and I/O in a single chip.Microcontrollers evolved from single-chip microcomputers. The

    microcontrollers are typically used for dedicated applications such as automotivesystems, home appliances, and home entertainment systems. Typicalmicrocontrollers, therefore, include on-chip timers and A/D (analog to digital) andD/A (digital to analog) converters.

    2.2

    The ALU is 8-bit. PIC18F4321.

    2.3

    (a) The PC stores address of the instruction. The MAR stores address of data.(b) The result is stored in the accumulator after most ALU operations. The Instruction register stores instructions.(c) Depending on the register section, the microcontroller can be classified eitheras an accumulator-based or a general-purpose register-based machine. In anaccumulator-based microcontroller such as the PIC18F, the data is assumed to beheld in a register called the accumulator. All arithmetic and logic operations areperformed using this register as one of the data sources. The result after theoperation is stored in the accumulator.

    In general-purpose register-based microcontroller such as the TexasInstruments MSP430, the microcontroller contains several general-purposeregisters. These registers can hold data, memory addresses, or the results ofarithmetic or logic operations.

    2.4

    (a) 0011 111 0916 = 0000 1001 flags+1716 = 0001 0111 sign = 0 overflow = 0 2016 = (0) 0010 0000 carry = 0 zero = 0

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 1

  • (b) 1111 111 A516 = 1010 0101 flags-A516 = 0101 1011 sign = 0, zero = 1 0016 = (1) 0000 0000 carry = 1s complement of 1 =0,

    overflow = 0

    (c) 1110 111 7116 = 0111 0001 flags-A916 = 0101 0111 sign = 1, zero = 0 C816 = (0) 1100 1000 carry = 1s complement of 0 = 1,

    overflow = 0

    (d) 1111 110 flags 6E16 = 0110 1110 sign = 1, carry = 0 + 3A16 = 0011 1010 zero = 0, overflow = 1, Wrong result A916 ?(0) 1010 1000

    (e) 1111 110 7E16 = 0111 1110 flags+7E16 = 0111 1110 sign = 1, carry = 0 FC16 ? (0) 1111 1100 zero = 0, overflow = 1, Wrong result

    2.5

    The PUSH OPERATION: is writing to the top or bottom of the stack.The POP OPERATION: is reading from the top or bottom of the stack. 2.6

    (a) SP = 20BE(b) (20BE) = 05, (20BF) = 02, assuming low byte is stored in low address, andhigh byte is stored in high address.

    2.7

    To load the program counter with the address of the first instruction to be executed.

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 2

  • 2.8

    22 bits.

    0x3FFFFF

    2.9

    2kB

    2.10

    In von Neumann architecture, a single memory system with the same address anddata buses is used for accessing both programs and data. This means that programsand data cannot be accessed simultaneously. This may slow down the overallspeed. Texas Instruments MSP 430 uses von Neumann architecture.

    Harvard architecture is a type of computer architecture which uses separateProgram and data memory units along with separate buses for instructions anddata. This means that these processors can execute instructions and access data simultaneously. Microchip PIC18F uses Harvard architecture.

    2.11

    In order to execute a program, conventional CPUs repeat the following threesteps for completing each instruction:

    Step 1: Fetch : The CPU fetches (Instruction Read) the instruction from themain memory (external to the CPU) into the Instruction Register.

    Step 2: Decode: The CPU decodes or translates the instruction using theControl Unit. The Control Unit inputs the contents of the Instruction Register, andthen decodes (translates) the instruction to determine the instruction type.

    Step 3: Execute: The CPU executes the instruction using the Control Unit. Inorder to accomplish the task, the Control Unit generates a number of enable signalsrequired by the instruction.

    The PIC18F CPU uses pipelining in which instruction fetch and executecycles are overlapped in order to speed up instruction execution.2.12CISC CPUs contain a large number of instructions and many addressing modeswhile RISC CPUs include a simple instruction set with a few addressing modes.Almost all computations can be obtained from a few simple operations. RISC

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 3

  • basically supports a small set of commonly used instructions which are executed ata fast clock rate compared to CISC which contains a large instruction set (some ofwhich are rarely used) executed at a slower clock rate. In order to implement fetch/execute cycle for supporting a large instruction set for CISC, the clock is typicallyslower.

    In CISC, most instructions can access memory while RISC contains mostlyload/store instructions. The complex instruction set of CISC requires a complexcontrol unit, thus requiring microprogrammed implementation. RISC utilizeshardwired control which is faster. CISC is more difficult to pipeline while RISCprovides more efficient pipelining. An advantage of CISC over RISC is thatcomplex programs require fewer instructions in CISC with a fewer fetch cycleswhile the RISC requires a large number of instructions to accomplish the same taskwith several fetch cycles. However, RISC can significantly improve itsperformance with a faster clock, more efficient pipelining and compileroptimization.

    2.13

    The PIC18F can convert an analog signal into a 10-bit value using its on-chip A/D(Analog to Digital) converter.

    The PIC18F can perform functions such as capture, compare, and pulsewidth modulation (PWM) using the timers and CCP (Capture / Compare / PWM)modules. The PIC18F can compute the period of an incoming signal using thecapture module. The PIC18F can produce a periodic waveform or time delaysusing the compare module. The PIC18Fs on-chip PWM can be used to obtainpulse waveforms with a particular period and duty cycle which are ideal forapplications such as motor control.

    Serial I/O is typically fabricated as an on-chip module with the PIC18F.This will facilitate interfacing the PIC18F with peripheral devices utilizing serialdata transmission synchronized with the clock.2.14Pipelining is a technique that overlaps instruction fetch (instruction read) withexecution. This allows a microcontrollers processing operation to be brokendown into several steps (dictated by the number of pipeline levels or stages) so thatthe individual step outputs can be handled by the microcontroller in parallel.Pipelining is often used to fetch the microcontrollers next instruction whileexecuting the current instruction, which considerably speeds up the overalloperation of the microcontroller.

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 4

  • 2.15

    The PIC18F implements a two-stage pipeline. The PIC18F CPU fetches theinstruction during the first stage. However, during the second stage, the PIC18FCPU while executing the instruction, fetches the next instruction. This is calledtwo-stage instruction pipelining, and is used by the PIC18F to increase the speedof instruction execution. When the PIC18F fetches a branch instruction, it clearsor flushes the pipeline and executes a new sequence of instructions starting at thenew branch address.

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 5

  • CHAPTER 3

    3.1

    Microcontrollers can be programmed using semi-English-language statements(assembly language). In addition to assembly language, microcontrollers use amore understandable human-oriented language called the high-level language.

    High-level language such as C is portable while Assembly language is not.Compilers normally provide inefficient machine codes because of the generalguidelines that must be followed for designing them. C is a high-level languagethat includes Input/Output instructions. However, the compiled codes generatemany more lines of machine code than an equivalent assembly language program.Therefore, the assembled program will take up less memory space and will executemuch faster compared to the compiled C .

    Although C/C++ language includes I/O instructions, applications involvingI/O are normally written in assembly language. One of the main uses of assemblylanguage is in writing programs for real-time applications. Real-time means thatthe task required by the application must be completed before any other input tothe program can occur which will change its operation. Typical programs involvingnon-real-time applications and extensive mathematical computations may bewritten in C .

    3.2

    Yes

    3.3

    No

    3.4

    (a) The 8-bit contents of address 0x23 are 00H.(b) The 8-bit contents of address 0x23 are 12H.

    3.5

    (a) Cross assembler is a program resident in a processor and assembles programswritten in assembly language of another processor. Resident assembler is a program that assembles programs written in assemblylanguage for the same processor.(b) Two-Pass assembler is a program that goes through the program twice. In thefirst pass, it assigns addresses to labels. In the second pass, it assembles the

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 6

  • program and thus takes care of forward branching. Meta-assembler assemblesprograms for several microcontrollers.

    3.6

    z = a +(b c) + (d e) - (f / g) - (h i);

    (a) Three Address

    r1-r0z;zr0,r1,subihr1;r1i,h,mulr1-r0r0;r0r0,r1,sub

    f/gr1;R1f,g,divr1+r0 r0;r0r0,r1,addedr1;r1,e,d,mulr0+ar0;r0r0,a,addcbr0;r0c,b,mul

    (b) Two Address

    r0z;zr0,movr1-r0r0;r0r1,subir1r1;r1i,mul

    hr1;r1h,movr1-r0r0;r0r1,sub

    r1/gr1;r1g,divfr1;r1f,mov

    r1+r0r0;r0r1,addr1er1;r1e,mul

    dr1;r1d,movr0+ar0;r0a,addcr0r0;r0c,mul

    br0;r0b,mov

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 7

  • 3.7

    We know that :

    a / a = 0 and a / 0 = a

    (a / b)/ a = a / b / a = a / a / b

    = (a / a)/ b

    = 0/ b = b

    The following sequence uses the above result in order to achieve the desired result:

    R2/R1R2;R2R1,XORR2/R1R1;R1R2,XORR2/R1R2;R2R1,XOR

    3.8

    M = 1111 11112, Q = 1111 11002Since M and Q are both negative numbers. 2s complement of M = 0000 000122s complement of Q = 0000 01002Multiplying the 2s complement of M and Q using unsigned multiplication

    method,product = 0000 0000 0000 01002 = + 410.The sign of the product,

    S = M Q = 1 1 = 0n n / n /

    Hence, the result is + 410

    3.9

    Quotient = -8, Remainder = -1. The sign of the remainder is the same as the sign ofthe dividend unless remainder is zero.3.10

    Logically AND with 8-bit hex data ED16

    3.11Logically OR with 8-bit hex data 81 .16

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 8

  • 3.12

    After arithmetically shifting B6 three times to left, the result will be B0 . Since16 16the most significant bit changes from 1 to 0 during shifting, the overflow bit is setto one.

    3.13 (a) To load constants into CPU registers.

    (b) To access data items stored in the memory.(c) To access data stored in memory location addressed by the contents of a

    register.(d) To design short branch or subroutine call instructions; to develop

    position independent program.(e) No operand instructions such as NOP.

    3.14

    Subroutines allow one to write one program for a specific function whose resultsare required many times in the main program.

    3.15

    When a subroutine call is made, the system usually stores the return address in thestack. This process is a natural solution for implementing subroutine calls so thatprogram execution starts at the right address in the main program after execution ofthe RETURN instruction placed at the end of the subroutine.

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 9

  • CHAPTER 4

    4.1The CPU can directly execute programs in main or primary memory. The size ofthe main memory is defined by the number of address pins on the CPU.

    Programs in the secondary or auxiliary memory can not directly be executedby the CPU. Operating system is required to load the programs from thesecondary to primary memory for execution. Hard disk is an example of secondarymemory.

    4.2

    2 = 16 Megabytes.24

    4.3(a) EPROMs (Erasable PROMs) can be reprogrammed and erased. The chip mustbe removed from the board for programming. This memory is erased by exposingthe chip via a lid or window on the chip to ultraviolet light. Typical erase timesvary between 10 and 20 min. The EPROM can be programmed by inserting thechip into a socket of the EPROM programmer and providing proper addresses andvoltage pulses at the appropriate pins of the chip.

    EEROMs (Electrically Erasable PROMs) can be programmed withoutremoving the memory from the ROMs sockets. These memories are also calledread mostly memories (RMMs), because they have much slower write times thanread times. Therefore, these memories are usually suited for operations whenmostly reading rather that writing will be performed.(b) Both SRAM and DRAM are read/write volatile memories. SRAM (StaticRAM) stores data in flip-flops. Therefore, this memory does not need to berefreshed.

    DRAM (Dynamic RAM) stores data in capacitors. That is, it can hold datafor a few milliseconds. Hence, DRAMs are refreshed typically by using externalrefresh circuitry. Dynamic RAMs (DRAMs) are used in applications requiringlarge memory. DRAMs have higher densities than SRAMs.

    4.4

    Flash memory is designed using a combination of EPROM and EEPROMs, and isnonvolatile.

    4.5

    (a) 214 = 16,384

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 10

  • (b) 1K x 1 bit = 1024 bits Total number of chips = = 128 chips16,384x 81024

    (c) Eight 1k x 1 chips will provide storage of 1k x8. Hence, four bits can be usedfor chip selects with a 4 x 16 decoder. Each decoder output will select a group ofeight 1k x 1 chips.

    4.6

    4.7

    (a) 20 (b) 6 x 64 decoder

    4.8

    14 unused address pins Available; maximum Directly Addressable Memory = 16Megabytes.

    4.9Two memory decoding techniques are typically used. These are: Linear decoding, and full decoding .Linear decoding is obtained by using unused address pins of the microprocessor asmemory chip selects. This method is suitable for small memory design. Memoryfoldback due to unused dont care conditions for address pins occur in memorydecoding. This results into address duplication and thus wastage of memory. Busconflict may occur if the designer is not careful.

    Full decoding uses a decoder to decode unused address pins of themicroprocessor for enabling memory chips. This method can be used for largememory design. Full decoding avoids bus conflict.

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 11

    2 = K4 8

    0 711 12

    13

    13

    A A O O2732

    4K x 8 A A O O

    2 = K

    27648K x 80 7

    12

    12

    0 0

    OE

    CE

    OE

    CE

  • 4.10

    AAAAR/W

    WE CS

    512x8

    CS

    Memory chip#1 Memory chip#2

    1211109

    1 2

    D D0 7 D D0

    A A0 8A A0 8

    WE CS

    512x8

    CS

    Memory chip#1

    1 2

    D D0 7

    A A8

    WE CS

    512x8

    CS1 2

    D D0 7

    A A0 8A

    15-A 13(Unused)

    9

    8

    CPU

    64K means that the microprocessor has 16 address pins.A15-A13 are dont cares. Assume 1s. Memory chip #1: A15 A14 A13 A12 A11 A10 A9 A8......A0

    1 1 1 0 1 1 0 all 0s to 1s EC00H - EDFFH

    Memory chip #2: A15 A14 A13 A12 A11 A10 A9A8......A0 1 1 1 1 0 0 1 all 0s to 1s

    F200H - F3FFH

    4.11

    (a) ROM map:A15 A14 A13 A12 A11 A10................A0 all 0s to 1s0000H - 07FFHRAM map:

    A15 A14 A13 A12 A11 A10 A9 A8 (A10 A9 A8 are dont cares; assume 0s)A7................A00 0 1 0 0 0 0 0 all 0s to 1s

    2000H - 20FFH

    (b) No bus conflict occurs since the selected decoder output ensures enabling ofone memory chip at a time. The unused outputs of the decoder can be used formemory expansion.

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 12

  • 4.12

    74138

    1K x 8EPROM

    1K x 8RAM 0

    1K x 8RAM 1

    D D0 7

    A A0 9

    AAAAAA

    14131215

    1110

    R/W

    4 1 0

    CBAG 1GG

    2A

    2B

    CEA

    0- A

    9

    OE

    CEA

    0- A

    9

    WE

    CEA

    0-A

    9

    WE

    8

    8

    8CPU

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 13

  • 4.13

    74138

    1K x 8

    1K x 8RAM 0

    1K x 8RAM 1

    CPU

    D D0 7

    A A0 9

    EPROM

    7 6 3

    R/W

    CBAGGG

    1

    2A

    2B

    A15A14A 13A12A

    11A 10

    CE

    OE

    A0- A

    9

    CEA0

    - A 9

    OE

    CE

    A0 - A 9

    OE

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 14

  • 4.14

    Foldback means duplication of addresses in linear decoding.

    4.15

    There are two ways of transferring data between the microcontroller and I/Odevices:

    Programmed I/OInterrupt I/O

    Using programmed I/O, the CPU executes a program to perform all datatransfers between the microcontroller and the external device. The maincharacteristic of this type of I/O technique is that the external device carries outthe functions as dictated by the program inside the microcontroller memory. Inother words, the CPU completely controls all transfers. Programmed I/O is CPU -initiated I/O transfer.

    In interrupt I/O, an external device can force the CPU to stop executing thecurrent program temporarily so that it can execute another program known as theinterrupt service routine. This routine satisfies the needs of the external device.After having completed this program, a return from interrupt instruction can beexecuted at the end of the service routine to return control at the right place in the main program. Interrupt I/O is device - initiated I/O transfer.

    4.16

    Standard I/O: The microcontroller uses IN or OUT instruction to transfer datavia I/O Ports.

    Memory-mapped I/O: I/O ports are mapped as memory locations. Memoryoriented instructions are used for input and output.

    The PIC18F uses memory-mapped I/O.

    4.17

    Memory mapping means all physical addresses available in the main memorywhere programs can be written by a user for execution. Memory mapped I/O is atechnique of mapping an I/O port as a memory address.

    4.18

    Polled I/O and Interrupt I/O: Polled I/O is conditional I/O transfer. The CPUwastes time by waiting in loop and checking a condition before the I/O transfer. In

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 15

  • Interrupt I/O, data transfer occurs upon activation of the CPUs interrupt pin by anexternal device.

    4.19

    Subroutine is called by an instruction while interrupt is initiated by activating themicrocontrollers interrupt pin by an external device. The subroutine callinstructions with microcontrollers save only the contents of the program counteronto stack before executing the subroutine whereas the microcontrollers typicallysave program counter, status registers and some other registers before executingthe interrupt service routine.

    4.20

    Interrupt address vector is the starting address of the service routine.

    4.21

    Maskable interrupts can be enabled or disabled by microcontroller instructionswhile the nonmaskable interrupt can not be enabled or disabled by instructions.Nonmaskable interrupt has higher priority. Power failure interrupt is handled using nonmaskable interrupt.

    4.22

    Internal interrupts are typically caused due to occurrence of conditions such as timer interrupt or completion of A/D conversion. The external interrupts, on theother hand, are initiated by an external device via interrupt pins.

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 16

  • CHAPTER 5

    5.1

    The PC is 21-bit wide. Hence, the maximum size of the PIC18Fs addressableprogram memory is 2 MB ( ).221

    5.2 Flash memory5.3The PIC18F can have a data memory of up to 4096 bytes. 12 bits are used to address data memory. This means that the maximum size of the

    data memory is 2 = 4096 bytes.12

    5.4 SRAM5.5The PIC18F4321 contains a maximum of 8 K bytes of on-chip program memory.The PIC18F4321, on the other hand, contains a maximum of 512 bytes of data memory.Critical data can be stored in the PIC18F4321 EEPROM and can be protected fromreading or writing by other users. 5.640 MHz5.7

    The PIC18F CCP module can perform functions such as capture, compare, andpulse width modulation (PWM) using the timers and CCP (Capture / Compare /PWM) modules. The PIC18F can compute the period of an incoming signal usingthe capture module. The PIC18F can produce a periodic waveform or time delaysusing the compare module. The PIC18Fs on-chip PWM can be used to obtainpulse waveforms with a particular period and duty cycle which are ideal forapplications such as motor control.

    5.8The PIC18F uses a two-stage pipeline. This means that execution of the previousinstruction is overlapped with fetching of the current instruction. This speeds upthe program execution by the CPU.

    5.9 (a) PC contains addresses of instructions in program memory whereas the FSRs

    point indirectly to data memory.

    Instructors Manual Microcontrollerr Theory & Applications with the PIC18F 17

  • (b) WREG is the accumulator, and is typically used for performing ALUoperations. IR stores instructions.

    5.10 4002H

    5.11MOVLB 0x0F

    5.12Address of the PIC18F Status register is 0xFD8

    Address of the PIC18F STKPTR is 0xFFC5.13No.

    The PIC18F hardware stack is a group of 31 21-bit registers to hold memoryaddresses. The low five bits of the STKPTR are used to address the stack. The31 stack registers are neither part of program memory nor data memory.

    5.14

    N = 0, OV = 0, Z = 1, DC = 1, C = 0

    5.15

    Large areas of data memory require an efficient addressing scheme to make rapidaccess to any address possible. Ideally, this means that an entire address does notneed to be provided for each read or write operation. For PIC18F, this isaccomplished with a RAM banking scheme. This divides the memory space into 16contiguous banks of 256 bytes. Depending on the instruction, each location can beaddressed directly by its full 12-bit address, or an 8-bit low-order address and a 4-bit Bank Pointer.

    Most instructions in the PIC18F instruction set make use of the BankPointer, known as the Bank Select Register (BSR). The BSR holds the four MostSignificant bits of a locations address; the PIC18F instruction contains the 8 Least Significant bits. Only the four lowerbits of the BSR are implemented (BSR3:BSR0). The value of the BSR indicatesthe bank in data memory; the 8 bits in the instruction show the location in the bankand can be thought of as an offset from the banks lower boundary.

    In order to access a memory location from one bank to a memory location ina different bank, bank switching is required. However the need for bank switching, sometimes, creates a major problem for the programmer. Obviously, programswill not work if the programmer forgets about bank switching. To facilitate access

    Instructors Manual Microcontrollerr Theory & Applications with the PIC18F 18

  • for the most commonly used data memory locations, the data memory isconfigured with an Access Bank, which allows users to access a mapped blockof memory without bank switching.

    5.16

    Most instructions contain one or more operands. Some instructions have nooperands. The manner in which a microcontroller specifies location(s) ofoperand(s) and destination addresses is called the addressing mode.

    5.17 (a) Implied mode(b) Literal mode(c)Indirect with preincrement mode

    5.18The PIC18F assembly language instruction sequence is provided below:

    MOVLW D50 ; Move 50 decimal into WREGMOVWF 0x80 ; Initialize Counter 0x80 with 50 decimalLFSR 0,0x0010 ; Initialize pointer FSR0 with starting

    ;address 0x010REPEAT CLRF PREINC0 ; Clear a location to 0 and increment FSR0

    ;by 1DECF 0x80,F ; Decrement Counter by 1BNZ REPEAT ; Branch to REPEAT if Zero flag = 0, else

    ; go to the next instruction

    Instructors Manual Microcontrollerr Theory & Applications with the PIC18F 19

  • CHAPTER 6

    6.1 MOVF 0x30, W

    ADDWF 0x40, W

    MOVWF 0x50

    6.2

    Assume data are already loaded into 0x30, 0x40, 0x50, and 0x60. Also,assume that no carry is generated due to subsequent addition of two numbers.

    INCLUDE

    A EQU 0x30

    B EQU 0x40

    C EQU 0x50

    D EQU 0x60

    E EQU 0x70

    MOVF A, W

    ADDWF B, W

    ADDWF C, W

    MOVWF E

    MOVF D, W

    SUBWF E, F

    SLEEP

    END

    6.3 (a) [0x20] = FFH

    (b) [0x0060] = 0x2A

    6.4 (a) [0x0075] = 0xFE

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 20

  • [FSR2] = 0x0074

    6.5 0x0E00

    0x6E93

    0x0000

    0x0EAA

    0x6E81

    0x0003

    6.6 CLRF 0x20

    SETF 0x22

    6.7 To write an instruction sequence for P = P - Q;

    The PIC18F instruction sequence is provided below:

    MOVF Q, W ; Q Wd

    SUBWF P, F ; P - W Pd

    6.8

    The C code is equivalent to:

    if (P>Q)

    P = 10;

    else

    P+ = 5;

    The PIC18F assembly language instruction sequence is provided below:

    MOVF Q, W

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 21

  • CPFSGT P

    BRA EPART

    MOVLW D10

    MOVWF P

    BRA NEXT

    EPART MOVLW 5

    ADDWF P

    NEXT ----

    6.9

    [WREG] = 0x110

    6.10 (a) MOVLW 0 or ANDLW 0

    (b) CLRF 0x40

    ANDWF 0x40, W

    6.11

    BCF STATUS, C

    6.12

    Machine code : 11010 + 11-bit offset

    Target branch address = (PC+2) + 2 x offset

    200 = 202 + 2 x offset

    Hence, offset = -1 (decimal) = 111 1111 1111 (binary)

    Therefore, the machine code is : 1101 0111 1111 1111 = 0xD7FF

    6.13

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 22

  • Assume N1 and N2 are already loaded into registers 0x20 and 0x21 respectively.

    INCLUDE

    ORG 0x100

    SWAPF 0x21, F ; Swap nibbles of N2 in 0x21

    MOVF 0x20, W ; Move [0x20] into WREG

    ADDWF 0x21, W ; Add [WREG] with [0x21], ;store result in WREG

    MOVWF 0x30 ; Store result in 0x30

    SLEEP

    END

    6.14

    INCLUDE

    ORG 0x100

    MOVLW 0xF1 ; Load highest byte of the first 24-bit data

    MOVWF 0x20

    MOVLW 0x91

    MOVWF 0x21

    MOVLW 0xB5 ; Load lowest byte of the first 24-bit data

    MOVWF 0x22

    MOVLW 0x04 ; Load highest byte of the second 24-bit data

    MOVWF 0x50

    MOVLW 0xA2

    MOVWF 0x51

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 23

  • MOVLW 0x07 ; Load lowest byte of the second 24-bit data

    MOVWF 0x52

    LFSR 0, 0x22 ; Initialize pointer

    LFSR 1, 0x50 ; Initialize pointer

    MOVLW 3 ; Initialize Counter

    MOVWF 0x30

    BCF STATUS, C ; Clear Carry flag

    BACK MOVF POSTDEC0, W ; Load a byte of first data into WREG

    ADDWFC POSTINC1, F ; Add with a byte of second data, and ;store result

    DECF 0x30, F

    BNZ BACK

    SLEEP

    END

    6.15

    INCLUDE

    ORG 0x100 ; Starting address of program

    MOVLW 0x72 ; load low byte of first data

    MOVWF 0x50

    MOVLW 0x64 ; load high byte of first data

    MOVWF 0x40

    MOVLW 0x16 ; load low byte of second data

    MOVWF 0x25

    MOVLW 0x34 ; load high byte of second data

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 24

  • MOVWF 0x20

    MOVF 0x25, W ; Load low byte of second data into WREG

    SUBWF 0x50, F ; Subtract low bytes, store result in 0x50

    MOVF 0x20, W ; Load high byte of second data into WREG

    SUBWFB 0x40, F ; Subtract low bytes with borrow , store ;result in 0x40

    SLEEP

    END

    6.16

    Assume data are already loaded into data registers.INCLUDE ORG 0x100 ; Starting address of program

    COUNTER EQU 0x20MOVLW D10 ; Initialize COUNTER with 10MOVWF COUNTER ; Move [WREG] into COUNTERMOVLW 0 ; Clear 16-bit SUM to 0MOVWF 0x40MOVWF 0x41LFSR 0, 0x50 ; Initialize pointer for XiLFSR 1, 0x70 ; Initialize pointer for Yi

    BACK MOVF POSTINC0, W; Move Xis into WREGMULWF POSTINC1 ; Unsigned multiply by Yis

    ; Result in PRODH:PRODLMOVF PRODL, W ; SUM in 0x41:0x40ADDWF 0x40, FMOVF PRODH, WADDWFC 0x41, FDECF COUNTERBNZ BACKSLEEPEND

    6.17

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 25

  • INCLUDE

    ORG 0x50

    MOVLW 2 ; Load J

    MOVWF 0x32

    MOVLW 5 ; Load K

    MOVWF 0x33

    MOVLW 6

    MULWF 0x32 ; 6 x J in PRODH:PRODL

    RRNCF 0X33,F ; Compute K/2 in 0x33

    RRNCF 0X33,F ; Compute K/2 in 0x33

    RRNCF 0X33,F ; Compute K/4 in 0x33

    MOVFF 0x33, 0x51 ; K/8 in 0x51

    MOVLW 0 ; Zero extend (K/8) to 16 bits

    MOVWF 0x50

    MOVF PRODL, W

    ADDWF 0x51, F

    MOVF PRODH, W

    ADDWFC 0x50, F

    SLEEP

    END

    6.18

    INCLUDE

    ORG 0x50

    ANDLW 0x01 ; Check if [WREG] odd or even

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 26

  • BNZ ODD

    CLRF 0x40 ; Clear [0x40] to 0s

    BRA FINISH

    ODD SETF 0x40 ; Set [0x40] to all 1s

    FINISH BRA FINISH

    END

    6.19

    INCLUDE

    ORG 0x70

    MOVWF 0x20 ; Save [WREG] in 0x20

    RLCF 0x20, F ; Check whether the number is ;positive or negative

    BNC POSITIVE ; If no carry, branch to positive

    IORLW 4 ; else negative, insert 1 at bit 2 of ;WREG

    BRA FINISH

    POSITIVE ANDLW 0xFB ; Clear bit 2 of WREG

    FINISH BRA FINISH

    END

    6.20

    Assume data is already loaded into 0x70.

    INCLUDE

    ORG 0x100

    COUNTER EQU 0x20

    PARITY EQU 0x21 ; Register 0x21to hold number of 1s

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 27

  • MOVLW 8

    MOVWF COUNTER ; Initialize COUNTER

    CLRF PARITY ; Clear register 0x21 to 0

    BACK RRCF 0x70, F ; Check a bit to carry

    BC DOWN ; If carry is 1, increment ;register 0x21

    BRA DOWN1 ; else, dont increment, but decrement ; COUNTER

    DOWN INCF PARITY, F

    DOWN1 DECF COUNTER, F

    BNZ BACK ; If Z = 1, 0x21 has number of 1s

    RRCF PARITY, F ; Check if # of 1s in 0x21 is odd or ;even

    BNC EVEN ; If no carry, even parity

    MOVLW 0xDD ; else, odd parity

    MOVWF 0x50 ; Store 0xDD in 0x50

    BRA FINISH

    EVEN MOVLW 0xEE ; Store 0xEE in 0x50

    MOVWF 0x50

    FINISH BRA FINISH

    END

    6.21

    Assume that the unsigned 16-bit number is 0x0124 (arbitrarily chosen). Since theremainder can be discarded, unsigned division can be accomplished by logicallyshifting the 16-bit unsigned number, 0x0124 once to the right.

    INCLUDE

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 28

  • ORG 0x100

    MOVLW 0x01 ; Load high byte into 0x20

    MOVWF 0x20

    MOVLW 0x24 ; Load low byte into 0x21

    MOVWF 0x21

    BCF STATUS, C ; Clear Carry flag to 0

    RRCF 0x20, F ; Right shift [0x20][0x21] once

    RRCF 0x21, F

    SLEEP

    END

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 29

  • CHAPTER 7

    7.1Assume data are already loaded into registers.

    INCLUDE ORG 0x150RRCF 0x50, F ; Check whether [0x50] is odd or evenBC ODD ; If Carry = 1, result odd, stopCLRF 0x40 ; else, store 0s in 0x40 and 0x41CLRF 0x41BRA FINISH ; Branch to Stop

    ODD MOVF 0x30, W ; Subtract low bytesSUBWF 0x20, WMOVWF 0x41 ; Store low byte subtraction result in 0x41MOVF 0x21, W ; Subtract high bytesSUBFWB 0x31, WMOVWF 0x40 ; Store high byte subtraction result in 0x40

    FINISH BRA FINISH ; StopEND

    7.2

    Assume data is already loaded into 0x30.INCLUDE

    ORG 0x200

    MOVFF 0x30, 0x40 ; Copy data in 0x40

    SWAPF 0x30, F ; Move data into low 4 bits

    MOVLW 0x0F ; Move mask data into WREG

    ANDLW 0x30, F ; One unsigned 8-bit data in 0x30

    ANDLW 0x40, W ; Another unsigned data in WREG

    MULWF 0x30 ; unsigned multiply data

    ; Since result will be 8-bit maximum,

    ; PRODL will contain result

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 30

  • MOVWF PRODL, 0x31 ; Result in 0x31

    SLEEP ; HALT

    END

    7.3

    Assume data are already loaded into data register 0x30. Perform signedmultiplication.

    INCLUDE ORG 0x100

    MULT1 EQU 0x30MULT2 EQU 0x40SIGN1 EQU 0X50SIGN2 EQU 0X51

    MOVFF MULT1, MULT2; Save data in 0x40MOVLW 8 ; Mask bit 3 (sign bit) of 1st dataANDWF MULT1, WBNZ SIGN ; If Z = 1, branch to sign extendMOVLW 0x0F ; else, zero extend 1st dataANDWF MULT1, F

    SIGN MOVLW 0xF0IORWF MULT1, FSWAPF MULT2, FMOVLW 0x0F ; zero extend 2nd dataANDWF MULT2, FMOVLW 5 ; Initialize STKPTR sinceMOVWF STKPTR ; since subroutine is usedCALL SMULT ; Call subroutine for signed

    ;multiplicationSLEEP ; Halt. 8-bit result in PRODLORG 0x200 ; Subroutine for signed multiplication

    SMULT CLRF SIGN1 ; Clear [SIGN1] to 0CLRF SIGN2 ; Clear [SIGN2] to 0

    ; STEPS 1 AND 2 OF THE ALGORITHM OF SECTION 7.7.1 BTFSS MULT1, 7 ; Check sign bit 7 for 1 for 1st # BRA NEG ; If sign = 0, branch to check sign of

    ; 2nd#INCF SIGN1 ; Increment [SIGN1] if sign of 1st# = 1NEGF MULT1 ; and take 2's complement of [MULT1]

    NEG BTFSS MULT2, 7 ; Check sign bit 7 for 1 for 2nd #

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 31

  • BRA POSMUL ;If both sign= 0, branch for unsigned ;mul

    INCF SIGN2 ; Increment [SIGN2] if sign of 2nd# ;= 1

    NEGF MULT2 ; and take 2's complement of ;[MULT2]

    ; STEP 3 OF THE ALGORITHM OF SECTION 7.7.1POSMUL MOVF MULT1, W ; Move [MULT1] to WREG

    MULWF MULT2 ; Unsigned product in ;PRODH:PRODL

    MOVF SIGN1, W ; Move [SIGN1] to WREG XORWF SIGN2 ; Compute sign of the resultBTFSS SIGN2, 0 ; If sign of result is 0, result inBRA FINISH ; PRODH:PRODL and StopCOMF PRODL ; For negative result, take comp of

    ;PROD; STEPS 4 AND 5 OF THE ALGORITHM OF SECTION 7.7.1

    COMF PRODH ; Take 2s complement of PRODLMOVLW 1ADDWF PRODLMOVLW 0ADDWFC PRODH, F ; Result in PRODH:PRODL in 2s

    ;compFINISH RETURN

    END

    7.4

    INCLUDE ORG 0x150

    DIVIDEND EQU 0x20DIVISOR EQU 0x40COUNTER EQU 0x21

    MOVLW 4 ; Initialize STKPTR since subroutine is usedMOVWF STKPTRMOVLW D50 ; Load 50 deg F to be converted to deg CMOVWF DIVIDENDMOVLW D32SUBLW DIVIDEND ; (F-32) in WREGMULLW 5 ; 8-bit result of (F-32) x 5 in PRODL. MOVFF PRODL, DIVIDEND ; Save in DIVIDEND

    MOVLW 9MOVWF DIVISOR

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 32

  • CALL UDIVFINISH BRA FINISH ; Halt. 8-bit result in 0x21

    ORG 0x100UDIV CLRF COUNTER ; Clear Counter to 0; STEPS 1 AND 2 OF THE ALGORITHM OF SECTION 7.7.2BACK CPFSEQ DIVIDEND ; If dividend equals divisor, skip next

    ;instr.BRA RESULT ; If not equal, branch to RESULTINCF COUNTER, F ; Increment [0x21] by 1SUBWF DIVIDEND, F ; Subtract divisor from dividend, result

    ;in 0x20BRA MAIN ; Go to Halt

    ; STEPS 3 , 4 AND 5 OF THE ALGORITHM OF SECTION 7.7.2RESULT CPFSGT DIVIDEND ; If dividend greater than divisor, skip

    ;next inst.BRA MAIN ; Quotient in 0x21, Remainder in 0x20

    ;is assumed ; to be 0 in this case, return

    INCF COUNTER, F ; Increment [0x21] by 1SUBWF DIVIDEND, F ; Subtract divisor from dividend,

    ;result in 0x20BRA BACK ; Repeat

    MAIN RETURN ; Return END

    7.5

    Assume data is already loaded into 0x40.

    INCLUDE

    ORG 0x100

    COUNTER EQU 0x50

    MOVF 0x40, W ; Move X into WREG

    MULWF 0x40 ; Compute (X ** 2). Result in ;PRODH:PRODL

    MOVLW 7 ; Initialize COUNTER

    MOVWF COUNTER

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 33

  • BACK BCF STATUS, C ; Clear Carry and compute ;(X**2)/128

    RRCF PRODH, F

    RRCF PRODL, F

    DECF COUNTER, F

    BNZ BACK

    MOVFF PRODL, 0x50 ; Store 8-bit result in 0x50

    FINISH BRA FINISH

    END

    7.6

    INCLUDE

    ORG 0x100

    LFSR 0, 0x0070

    MOVLW 0xFF ; Load X

    MOVWF 0x30

    MOVLW 2 ; Load Y

    MOVWF 0x60

    MOVLW 0x10

    MOVWF STKPTR

    CALL SUMSQ

    MOVFF 0x40, PREINC0 ; Push 8-bit result onto ;software stack

    HERE BRA HERE

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 34

  • ORG 0x200

    SUMSQ MOVF 0x60, W

    MULWF 0x60 ; 8-bit (Y**2) in PRODL

    MOVFF PRODL, 0x70 ; Save in 0x70

    CALL SMUT ; Compute 8-bit (X**2) in PRODLMOVF PRODL, W

    ADDWF 0x40, F ; (X**2 + Y**2) in 0x40

    RETURN

    ORG 0x150

    MULT1 EQU 0x30MULT2 EQU 0x30SIGN1 EQU 0X50SIGN2 EQU 0X51SMUT CLRF SIGN1 ; Clear [SIGN1] to 0

    CLRF SIGN2 ; Clear [SIGN2] to 0; STEPS 1 AND 2 OF THE ALGORITHM OF SECTION 7.7.1

    BTFSS MULT1, 7 ; Check sign bit 7 for 1 for 1st # BRA NEG ; If sign = 0, branch to check sign of

    ; 2nd#INCF SIGN1 ; Increment [SIGN1] if sign of 1st# = 1NEGF MULT1 ; and take 2's complement of [MULT1]

    NEG BTFSS MULT2, 7 ; Check sign bit 7 for 1 for 2nd #BRA POSMUL ;If both sign= 0, branch for unsigned

    ;mulINCF SIGN2 ; Increment [SIGN2] if sign of 2nd# = 1NEGF MULT2 ; and take 2's complement of [MULT2]

    ; STEP 3 OF THE ALGORITHM OF SECTION 7.7.1POSMUL MOVF MULT1, W ; Move [MULT1] to WREG

    MULWF MULT2 ; Unsigned product in PRODH:PRODLMOVF SIGN1, W ; Move [SIGN1] to WREG XORWF SIGN2 ; Compute sign of the resultBTFSS SIGN2, 0 ; If sign of result is 0, result inBRA FINISH ; PRODH:PRODL and StopCOMF PRODL ; For negative result, take comp of

    ;PRODL

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 35

  • ; STEPS 4 AND 5 OF THE ALGORITHM OF SECTION 7.7.1COMF PRODH ; Take 2s complement of PRODLMOVLW 1ADDWF PRODLMOVLW 0ADDWFC PRODH, F ; Result in PRODH:PRODL in 2s

    ;compFINISH RETURN

    END

    7.7

    Assume arrays x[i] and y[i] are already loaded into 0x20 and 0x30 respectively.Use MULWF for unsigned multiplication.

    INCLUDE

    ORG 0x100

    CLRF 0x50 ; Clear sum to 0

    LFSR 0, 0x0020 ; Load 0x0020 into FSR0

    LFSR 1, 0x0030 ; Load 0x0030 into FSR1

    MOVLW D10 ; Move 10 (decimal) into counter 0x75

    MOVWF 0x75

    LOOP MOVF POSTINC0, W; Move x[i] into WREG, increment ptrMULWF POSTINC1 ; unsigned multiply in x[i] * y[i]

    MOVF PRODL, W ; Move 8-bit product to WREG

    ADDWF 0x50, F ; sum in 0x50

    DECF 0x75, F ; Decrement counter by 1

    BNZ LOOP ; Repeat if Z = 0

    SLEEP

    END

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 36

  • 7.8

    INCLUDE

    ORG 0x150

    MOVLW 0xEE

    MOVWF 0x20

    CLRF 0x21

    MOVLW D10 ; Initialize counter

    MOVWF 0x22

    LFSR 0, 0x60 ; Initialize software SP

    LFSR 1, 0x30 ; Initialize pointer for string 1

    LFSR 2, 0x50 ; Initialize pointer for string 2

    BACK MOVF POSTINC1 ; Move a byte from string 1 to WREG

    CPFSEQ POSTINC2 ; Compare with string2 for equality

    BRA NOTEQUAL

    MOVFF 0x20, PREINC0 ; Push EE to software stack

    BRA DOWN

    NOTEQUAL MOVFF 0x21, PREINC0 ; Push 0 onto software stack

    DOWN DECF 0x22, F ; Decrement counter

    BNZ BACK

    FINISH BRA FINISH

    END

    7.9

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 37

  • INCLUDE

    ORG 0x100

    MOVLW 7

    MOVWF 0x40

    BACK BCF STATUS, C ; Clear Carry

    RRCF 0x30, F ; Shift [0x30][0x31] seven times

    RRCF 0x31, F ; to right to move 9-bit data

    DECF 0x40, F ; in low 9 bits of the registers

    BNZ BACK

    MOVLW 3

    MOVWF 0x40

    BACK1 BCF STATUS, C

    RRCF 0x30, F ; Shift [0x30][0x31] three times

    RRCF 0x31, F ; to right to divide by 8 by discarding remainder

    DECF 0x40, F

    BNZ BACK1

    SLEEP

    END

    7.10

    INCLUDE

    ORG 0x200

    MOVLW 4 ; Load shift count in 0x44

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 38

  • MOVWF 0x44 ; to divide by 16

    RRCF 0x31, W ; Check sign bit

    BNC POSITIVE ; If Carry = 0, the number is positive

    SETF 0x40 ; else, the number is negative, set [0x40] to 1s

    BRA FINISH

    POSITIVE RLCF 0x20, F ; Shift [0x21][0x20] four times to left

    RLCF 0x21, F ; to multiply by 8

    DECF 0x44, F

    BNZ POSITIVE

    FINISH BRA FINISH

    END

    7.11

    Assume data are already loaded into data memory from 0x10 through 0x2D. Also,note that a number P is divisible by 5 if its least significant digit is either 0 or 5.

    INCLUDE

    ORG 0x100

    MOVLW 0x2D ; Move last address to 0x60

    MOVWF 0x60

    CLRF 0x40 ; Clear counter 0x40 to 0

    LFSR 0, 0x10 ; Load starting address into FSR0

    BACK MOVLW 0x0F ; Load mask data into WREG

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 39

  • ANDWF INDF0, F ; Retain low 4 bits of data in data memory ;address

    MOVFF INDF0, 0x60; Save masked data in 0x60

    MOVLW 0x00 ; Load 0 into WREG

    SUBWF INDF0, F ; Subtract 0 from data

    BZ DOWN ; If Z = 1, divisible by 5, increment [0x40]

    MOVLW 0x05 ; Else, load 5 into WREG

    SUBWF 0x60, F ; Subtract 5 from data byte

    BZ DOWN ; If Z = 1, divisible by 5, increment [0x40]

    MOVLW 0x2D ; Load last address into WREG

    CPFSEQ 0x60 ; If [FSR0] = 0x2D, skip

    BRA DOWN1

    FINISH BRA FINISH

    DOWN INCF 0x40, F ; Increment [0x40] by 1

    DOWN1 INCF FSR0, F ; Increment [FSR0] by 1

    BRA BACK

    END

    7.12

    Assume data are already loaded into data registers.

    INCLUDE

    ORG 0x100

    MOVLW 4 ; Initialize counter

    MOVWF 0x50

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 40

  • LFSR 0, 0x23

    LFSR 1, 0x33

    BCF STATUS, C ; Clear Carry

    BACK MOVF INDF0, W ; Load a data byte into WREG for 1st #

    ADDWFC POSTDEC1, W ; Add with carry, result in WREG

    DAW ; Convert to valid BCD

    MOVWF POSTDEC0 ; Store in data memory

    DECF 0x50, F ; Decrement counter

    BNZ BACK ; Branch to BACK if Z not 0

    SLEEP

    END

    7.13

    ; Main program

    INCLUDE ORG 0x200

    COUNTER EQU 0x20MOVLW UPPER ADDR ; Move upper 5 bits (00H) of address MOVWF TBLPTRU ; to TBLPTRU MOVLW HIGH ADDR ; Move bits 15-8 (03H) of address MOVWF TBLPTRH ; to TBLPTRH MOVLW LOW ADDR ; Move bits 7-0 (00H) of address MOVWF TBLPTRL ; to TBLPTRL LFSR 0, 0x50 ; Initialize FSR0 to 0x50 to be used as

    ; destination pointer in data memory MOVLW D10 ; Initialize COUNTER with 10 MOVWF COUNTER ; Move [WREG] into COUNTER

    LOOP TBLRD*+ ; Read data from program memory ; into TABLAT, increment TBLPTR by 1

    MOVF TABLAT, W ; Move [TABLAT] into WREG

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 41

  • MOVWF POSTINC0 ; Move W into data memory pointed ; to by FSR0, and then increment FSR0 ; by 1

    DECF COUNTER, F ; Decrement COUNTER BY 1 BNZ LOOP ; Branch if Z = 0, else Stop MOVLW 0x10MOVWF STKPTRMOVLW 5 ; BCD digit arbitrarily chosenCALL SQUARE

    FINISH BRA FINISH

    ; Subroutine

    ORG 0x100SQUARE LFSR 0, 0x50 ; Starting address of the pointer

    ;where squares are stored

    MOVF PLUSW0, W ; Move the square of the BCD digit ;into WREG

    RETURNORG 0x300 ; Square of BCD digits

    ADDR DB D0, D1, D4, , D9, D16, D25, D36, D49, D64, D81 END

    7.14

    ; Main program

    INCLUDE ORG 0x200MOVLW 0x10MOVWF STKPTRMOVLW 5 ; BCD digit arbitrarily chosenCALL SQUARE

    FINISH BRA FINISH; SUBROUTINE

    ORG 0x100SQUARE MULLW 2 ;Double the WREG value

    MOVF PRODL,W ;Place the answer back into WREGADDWF PCL ;Use PCL to find the location on the table

    ; PCL CONTAINS THE STARTING ADDRESS OF THE TABLERETLW D0 ;Value for square of 0 RETLW D1 ;Value for square of 1 RETLW D4 ;Value for square of 2 RETLW D9 ;Value for square of 3

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 42

  • RETLW D16 ;Value for square of 4 RETLW D25 ;Value for square of 5RETLW D36 ;Value for square of 6 RETLW D49 ;Value for square of 7 RETLW D64 ;Value for square of 8 RETLW D81 ;Value for square of 9END

    7.15

    Assume BCD digit is low nibble of each byte; high nibble is 0.

    N = (N2 x 10 + N1) x 10 + N01

    The PIC18F assembly language program is provided below:

    INCLUDE ORG 0x150

    BCD2BIN MOVLW 0 ; Clear 8-bit sum in 0x50 to 0MOVWF 0x50MOVLW D10MOVWF 0x40LFSR 0, 0x30 ; Initialize pointerMOVF POSTINC0, W ; Move N2 into WREGMULWF 0x40 ; 10 x N2 PRODLdMOVF PRODL, WADDWF 0x50, FMOVF POSTINC0, W ; Move N1 into WREGADDWF 0x50, F ; (N2 x10 + N1) in 0x50MOVF 0x40, WMULWF 0x50 ; (N2 x10 + N1) x 10 in PRODLMOVF POSTINC0, W ; Move N0 into WREGADDWF 0x50, F ; Result in 0x50RETURNEND

    7.16

    ; Main programINCLUDE ORG 0x150LFSR 1, 0x30

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 43

  • MOVLW D20MOVWF STKPTRCALL SUMRRNCF 0X50,F ; Unsigned divide by 8 by shiftingRRNCF 0X50,F ;three times to rightRRNCF 0X50,FSLEEP

    ; SubroutineORG 0x100

    SUM CLRF 0x50 ; Clear sum to 0MOVLW 8MOVWF 0x60 ; Move 8 to 0x60

    BACK MOVF POSTINC1, W ; Move Xi to WREGADDWF 0x50, F ; Add Xis, result in 0x50DECF 0x60, FBNZ BACKRETURNEND

    7.17

    INCLUDE VALUE EQU 0x20 ;0x20 contains the numberCONST EQU 0x21COUNTER EQU 0x22

    ORG 0x100CLRF COUNTER ;Clear [COUNTER] to 0MOVLW 1SUBWF VALUE, F ;Subtract 1 from number. BN FINISHED ;If the number is 0, result will be negative,

    ;branch to endBACK INCF COUNTER, F ;else, increment [COUNTER] by 1

    MOVLW 2ADDWF CONST, F ;Increment [CONST] by 2 to obtain 3, 5 etcMOVF CONST, W ;Move [CONST] to WREGSUBWF VALUE, F ;Subtract [WREG] from [VALUE]BN FINISHED ;If result negative, go to endBRA BACK ; else, repeat

    FINISHED JMP FINISHED ;COUNTER contains sq root of the numberEND

    7.18

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 44

  • Since Fosc = 1 MHz, each instruction cycle = 4 sec

    Total Delay (D) for the DELAY loop = (145, 940 msec)/(4 sec) = 34, 685

    Delay (I2) in LOOP2 = 99 (3) + 2 = 299

    Delay (I1) between the label LOOP1 and the BNZ LOOP1

    instruction = (Q-1)x ( 2 + I2 + 3) + (2 + I2 + 4)

    = (Q-1)x (I2 + 5) + ( I2 + 6)

    = Q (I2 + 5) + 1

    = 304 Q + 1

    Total Delay in the DELAY loop including MOVLW, MOVWF, and RETURN =2 + I1 +2 = I1 + 4 = 304 Q + 5

    Hence, 304 Q + 5 = 34, 685

    304Q = 34, 680

    Therefore, Q = 120

    7.19

    The timing calculation for Method I is : 1 + 1 + 79 x (1 + 2) + 1 + 1 = 241instruction cycles.

    The timing calculation for Method II is : 1 + 1 + 79 x (1 + 1 ) + 1 + 2 = 163instruction cycles.

    If we assume a default clock of 1 MHz, then one instruction cycle = 4 x 1 sec = 4 sec.

    Therefore, the first delay loop (Method I) will take 0.964 msec while the second loop (Method II) will take 0.653 msec. Hence, Method II is better choice in termsof execution time.

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 45

  • Chapter 8

    8.1

    Pin numbers 11 and 32 are for power, and pin numbers 12 and 31 are for ground.The purpose is to distribute power in order to reduce noise.

    8.2

    1 MHz

    8.3

    Upon activating the pin, the PC is loaded with address 0.MCLR

    8.4

    A Power-on reset is generated upon power-up whenever VDD rises above a certain threshold.This allows the device to start in the initialized state when VDD is adequate foroperation.A manual reset, on the other hand, is activated a push button connecting to thePIC18F4321s pin via a reset circuit. The reset circuit provides theMCLRminimum timing requirements for the manual reset. During normal operation, aprogram can be executed by activating the push button.

    8.5

    The PIC18F4321 chip contains four 8-bit ports namely, Ports A through D, a 4-bit port called Port E.

    8.6

    (a) SETF TRISC (b)CLRF TRISD

    (c) MOVLW 0x0F (d)CLRF TRISAMOVWF ADCON1

    8.7INCLUDE

    SETF PORTC ; Configure PORTC as an input portBCF TRISD, 6 ; Configure bit 6 of PORTD as outputBCF PORTD, 6 ; Turn LED OFF

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 47

  • MOVF PORTC, F ; Input PORTC MOVLW 0x07ANDWF PORTC, F ; Retain low three bitsMOVLW 0x00 ; Check for no high switches, 0 is an even

    ;numberSUBWF PORTC, WBZ LED ; If no high switches, turn LED ONMOVLW 0x03 ; Check for two high switchesSUBWF PORTC, WBZ LED ; If two high switches, turn LED ONMOVLW 0x05 ; Check for two high switchesSUBWF PORTC, WBZ LED ; If two high switches, turn LED ONMOVLW 0x06 ; Check for two high switchesSUBWF PORTC, WBZ LED ; If two high switches, turn LED ON

    FINISH SLEEP ; HaltLED BSF PORTD, 6; Turn LED ON

    BRA FINISHEND

    8.8

    INCLUDE MOVLW 0x0F ;Configure PORTA and PORTB as

    ;inputsMOVWF ADCON1MOVF PORTA, W ;Input PORTA into WREGMOVWF 0x20 ;Save in 0x20MOVF PORTB, W ;Input PORTB into WREGMOVWF 0x21 ;Save in 0x21RRNCF 0x20, F ;Align data in PORTARRNCF 0x21, F ;Align data in PORTBBCF TRISA, RA0 ;Configure RA0 as outputBCF TRISB, RB0 ;Configure RB0 as outputMOVFF 0x20, PORTA ;Output to PORTA LEDMOVFF 0x21, PORTB ;Output to PORTB LED

    FINISH BRA FINISHEND

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 48

  • 8.9

    INCLUDE ORG 0x100MOVLW 0x04MOVWF TRISD ;Configure PORTD as output, turn LEDs

    ;OFFMOVLW 0x1B ;Output 11 to NAND inputs keeping LEDs

    ;OFFMOVF PORTD, W ;Input PORTD into WREGANDLW 4 ;Mask NAND output (bit 2)BNZ LED ;If NAND output is 1, turn ON faulty LEDMOVLW 0x19 ;Output 01 to NAND inputsMOVF PORTD, W ;Input PORTD into WREGANDLW 4 ;Mask NAND output (bit 2)BZ LED ;If NAND output is 0, turn ON faulty LEDMOVLW 0x1A ;Output 10 to NAND inputsMOVF PORTD, W ;Input PORTD into WREGANDLW 4 ;Mask NAND output (bit 2)BZ LED ;If NAND output is 0, turn ON faulty LEDMOVLW 0x18 ;Output 00 to NAND inputsMOVF PORTD, W ;Input PORTD into WREGANDLW 4 ;Mask NAND output (bit 2)BZ LED ;If NAND output is 0, turn ON faulty LEDMOVLW 0x10 ;Turn ON LED indicating good chipMOVWF PORTDBRA FINISH

    LED MOVLW 8 ;Turn ON LED indicating faulty chipMOVWF PORTD

    FINISH BRA FINISHEND

    8.10

    INCLUDE ; MAIN PROGRAM

    ORG 0x40SETF TRISC ;Configure PORTC is inputCLRF TRISD ;Configure PORTD is outputMOVLW 0x10 MOVWF STKPTR ;Initialize STKPTR to 0x10

    LOOP MOVF 0x20, W ;Move [0x20] to WREG

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 49

  • ANDLW 7 ;Mask the lower 3 bitsMOVWF 0x20MOVF 0x21, W ;Move [0x20] to WREGANDLW 7 ;Mask the lower 3 bitsADDWF 0x20, W ;Addition result in WREGCALL LOOKUP ;Call the subroutine LOOKUPMOVWF PORTD ;Move WREG to PORTDBRA LOOP ;Loop

    ; SUBROUTINEORG 0x70

    LOOKUP MULLW 2 ;Double the WREG valueMOVF PRODL,W ;Place the answer back into WREGADDWF PCL ;Use PCL to find the location on the table

    ; PCL CONTAINS THE STARTING ADDRESS OF THE TABLERETLW 0x3F ;Value for 0 displayRETLW 0x06 ;Value for 1 displayRETLW 0x5B ;Value for 2 displayRETLW 0x4F ;Value for 3 displayRETLW 0x66 ;Value for 4 displayRETLW 0x6D ;Value for 5 displayRETLW 0x7D ;Value for 6 displayRETLW 0x07 ;Value for 7 displayRETLW 0x7F ;Value for 8 displayRETLW 0x67 ;Value for 9 displayEND

    8.11

    INCLUDE ORG 0x100

    COUNTER EQU 0x20MOVLW UPPER ADDR ; Move upper 5 bits (00H) of address

    MOVWF TBLPTRU ; to TBLPTRU MOVLW HIGH ADDR ; Move bits 15-8 (03H) of address MOVWF TBLPTRH ; to TBLPTRH MOVLW LOW ADDR ; Move bits 7-0 (00H) of address MOVWF TBLPTRL ; to TBLPTRL LFSR 0, 0x30 ; Initialize FSR0 to 0x30 to be used as

    ; destination pointer in data memory MOVLW D10 ; Initialize COUNTER with 10

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 50

  • MOVWF COUNTER ; Move [WREG] into COUNTERLOOP TBLRD*+ ; Read data from program memory

    ; into TABLAT, increment TBLPTR by 1 MOVF TABLAT, W ; Move [TABLAT] into WREG MOVWF POSTINC0 ; Move W into data memory pointed

    ; to by FSR0, and then increment FSR0 ; by 1

    DECF COUNTER, F ; Decrement COUNTER BY 1 BNZ LOOP ; Branch if Z = 0, else StopSETF TRISC ; Configure PORTC as inputCLRF TRISD ; Configure PORTD as outputLFSR 0, 0x00 ; Load FSR0 to be used as a pointerMOVF PORTC, W ; Input an ASCII code in WREGMOVFF PLUSW0, PORTD ; using indexed addressing

    STAY BRA STAYORG 0x300 ; EBCDIC codes for BCD digits

    ADDR DB 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9 END

    8.12

    INCLUDE ORG 0x200

    START MOVLW 0x0F ;Configure PORTB as inputMOVWF ADCON1BCF TRISC, 1 ; Configure bit 1 of PORTC as an outputBCF PORTC, RC1 ;Turn LED OFF

    BACK MOVF PORTB, 0x20 ; Input PORTB into 0x20RRCF 0x20, W ; Rotate right once to align output dataBNC BACK ;Wait for the COMP.output to be HIGHBSF PORTC, RC1 ;Turn LED ONBRA STARTEND

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 51

  • 8.13

    The PIC18F assembly language program is provided in the following:

    INCLUDE ORG 0 ; RESETGOTO MAIN_PROG

    ; MAIN PROGRAMORG 0x00080 ; MAIN PROGRAM

    MAIN_PROG MOVLW 5 ; Initialize STKPTR with 5MOVWF STKPTRBCF TRISC,1 ; Configure bit 1 OF PORTC as

    ; outputMOVLW 0x0F ; Configure INT1 as inputMOVWF ADCON1BCF INTCON, INT1IF ; Clear interupt flagBSF INTCON3, INT1IE; Enable the external interruptBSF INTCON, GIE ; Enable global interruptsBCF PORTC, RC1 ; Turn LED OFF

    OVER BRA OVER ; Wait for interruptGOTO MAIN_PROG ; Repeat

    ; INTERRUPT SERVICE ROUTINEORG 0X000008BRA ISRORG 0x000150 ; Interrupt Address Vector

    ISR BSF PORTC, RC1 ; Turn LED ONBCF INTCON, INT1IF ; Clear the external interrupt

    ; flag to avoid double interruptRETFIE ; Enable interrupt and returnEND

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 52

  • 8.14 (a)

    (b)

    The PIC18F assembly language program is provided in the following:

    INCLUDE ORG 0 ; RESETGOTO MAIN_PROG

    ; MAIN PROGRAMORG 0x000150 ; MAIN PROGRAM

    MAIN_PROG MOVLW 0x10 ; Initialize STKPTR to 0x10MOVWF STKPTRMOVLW 1 ; Configure PORTC MOVWF TRISCMOVLW 0x0F ; Configure INT0 as inputMOVWF ADCON1 ; and bit 1 as inputBCF INTCON, INT0IF ; Clear interrupt flagBSF INTCON, INT0IE ; Enable the external interruptBSF INTCON, GIE ; Enable global interruptsBCF PORTC, RC3 ; Turn LED OFF

    OVER BRA OVER ; Wait for interruptGOTO MAIN_PROG ; Repeat

    ; INTERRUPT SERVICE ROUTINEORG 0X000008BRA ISR

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 53

    PIC18F4321

    .

    .0

    3

    INT0

    ToLED

    XFrom outputof top comparatorof Figure

    P8.14

    Fromoutputof ORgate inFigureP8.14

    PORTC

  • ORG 0x000200 ; Interrupt Address VectorISR MOVFF PORTC, 0x50 ; Move PORTC into 0x50

    RRCF 0x50BC LEDONBCF PORTC, RC3 ; Turn LED OFFBRA HERE

    LEDON BSF PORTC, RC3 ; Turn LED ONBCF INTCON, INT1IF ;Clear the external interrupt flag to

    ;avoid double interruptHERE RETFIE

    END

    8.15

    0x000008

    8.16

    The PIC18F4321 does not have any nonmaskable external interrupts. All external interrupts (INT0, INT1, INT2) are maskable.

    8.17

    High priority interrupt address vector is 0x000008.

    Low priority interrupt address vector is 0x000018.

    8.18

    Upon power-on reset, all interrupts in the PIC18F4321 have high priorities; nointerrupt priorities are available.

    8.19

    RETFIE instruction pops the contents of the program counter previously pushedbefore going to the service routine, enables the global interrupt enable bit, andreturns control to the appropriate place in the main program. The RETFIE 1instruction, on the other hand, pops the contents of WREG, BSR, and STATUSregisters (previously PUSHed) from shadow registers WS, STATUSS, and BSRSbefore going to the main program,, enables the global interrupt enable bit, andreturns control to the appropriate place in the main program.

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 54

  • 8.20

    In order to program INT1 as a high priority interrupt and INT2 as a low priorityinterrupt, the following instruction sequence can be used:

    BSF RCON, IPEN ; Set IPEN to 1, enable ; interrupt level

    BSF INTCON, GIEL ; Set low priority levelsBSF INTCON, GIEH ; Set high priority levelsBSF INTCON3, INTIP ; INT1 has high levelBCF INTCON3, INT2P ; INT2 has low level

    8.21

    INT0 has high priority level.

    8.22

    Upon power-on reset, each of the external interrupts (INT0, INT1, INT2) areactivated by a rising edge pulse (LOW to HIGH).

    The following PIC18F instruction sequence will activate the triggering level of INT0 by rising edge, and INT1 and INT2 by falling edge:

    BSF INTCON2, INTEDG0BCF INTCON2, INTEDG1BCF INTCON2, INTEDG2

    8.23

    The PIC18F4321 provides four interrupt-on-change pins (KB10 through KB13).These pins are multiplexed among others with bits 4 through 7 of PORT B.

    An input change (HIGH to LOW or LOW to HIGH) on one or more of theseinterrupts sets the flag bit, RBIF (bit 0 of INTCON register). Note that a single bitis assigned to all four interrupts.

    8.24

    The three control pins, EN, R/ , and RS allow the user to let the display knowWwhat kind of data is sent. The EN pin latches the data from the D0-D7 pins intothe LCD display. Data on D0-D7 pins will be latched on the trailing edge (high-to-low) of the EN pulse. The EN pulse must be at least 450 ns wide. The R/ (read/write) pin, allows the user to either write to the LCD or read data fromWthe LCD.

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 55

  • 8.25

    INCLUDE ORG 0x100 ; Start of the MAIN program

    MAIN MOVLW 5 ; Initialize STKPTR with arbitrary value; of 5

    MOVWF STKPTRCLRF TRISD ;PORTD is outputCLRF TRISB ;PORTB is outputSETF TRISC ;PORTC is input

    AGAIN MOVF PORTC, W ;Move switch values to WREGMOVWF 0x50 ;Save in 0x50MOVLW 0x0FANDWF 0x50, F ;Mask low 4 bits, and save in 0x50CPFSEQ 0x50 ;Compare switch values with 0x0FBRA AGAINCLRF PORTB ;rs=0 rw=0 en=0MOVLW D10 ;20 msec delayCALL DELAYMOVLW 0x0C ;Display on, Cursor offCALL CMDMOVLW D10 ;20 msec delayCALL DELAYMOVLW 0x01CALL CMD ;Clear DisplayMOVLW D10 ;20 msec delayCALL DELAYMOVLW 0x06 ;Shift Cursor to the rightMOVLW D10 ;20 msec delay CALL DELAYMOVLW 0x80 ;Move cursor to the start of the first lineCALL CMDMOVLW D10 ;20 msec delayCALL DELAYMOVLW A'P' ;Send ASCII PCALL LCDDATAMOVLW A'I' ;Send ASCII ICALL LCDDATAMOVLW A'C' ;Send ASCII CCALL LCDDATAMOVLW A'1' ;Send ASCII 1CALL LCDDATAMOVLW A'8' ;Send ASCII 8

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 56

  • CALL LCDDATAMOVLW A'F' ;Send ASCII FCALL LCDDATA

    FINISH BRA FINISHCMD MOVWF PORTD ;Command is sent to PORTD

    MOVLW 0x04MOVWF PORTB ;rs=0 rw=0 en=1MOVLW D10 ;20 msec delayCALL DELAYCLRF PORTB ;rs=0 rw=0 en=0RETURN

    LCDDATA MOVWF PORTD ;Data sent to PORTDMOVLW 0x05 ;rs=1 rw=0 en=1MOVWF PORTBMOVLW D10 ;20 msec delayCALL DELAYMOVLW 0x01MOVWF PORTB ;rs=1 rw=0 en=0RETURN

    DELAY MOVWF 0x20LOOP1 MOVLW D255 ;LOOP2 provides 2 msec delay with a

    ;count of 255MOVWF 0x21

    LOOP2 DECFSZ 0X21GOTO LOOP2DECFSZ 0x20GOTO LOOP1RETURNEND

    In the above, the following loop for the 2 msec delay is used:LOOP1 MOVLW D255 ;LOOP2 provides 2 msec delay with a count

    ;of 255MOVWF 0x21

    LOOP2 DECFSZ 0X21GOTO LOOP2

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 57

  • 8.26

    The main functions to be performed for interfacing a keyboard are:

    Sense a key actuation.Debounce the key. Decode the key.

    8.27

    The two-key lockout ensures that only one key is pressed. An additional keypressed and released does not generate any codes. The system is simple toimplement and most often used. However, it might slow down the typing becauseeach key must be released fully before the next one is pressed down. On the otherhand, the N-key rollover will ignore all keys pressed until only one remains down.

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 58

  • CHAPTER 9

    9.1Bit 7: Set to 0 so that TMR0 is offBit 6: Set to 1 in order to enable the 8-bit mode of TMR0Bit 5: Set to 1 so that an external crystal oscillator can be usedBit 4: Set to 1 so the timer will increment when the clock is going from high tolow, the negative edgeBit 3: Set to 0 in order to enable the prescaler functionBit 2-0: Set to 011 to enable a 1:16 prescaler

    Final solution:T0CON=0x73

    9.2

    Counter value = 100 = Initial counter value.The timer counts up from the initial value of 100 to 255, and then rolls over(increments) to 0. The number of counts for rollover is (255 - 100) = 155.

    Note that an extra cycle is needed for the roll over from 0xFF (255 ) to100x00, and the TMR0IF flag is then set to 1. Because of this extra cycle, the totalnumber of counts for rollover = 155 + 1 = 156 = 9CH. Hence, TMR0L should be10loaded with 9CH.

    INCLUDE ORG 0x70MOVLW 0x43MOVWF T0CON ;TMR0 8-bit 1:16 prescalerMOVLW 0x9CMOVWF TMR0L ;Count of 100 BCF INTCON, TMR0IF ;Clear TMR0 rollover interrupt flagBSF T0CON, TMR0ON ;Turn on TMR0

    LOOP BTFSS INTCON, TMR0IFBRA LOOP ;Wait for rollover

    FINISH BRA FINISHEND

    9.3

    Each half cycle of the square wave with 50% duty cycle is 2 msec.Clock Period = 1/(4 MHz) = 0.25 sec, Instruction cycle clock period = 4 x 0.25 sec= 1 sec.

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 59

  • No prescalar value is assigned.Time delay = Instruction cycle x Prescale value x CountHence, Count = (2 ms) / (1 sec ) = 2000 (0x07D0). The timer counts up from an10initialized value to 0xFFFF, and then rolls over (increments) to 0000H. Thenumber of counts for rollover is (0xFFFF - 0x07D0) = 0xF82F.

    Note that an extra cycle is needed for the roll over from 0xFFFF to 0x0000,and the TMR0IF flag is then set to 1. Because of this extra cycle, the total numberof counts for roll over = 0xF82F + 1 = 0xF830.

    The PIC18F assembly language program is provided below:

    INCLUDE ORG 0x70BCF TRISC, TRISC0 ;Bit 0 of PortC is outputMOVLW 0x08MOVWF T0CON ;TMR0 16-bit no prescaler

    BACK MOVLW 0xF8MOVWF TMR0H ;TMR0H valueMOVLW 0x30MOVWF TMR0L ;TMR0L valueBCF INTCON, TMR0IF ;Clear TMR0 interrupt flagCOMF PORTC, RC0 ;1's compliment of bit 0 PORTCBSF T0CON, TMR0ON ;Turn on TMR0

    LOOP BTFSS INTCON, TMR0IFBRA LOOP ;Wait for interruptBCF T0CON, TMR0ON ;Turn off TMR0BRA BACK ;Go againEND

    9.4

    From Problem 9.3, the TIMR1H:TMR1L should be loaded with 0xF830. ThePIC18F assembly language program is provided below:

    INCLUDE ORG 0x70BCF TRISD, RD7 ;Bit 7 of PORTD is outputMOVLW 0xC8MOVWF T1CON ;Setup Timer1 as 16-bit, no

    ;prescalerLOOP MOVLW 0xF8

    MOVWF TMR1H ;Value placed in TMR1HMOVLW 0x30

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 60

  • MOVWF TMR1L ;Value place in TMR1LBCF PIR1, TMR1IF ;Clear Timer1rollover interrupt

    ;flagCOMF PORTD, RD7 ;1's complement of bit 7 of

    ;PORTDBSF T1CON, TMR1ON ;Turn on Timer1

    WAIT BTFSS PIR1, TMR1IF ;Wait until Timer1 interrupt ;occurs

    BRA WAITBCF T1CON, TMR1ON ;Turn Timer1 offBRA LOOPEND

    9.5

    INCLUDE ORG 0x70BCF TRISC, TRISC0 ; Configure bit 0 of PORT C as

    ;outputBCF PORTC, RC0 ; Turn LED OFFCLRF T2CON ;8-bit, no prescaler and no postscalerCLRF TMR2 ; Clear TMR2 to 0MOVLW D200MOVWF PR2 ;count 200 timesBCF PIR1, TMR2IF ;Clear TMR2 interrupt flagBSF T2CON, TMR2ON;Turn on TMR2

    LOOP BTFSS PIR1, TMR2IF ;Wait for TMR2 to count to 200BRA LOOPBSF PORTC, RC0 ;Turn LED on

    FINISH BRA FINISHEND

    9.6

    Each half cycle of the square wave with 50% duty cycle is 2 msec.Clock Period = 1/(4 MHz) = 0.25 sec, Instruction cycle clock period = 4 x 0.25sec= 1 sec.Time delay = Instruction cycle x Prescale value x CountHence, Count = (2 ms) / (1 sec x 8) = 250 (0x00FA). The timer counts up from10an initialized value to 0xFFFF, and then rolls over (increments) to 0000H. Thenumber of counts for rollover is (0xFFFF - 0x00FA) = 0xFF05.

    Note that an extra cycle is needed for the roll over from 0xFFFF to 0x0000,and the TMR0IF flag is then set to 1. Because of this extra cycle, the total numberof counts for roll over = 0xFF05 + 1 = 0xFF06.

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 61

  • INCLUDE ORG 0x70BCF TRISC, TRISC3 ;PORTC pin 3 is outputMOVLW 0xBCMOVWF T3CON ;TMR3 16-bit with 1:8

    ;prescalerBACK BCF PIR2, TMR3IF ;Clear TMR3IF

    MOVLW 0xFF ;Initialize TMR3H:TMR3LMOVWF TMR3HMOVLW 0x06MOVWF TMR3LBTG PORTC, RC3 ;Toggle bit 3 of PORTCBSF T3CON, TMR3ON;Start TMR3

    LOOP BTFSS PIR2, TMR3IF ;Wait for TMR3IF to be oneBRA LOOPBCF T3CON, TMR3ON;Stop TMR3BRA BACKEND

    9.7

    INCLUDE D0 EQU 0x30 ;Set variables equal to a registerD1 EQU 0x31ADCONRESULT EQU 0x34

    ORG 0x000 ;ResetGOTO MAIN_PROG

    ; Main ProgramORG 0x100

    MAIN_PROG MOVLW0x10 ;Initialize STKPTR since interrupt ;and subroutines are used

    MOVWF STKPTR ;Value arbitrarily chosenCLRF TRISC ;Set PortC and PortD as outputCLRF TRISDMOVLW 0x01 ;Select AN0 for input and enable ;ADCMOVWF ADCON0MOVLW 0x0DMOVWF ADCON1 ; Set VDD and VSS as reference

    ; input voltages and AN0 as analog MOVLW 0x29MOVWF ADCON2 ;Left justified 12TAD and Fosc/8BSF PIE1,ADIE ;Enable the ADC interrupt flag

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 62

  • BCF PIR1, ADIF ;Clear the ADC interrupt flagBSF INTCON, PEIE ;Enable peripheral interruptsBSF INTCON, GIE ;Enable global interruptsBSF ADCON0,GO ;Start A/D conversion

    WAIT BRA WAIT ;Wait for interruptGOTO MAIN_PROG

    ;INTERRUPT SERVICE ROUTINEORG 0x0008 ;Interrupt Address VectorBCF PIR1, ADIF ;Clear ADIFMOVFF ADRESH,ADCONRESULT ;Move 8-bits of result into

    ; ADCONRESULT registerCALL DIVIDE ; Call the divide subroutineCALL DISPLAY ;Call display subroutineRETFIE

    DIVIDE CLRF D0 ;Clears D0 CLRF D1 ;Clears D1MOVLW D51 ;Load 51 into WREG

    EVEN CPFSEQ ADCONRESULT BRA QUOTIENT INCF D1, F SUBWF ADCONRESULT, F

    QUOTIENTCPFSGT ADCONRESULT ;Checks if ADCONRESULT ;still greater than 51

    BRA DECIMAL INCF D1, F ; increment D1 for each time

    ; ADCONRESULT is greater ; than 51

    SUBWF ADCONRESULT, F; Subtract 51 from ;ADCONRESULT

    BRA EVEN DECIMAL MOVLW 0x05 REMAINDER CPFSGT ADCONRESULT ; Checks if ADCONRESULT

    ; greater than 5BRA DIVDONE INCF D0, F ; Increment D0 each SUBWF ADCONRESULT, F ; Subtract 5

    ;from ADCONRESULTBRA REMAINDER

    DIVDONE RETURNDISPLAY MOVFF D1, PORTC ; Output D1 on integer 7-seg

    MOVFF D0, PORTD ; Output D0 on fractional 7-segRETURNEND

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 63

  • Instructors Manual Microcontroller Theory & Applications with the PIC18F 64

  • 9.8The hardware block diagram is provided below:

    Squareroot algorithm

    The square root of xi /N will be calculated up to one decimal point. Assume xi2 2to be an 8-bit number. Hence, the maximum value is 255. Since the square root of256 is 16, assume the initial value of the square root is 16. The square rootalgorithm is as follows:

    Suppose, xi /N is 225. Guess 16 as the square root. The difference is (16 -2 2225) = 31. Since the difference is positive, decrement the guess value of 16 by 1 toobtain 15. Calculate the difference, (15 - 225) = 0. Since the difference is 0, the2square root of 225 will be 15. Note that there would be no fractional part.Suppose xi /N is 255. Guess 16 as the square root. The difference is (16 - 255) =2 2-1. Since the difference is negative, decrement the guess value of 16 by 1 to obtain15. The integer part of the square root will be 15. Next, in order to calculate thefractional part in this case, calculate the difference, (255- 15 ) = 30 and then2increment the integer part by 1 to obtain 16, and then calculate the difference, (16 -215 ) = 31. Hence, Fractional part = Quotient of (30 x 10/31) = 9. Therefore, the2approximate value of the square root of 255 will be 15.9.

    Next, suppose, xi /N is 180. To find the square root of 180, first guess that2the square root of 180 as 16. Calculate the difference, (16 - 180) = 76. Since 76 is2positive, decrement 1 from 16 to obtain 15, and guess the next square root as 15.The difference, (15 - 180) = 45. Since 45 is positive, decrement 1 from 15 to2

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 65

    PORT C

    PORT A

    Analog Signal

    PIC18F4321

    0123

    a-g7

    a-g7

    7447

    7447

    DCBA

    DCBA

    Common Anode7-Segment Displays

    AbsoluteValue Circuit5v peak-to-peak

    45

    67

    PORT D

    3

    2

    1

    0A

    BCD

    7a-g

    7447

    AN0

  • obtain 14, and guess the next square root as 14. Calculate the difference (14 - 180)2= 16. Since 16 is positive, decrement 1 from 1 to obtain 13, and guess the nextsquare root as 13. Calculate the difference (13 - 180) = -11.Since the result is2negative, stop.Integer part is 13. Next, calculate the fractional part for this case. For fractionalpart, negate the differences -11 to obtain +11. Next, increment the integer part by 1to obtain 14, and then calculate the difference, (14 -180) = 16. Hence, the2fractional part = Quotient of (11 x 10/16) = 6. Therefore, the approximate value ofthe square root of 180 will be 13.6.

    Since the integer part will be displayed in BCD, the integer part should beconverted from binary to BCD. If the integer part is greater than 15, ten will besubtracted from 15, and a counter will be incremented by one. The counter valuewill be the upper most decimal digit of the two-digit integer displays. Thesubraction result will be the lower digit of the integer display.

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 66

  • (a) FLOWCHART FOR xi /N:2Instructors Manual Microcontroller Theory & Applications with the PIC18F 67

    Start

    Configure PortC and PortD

    Sum

  • FLOWCHART FOR COMPUTING THE INTEGER PART OF THESQUARE ROOT:

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 68

    Start

    [VALUE 0] 16

    Square [VALUE 0] in PRODL

    [VALUE 1] 9

    > 9

    No

    Output [VAUE 0]to Lower interger

    display. Blank upper integerdisplay

    [VALUE 3]

  • FLOWCHART FOR COMPUTING THE FRACTIONAL PART OF THESQUARE ROOT:

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 69

    1

    Negate [VALUE 1]and Store in

    VALUE

    Multiply [VALUE 2] by 1 0 and save [PRODL] in VALUE6

    Unsigned divide [VALUE5] by [VALUE 4]

    COUNTER2]

  • (b) The PIC18F assembly language program is provided below:

    INCLUDE VALUE0 EQU 0x30 VALUE1 EQU 0x31VALUE2 EQU 0x32VALUE3 EQU 0x33VALUE4 EQU 0x34VALUE5 EQU 0x35ADCONRESULT EQU 0x36SUM EQU 0x37COUNTER EQU 0x38COUNTER1 EQU 0x39COUNTER2 EQU 0x3A

    ORG 0x200CLRF TRISC ;Set PortC and PortD as outputCLRF TRISDMOVLW D128MOVWF COUNTERMOVLW 0x01 ;Select AN0 for input and enable ADCMOVWF ADCON0MOVLW 0x01MOVWF ADCON1 ; Set VDD and VSS as reference voltages

    ;and AN0 as analog inputMOVLW 0x29MOVWF ADCON2 ;Right justified 12TAD and Fosc/8CLRF SUM ;Clear SUM to 0

    START BSF ADCON0,GO ;Start AD conversionINCONV BTFSC ADCON0, DONE ;Wait until A/D conversion is done

    BRA INCONVMOVF ADRESH, W ;Move highest 8-bits of Xi into WREGMULWF ADRESH ;Compute Xi**2 in PRODLMOVF PRODL, W ;Move Xi**2 into WREGADDWF SUM, F ;Add (Xi**2) to SUMDECF COUNTER, F;Decrement COUNTERBNZ START ;Go back for the next sample

    ;Sum of Xi**2 in SUM. Next, compute SUM/128 by shifting SUM, seven times;to right

    BCF STATUS, C ;Clear Carry to 0DIVIDE MOVLW 7 ; Move 7 for dividing (Xi**2) by 128 via

    ;shiftingMOVWF COUNTERRRCF SUM, F

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 70

  • DECF COUNTER, FBNZ DIVIDE

    ;SUM contains 8-bit value of ( Sum of Xi**2)/128. CLRF COUNTER1 ;Clear COUNTER1 to 0MOVLW D16MOVWF VALUE0

    START1 MOVF VALUE0, W ;Move [VALUE0] to WREGMULWF VALUE0 ;Square [VALUE0] in PRODLMOVFF PRODL, VALUE1MOVF SUM, W ;Move [SUM] to WREGSUBWF VALUE1, FBNZ NEGATIVEMOVLW D9CPFSGT VALUE0 ;Check whether integer value

    ; greater than 9BRA DISPLAY1 ;If it is, the integer is

    ;between 10 and 15MOVLW 0xF0 ;Data for blanking upper

    ;integer display and retaining lower integerIORWF VALUE0MOVFF VALUE0, PORTC;Display integer on lower 7-seg

    ;display and blank upper seven segMOVLW 0 ;Display 0 on fractional displayMOVWF PORTD

    HERE BRA HEREDISPLAY1 MOVFF VALUE0, VALUE3

    MOVLW D10SUBWF VALUE3, FINCF COUNTER1, FMOVF COUNTER1, WSWAPF VALUE3, F ;Move lower integer to higher nibble

    ;of Port C IORWF VALUE3, FMOVFF VALUE3, PORTC;Output both integers to Port C

    FINISH1 BRA FINISH1NEGATIVEBN DISPLAY2

    DECF VALUE0, FBRA START1

    DISPLAY2 MOVLW D9CPFSGT VALUE0 ;Check whether integer value

    ;greater than 9BRA DISPLAY3 ;If it is, integer is between 10 and 15

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 71

  • MOVLW 0xF0 ;Data for blanking upper integer ;display and retaining lower integer

    IORWF VALUE0MOVFF VALUE0, PORTC;Display integer on lower 7-seg

    ;display and blank upper seven segMOVLW 0 ;Display 0 on fractional displayMOVWF PORTDBRA FRACTION

    DISPLAY3 MOVFF VALUE0, VALUE3MOVLW D10SUBWF VALUE3, FINCF COUNTER1, FMOVF COUNTER1, WSWAPF VALUE3, F ;Move lower integer to higher

    ;nibble of Port C IORWF VALUE3, FMOVFF VALUE3, PORTC;Output both integers to Port C

    ; Compute fractional partFRACTION MOVFF VALUE1, VALUE2

    NEGF VALUE2INCF VALUE0, FMOVF VALUE0, WMULWF VALUE0MOVFF PRODL, VALUE4MOVF SUM, WSUBWF VALUE4, FMOVF VALUE2, WMULLW D10MOVFF PRODL, VALUE5

    ; Unsigned divide [VALUE5] by [VALUE4], Quotient in COUNTER2MOVF VALUE4, W ; Divisor in WREGCLRF COUNTER2 ; Clear COUNTER2 to 0

    BACK CPFSEQ VALUE5 ; If dividend equals ;divisor, skip next instr.

    BRA RESULT ; If not equal, branch to ;RESULT

    INCF COUNTER2, F ; Increment COUNTER2 SUBWF VALUE5, F ; Subtract divisor from

    ;dividend, result in VALUE5BRA DISPLAY4 ; Go to DISPLAY4

    RESULT CPFSGT VALUE5 ; If dividend greater than divisor, ;skip next inst.

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 72

  • BRA DISPLAY4 ; Quotient in COUNTER2, ;Remainder in VALUE5, halt

    INCF COUNTER2, F ; Increment [COUNTER2] by 1SUBWF VALUE5, F ; Subtract divisor from

    ;dividend, result in COUNTER2BRA BACK ; Repeat

    DISPLAY4 MOVFF COUNTER2, PORTD; Display fractional part on Port CFOREVER GOTO FOREVER ; Halt

    END

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 73

  • 9.9(a)Discharge voltage, Vc (t) = k e . For one time constant, t = RC. Hence, Vc (t) =t/RC(k/e). Hence, Vc(t) = 0.368 k. If k = 5.5V is arbitrarily used in this example, thenVc(t) = 2.02V for one time constant.

    Figure above shows the hardware schematic of the capacitance meter. Thecapacitor is charged by outputting a 1 (5 V) via bit 0 of Port C. Three 741 opamps are used. With a gain of 3, a 15V output is obtained from the 741 connectedto bit 0 (RC0) of Port C. Since discharge time is used rather than charging time, assoon as the capacitance is charged to 5.5 volts (arbitrarily chosen) as detected byanother 741 connected to bit 1 (RC1) of Port C, the PIC18F 4321 is programmedto output 0 from RC0 so that the capacitor starts discharging. A counter isincremented using a one-second software delay loop. When the voltage drops to2.02V after one time constant detected by another 741 via bit 2 (RC2) of Port C,the counter is stopped. The content of the counter will provide the value of thecapacitor in microfarad. This is because one Megaohm resistor is used to chargethe capacitor. Capacitors of different ranges of values (picofarad, nanofarad) canbe obtained by selecting different resistor values. The counter value is output to two seven-segment displays via two 7447s. The capacitor value in the range of 1F to 15 F is used; the fractional part is discarded.

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 74

  • (b)#INCLUDE

    ORG 0BRA MAIN

    MAIN ORG 0x200DELAY EQU 0x14DELAY1 EQU 0x15COUNTER EQU 0x30

    BCF TRISC,TRISC0 ;Configure bit 0 of Port C as outputBSF TRISC, TRIS1 ;Configure bit 1 of Port C as inputBSF TRISC,TRIS2 ;Configure bit 2 of Port C as inputCLRF TRISD ;Configure Port D as outputCLRF PORTDCLRF COUNTER ;Clear COUNTER to 0BSF PORTC, RC0 ;Start charging the capacitor

    WAIT BTFSS PORTC, RC1 ;Check RC1 for HIGH to dischargeBRA WAIT ;else, waitBCF PORTC, RC0

    WAIT1 MOVLW D249 ;Time delay for 500 cyclesMOVWF DELAY

    LOOP1 MOVLW D249 ;Time delay for 500x500 cycles, 1-sec delayMOVWF DELAY1

    LOOP DECF DELAY1, FBNZ LOOPDECF DELAYBNZ LOOP1INCF COUNTER, F ;Start incrementing COUNTERBTFSC PORTC, RC2 ;Check RC2 to be LOW for doneBRA WAIT1 ;Capacitor will be [COUNTER]MOVLW 0ADDWF COUNTER, WDAW ;Convert into correct packed BCDMOVWF PORTD ;Output WREG to Port DSLEEPEND

    9.10Assume 8 MHz internal clock. Each instruction cycle is 0.5 s. Time delay = Instruction cycle x Prescale value x Counter valueFor 1 sec delay with prescale value of 1:128,Counter value = (1 sec)/ ( 0.5 s x 128) = 15625 = 3D09H. The counter counts upfrom an initial value of FFFFH, and then rolls over to 0000H. The number ofcounts for rollover = FFFFH - 3D09H = C2F6H. An extra cycle is needed forrollover. Hence, total number of counts = C2F7H.

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 75

  • The PIC18F assembly language program is provided below:

    INCLUDE SEC EQU 0x20MIN EQU 0x21HOUR EQU 0x22

    ORG 0X70MOVLW 5MOVWF STKPTRMOVLW 0x06MOVWF T0CON ;1:128 prescale, internal oscillator

    ; For 1 sec time delay, initialize TMR0H with 0xC2, and TMRL with 0xF7MOVLW 0xC2MOVWF TMR0H ;Value placed in TMR0HMOVLW 0xF7MOVWF TMR0L ;Value placed in TMR0LBCF INTCON, TMR0IF;Clear Timer0 interrupt flagBSF INTCON, TMR0IE;Enable Timer1 interruptCLRF SEC ;Clear SEC registerCLRF MIN ;Clear MIN registerCLRF HOUR ;Clear hour registerBSF T0CON, TMR0ON;Turn on Timer0

    LOOP BTFSS INTCON, TMR0IFGOTO LOOPINCF SECMOVLW D'60' ;Move 60 into WREGCPFSLT SEC ;Compare value in SEC to 60 and skip if less thanCALL INC_MIN ;else, call the INC_MIN subroutineBSF T0CON,TMR0ONBRA LOOPORG 0x100

    INC_MIN CLRF SEC ;Clear SEC registerINCF MIN ;Increment the MIN registerMOVLW D'60' ;Move 60 into WREGCPFSLT MIN ;Compare value in MIN to 60 and skip if less thanCALL INC_HOUR;else, call the INC_HOUR subroutineRETURNORG 0x200

    INC_HOUR CLRF MIN ;Clear MIN registerINCF HOUR ;Increment the HOUR registerMOVLW D'25' ;Move 25 into WREGCPFSLT HOUR;Compare value in HOUR to 25 skip if less thanCLRF HOUR ;Clear HOUR register

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 76

  • SLEEPEND

    9.11INCLUDE

    ADCONRESULT EQU 0x36VALUE EQU 0x37

    ORG 0x200CLRF TRISC ;Set PortC and PortD as outputCLRF TRISDMOVLW D128MOVWF COUNTERMOVLW 0x01 ;Select AN0 for input and enable ADCMOVWF ADCON0MOVLW 0x01MOVWF ADCON1 ; Set VDD and VSS as reference voltages

    ;and AN0 as analog inputMOVLW 0x29MOVWF ADCON2 ;Left justified 12TAD and Fosc/8BSF ADCON0,GO ;Start AD conversion

    INCONV BTFSC ADCON0, DONE ;Wait until A/D conversion is doneBRA INCONVMOVF ADRESH, W ;Move 8-bits of Xi into WREGMULWF ADRESH ;Compute Xi**2 in PRODLMOVF PRODL, VALUE ;Move Xi**2 into VALUECLRF STATUS, C ;Clear the carry flagRRCF VALUE ;Divide (VALUE **2) part by 2

    ;VALUE will contain power in mW END

    Instructors Manual Microcontroller Theory & Applications with the PIC18F 77

  • 9.12The block diagram is provided below:

    The PIC18F assembly language program is provided below:

    INCLUDE ;RESET vector

    ORG 0x000GOTO MAIN

    ;Interrupt address vectorORG 0x0008 ;System will go to CHECK_INT at interruptGOTO CHECK_INT

    ;Interrupt service routineORG 0x0040

    CHECK_INT BTFSS PORTB, RB1 ;If RB1 = 1, DecrementBRA INC_ISRBCF INTCON, INT0IF ;Clear INT0 interrupt flagMOV