Top Banner
CMPT 229 – PIC Microcontroller Grant MacEwan University - Fall 2010 Mr. Marcel Berard
85
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
Page 1: DSpic

CMPT 229 – PIC Microcontroller

Grant MacEwan University - Fall 2010

Mr. Marcel Berard

Page 2: DSpic

PIC24 Features and Architecture Memory and I/O Using MPLAB PIC24 ASM Language

Topics

Page 3: DSpic

Microchip document 39747C.pdf:

PIC24FJ128GA Family Data Sheet

Microchip document 51281F.pdf:

MPLAB IDE Quick Start Guide

Microchip document 70157B.pdf:

dsPIC30F/33F Programmers Reference Manual

References

Page 4: DSpic

The PIC microcontrollers are manufactured by a company called Microchip Technology Inc. (www.microchip.com) which has its headquarters in Arizona.

The sales made by Microchip have increased rapidly in the past 25 years. Microchip is one of the leading providers of microcontrollers.

PIC Features

Page 5: DSpic

The PIC microcontrollers are a complete computer on a single chip. They typically do not have external devices such as disk drives or keyboards.

Since a PIC program cannot be stored on a hard drive, it is stored in flash memory which retains its contents when powered off.

PIC Features

Page 6: DSpic

The PIC24 microcontrollers are referred to as a 16-bit microcontrollers. This is because the data word width is 16 bits which is the amount of data processed during an instruction. All PIC controllers have instructions such as add and sub as well as the logical operations and branches. The newer controllers also have hardware mul and div instructions as well as additional addressing modes.

Earlier PIC microcontrollers such as the PIC12, PIC16 and PIC18 were 8 bit. In 2007, Microchip introduced a line of 32 bit PIC microcontrollers.

PIC Features

Page 7: DSpic

There are some 16-bit PIC microcontrollers that are more powerful than the PIC24. These are the dsPIC30 and dsPIC33 controllers.

The dsPIC is an enhancement of the PIC that can also perform digital signal processing. DSP requires extensive floating point multiplication. As one example, DSP can take an analog signal (such as from a modem) representing binary data and convert the analog signal to digital data.

PIC Features

Page 8: DSpic

The PIC microcontrollers have I/O pins; these are the legs on the chip. These pins are used to communicate with the outside world. The number of pins can vary from about 8 to 150. The high-end PIC24s have from 64 to 100 pins.

Most of the PIC inputs and generally all of the outputs are binary (Binary input/output = 0 volts or operating voltage). A binary PIC input could be used to indicate if a switch was open or closed. A binary output could be used to switch an LED on or off.

Are there any uses for the pins other than I/O?

PIC Features

Page 9: DSpic

For many PICs, some of the PIC inputs are analog. An analog input can accept a continuous range of input voltages from 0 to the operating voltage.

An analog-to-digital converter (ADC) inputs an analog voltage and converts it internally to a digital (unsigned integer) value. For example, consider an 8-bit ADC that accepts voltages from 0 to 2.55 Volts. What integer value would it produce for an input voltage of 1 Volt or 2.352 Volts?

Some specialized PICs also have digital-to-analog converters (DACs). What is their purpose?

PIC Features

Page 10: DSpic

Another feature found in many PICs is one or more serial ports (UARTs). These ports are similar to the COM port found in (older) PCs and provide a mechanism for communicating with a PC.

Some of the newer PICs also support onboard USB, providing for a superior communication protocol with a PC.

Many PICs also support various communication protocols that can be classified as electronic (SPI, I2C) and industrial (CAN, ModBus) protocols.

PIC Features

Page 11: DSpic

The PIC24 microcontroller is quite inexpensive (about $5 - $20 depending on the sub-series). Lower end PIC microcontrollers such as the PIC12 sell for < $1.

Late model cars can contain several microcontrollers. One sample application for a microcontroller is to control the airbags.

Other devices such as washing machines can also be controlled by a microcontroller.

PIC Features

Page 12: DSpic

A PIC microcontroller is often referred to as an embedded controller. It typically has a single role; to control the device in which it is embedded.

A sample (infinite) loop for a chip controlling an airbag was presented earlier and is repeated here.

SensorLoop:# Read data from acceleration sensors# Branch to SensorLoop if accel data is

normal# Deploy airbag# Replace airbags

PIC Features

Page 13: DSpic

The previous program is a common template for a PIC program. Once the PIC is powered on, it goes to the start of its program and typically has an infinite loop that is performed until it is powered off. Note: A program like this completely controls the PIC and has no restrictions. There is no protected mode as there is on a MIPS CPU.

PICs also have a feature referred to as brown-out protection. If the supply voltage drops below an acceptable value (say 2 V on a 3 V PIC) such that some data may become corrupted, then the PIC will reset which involves the program being sent back to the start so that the PIC properly re-initializes itself.

PIC Features

Page 14: DSpic

The PIC24 controllers have various clocking (oscillator) alternatives that run the chip at different speeds.

Providing a faster clock allows the controller to perform the instructions more quickly. (The maximum performance of the PIC24 is 16 MIPS.) Is there any advantage to a slower clock?

PIC Features

Page 15: DSpic

The PIC microcontrollers utilize the Harvard architecture (actually a modified Harvard architecture). With this architecture, there are 2 separate memories, a program memory and a data memory. Each memory has its own address space.

There are separate buses leading to the two memories. Address 100 in the program memory differs from address 100 in the data memory.

PIC Architecture

Page 16: DSpic

The program memory space has a 24 bit address. Thus, there appears to be 224 bytes or 16 MB. However, only half of the addresses are available to program instructions, the top half is for configuration data (ie. clock mode). The PC has 23 bits. Every instruction is 24 bits (3 normal bytes) but occupies 2 program memory addresses. Thus, the program memory logical address space can hold 4 million instructions.

The amount of physical program memory varies between the PIC24 models from 64 KB to 128 KB which supports 22,016 up to 44,032 instructions.

PIC Architecture

Page 17: DSpic

The data memory space has a 16 bit address so it is 216 bytes (64 KB) on all PIC24s. Data memory is byte addressable. A data word is 16 bits (2 bytes) so the address space can contain 32 KB words. Memory accesses are usually word operations.

The amount of physical data memory (RAM) in most PIC24s is 8 KB. This memory is volatile and loses its data when powered off.

There is no virtual memory in a PIC. All data addresses are absolute. The higher addresses are empty.

PIC Architecture

Page 18: DSpic

The PIC24 has special function registers (SFRs) mapped into the first 2 KB of the data address space. I/O is performed by reading or writing at these addresses. This is equivalent to memory mapped I/O on the MIPS architecture.

Most of the addresses between 0 and 2 KB are empty as there is not a SFR at every word address.

The operations (read or write) performed on SFRs depend on whether they perform input or output or both.

PIC Architecture

Page 19: DSpic

The 8 KB of physical RAM occupies the memory addresses from 2 KB to 10 KB. The memory cells at these addresses can be read or written.

The data addresses from 10 KB to 32 KB are empty and should not be accessed.

The data addresses from 0 to 8 KB (including SFRs) are referred to as the near data space. These addresses can be represented with 13 bits and are stored within many instructions. Thus, they can be accessed with the direct addressing mode more easily than cells at higher addresses.

PIC Architecture

Page 20: DSpic

Data addresses between 32 KB and 64 KB may be empty or may be mapped into program memory. The PIC24 has two mechanisms for mapping data addresses (above 32 KB) into the program memory space. This is why its architecture is referred to as a modified Harvard architecture.

As an example application of this feature, constants can be stored in the program memory and mapped to data memory at program start.

PIC Architecture

Page 21: DSpic

The PIC24 has 16 (16-bit) working registers. Early PIC models had only a single 8-bit working register.

The PIC24 register names are W0 to W15 (or WREG0 to WREG15). On previous PICs, the only working register was called WREG. Register W0 (WREG0) on the PIC24 is equivalent to WREG on earlier PIC controllers.

The PIC24 working registers are mapped into the data memory as SFRs at word addresses 0x00 to 0x1E.

PIC Architecture

Page 22: DSpic

On earlier PIC controllers, WREG was often used implicitly during instructions.

To maintain compatibility, the PIC24 maintains many instructions from earlier PIC models. The PIC24 uses register W0 as WREG.

PIC Architecture

Page 23: DSpic

Register W15 is implicitly used as the stack pointer and W14 as the frame pointer. The programmer can also explicitly write to these registers as they are working (general-purpose) registers.

If a program does not use a stack (W15) or linking and unlinking (W14), then it is safe to use these registers for other purposes.

These registers are used extensively by high level languages such as C. The PIC24 architecture was designed with 3rd generation languages in mind.

PIC Architecture

Page 24: DSpic

MPLab is the (free) Windows software IDE provided by Microchip to develop software for its PIC and dsPIC microcontrollers. The current MPLab version is 8.6.

With MPLab, code is developed in the Windows environment and the binary executable file (and device configuration information) is burned into the flash memory of a PIC device. The executable file was traditionally outputted from the PC via a COM port but a USB transfer is more common today.

MPLab

Page 25: DSpic

MPLab contains a project manager, an editor, an assembler (MPASM), a linker, a software simulator (MPLab SIM) and interfaces to its programming / debugging devices. It is a complete environment for assembly language programming.

MPLab has an open interface that is easily expandable. Microchip provides a lite (free) C compiler that can be integrated into MPLab. There are several 3rd party compilers; almost all C, and at least one Pascal compiler. MPLab 8 also has an integrated copy of the PICC LITE C compiler.

MPLab

Page 26: DSpic

A complete tutorial for building an MPLab project is given in Chapter 2 of document 51281F.pdf. A relatively brief description will be given here.

Create a folder in which to put the project. Select Project > Project Wizard.. and accept Next. Select the appropriate device (PIC24FJ128GA010). Select the appropriate toolsuite (Microchip ASM30 Toolsuite)

from the drop down list at the top. Select a project name and directory. Add files to the project. This step will not be performed here. When finished, the project window shows some empty folders

based on groups such as Source Files and Header Files.

MPLab

Page 27: DSpic

To compile an MPLab project, 3 files are required: an include file, a linker file and a source code file. These 3 files are provided in a Template project built by the instructor.

The include (header) file declares the existence of SFRs and various other aspects of the chip. We will use the include file: pf24FJ128GA010.inc

The appropriate linker script defines the locations of the declared SFRs. We will use pf24FJ128GA010.gld.

Note: The include and linker files are located in the installation directory. Normally, the project contains links to the original files. The Template project has placed a copy of these files in the project directory.

MPLab

Page 28: DSpic

MPLab does not provide an assembly source code template for the PIC24. Microchip anticipates that the C language will be used almost exclusively for this chip.

A minimal PIC24 source code template (Template.s) has been placed in the Template project.

The menu items Project > Make (F10) or Project > Build All (Ctrl + F10) can be used to generate the project executable.

MPLab

Page 29: DSpic

The PIC assembly source code has many similarities with the MIPS assembly source code.

PIC assembly has a data segment and a text segment. At a minimum, the text segment (code) for a control application should have an infinite (polling) loop.

Another requirement is a definition of the program entry point, this is the .global directive in the source code template.

MPLab Code

Page 30: DSpic

A minimal source code file is shown below.

; #include "p24FJ128GA010.inc“

.global __reset

.data ;Start of data section

.text ;Start of code section

__reset:

loop:

BRA loop ;End of main

.end ;End of source

MPLab Code

Page 31: DSpic

Single line comments are started with the semi-colon.

The (commented out) include directive contains the SFR declarations for a particular microcontroller.

The __reset variable is the program entry point at controller reset. It’s scope is set to global to make it visible to the linker.

Labels are defined the same as for the MIPS controller, an identifier followed by a colon.

MPLab Code

Page 32: DSpic

The program shown can be built and run. It is an empty infinite loop.

The only instruction used in the code is the branch (BRA or bra). The instruction mnemonics are not case sensitive (compiler) but the identifiers are case sensitive (linker).

By default, the user program instructions start at address 0x200.

MPLab Code

Page 33: DSpic

The data for a PIC program is defined in the data segment (directive .data). Multiple items are comma separated. The data types include:

.ascii (requires an explicit null terminator) .asciz (implicit null terminator) .byte .int or .long (4 bytes) .word (2 bytes) .double (8 bytes) .pword (3 bytes) .space

MPLab Code

Page 34: DSpic

A sample data segment is as follows. The value following a space declaration indicates the byte count. The following declaration allocates 18 bytes in the data segment. By default, the (global) data variables are placed at a start address of 0x800 (the start of RAM). Thus, variable x is at address 0x810.

.data

w: .space 16

x: .word 1

MPLab Code

Page 35: DSpic

MPLab provides a simulator (MPLAB SIM) to view the “operation” of a PIC program on the PC.

To use the simulator, select it via the Debugger > Select Tool menu item.

Note that there are several other debugging tools available. MPLAB SIM is a software emulator run on the PC. The other debugging tools all involve external hardware. Some such as MPLAB ICD 3 involve a PIC microcontroller that is under the control of a hardware debugger while others such as the ICE options are specialized hardware devices that emulate the PIC microcontrollers.

MPLab Debugging

Page 36: DSpic

When there is a debugger selected, there are several items added to the Debugger menu. These items (Run, Step Into, Step Over, Reset) allow the operator to step through the code on a line by line basis or to run to a breakpoint. A green arrow shows the current instruction. Note that the program counter (pc) is shown in the status bar.

Breakpoints are added or removed by double-clicking in the gutter next to a line.

For the previous template program, the branch instruction (at address 0x200) is the only instruction ever performed.

MPLab Debugging

Page 37: DSpic

When debugging, the operator typically wants to observe the program data or code. There are several program windows that can be displayed in the View menu.

The File Registers window shows the data memory contents from address 0x0000 to 0x27FF (10 KB). What is in this region of memory and why are some of the entries empty? Note: The file registers can also be edited from this window to provide a program with specific data.

MPLab Debugging

Page 38: DSpic

The Program Memory menu item in the View menu displays a window with the contents of program memory. By scrolling to the bottom of this window, the last address is 0x157FA. This corresponds to about 128 KB of program memory.

When reset, the PIC PC is set to 0. The instruction at address 0 is goto 0x000200. What is at address 200 and beyond?

What are the instructions at addresses between 0 and 0x200 and what is their purpose?

MPLab Debugging

Page 39: DSpic

The Special Function Registers menu item in the View menu displays a window with the contents of the SFRs. These registers are memory mapped into the data address from 0 to 0x7FE (first 2 KB).

In addition to the addresses, this window displays the names of the SFRs so that it is easier to find a specific SFR. Note the addresses of the WREGs.

As stated previously, there are many holes in the SFR address space.

MPLab Debugging

Page 40: DSpic

Before looking at common program instructions, consider the RESET and NOP instructions which are both control instructions.

The RESET instruction causes a software reset. This is equivalent to powering on the PIC. It places all of the registers in their power-on state including the PC which is set to 0.

The NOP instruction stands for NO OPERATION. This instruction consumes a clock cycle but does not perform any operation. What is its purpose?

PIC24 Instructions

Page 41: DSpic

The PIC24 has about 76 instructions that fall into the following groups. Its instructions are those of the 30F/33F except for the DSP instructions.

Move Math Logic Rotate/Shift Bit Compare/Skip Program Flow Shadow/Stack Control

PIC24 Instructions

Page 42: DSpic

The PIC24 instructions have operands of various sizes: byte, word, long …

For byte operands, the instruction has a trailing “.b”. For word operands, the trailing “.w” is optional.

The instructions have 4 addressing modes for their operands which are listed below.

Immediate File Register Register Direct Register Indirect

PIC24 Instructions

Page 43: DSpic

An immediate operand is stored within the instruction. In the assembly code, such operands are preceded by the # symbol. The operand can be given in either decimal (#10) or hexadecimal (#0xA).

Immediate operands are typically used to load values into registers or to be used as an offset when calculating an address.

PIC24 Instructions

Page 44: DSpic

A file register operand corresponds to a data memory location (address) which is any integer from 0x0000 and 0xFFFF inclusively. This can correspond to a RAM location or a SFR.

File register operands can be specified numerically (ie. 0x810) or symbolically based on an identifier in the data segment (ie. x). The following notes use numerical addresses to avoid the problem of showing variable names in every example. Clearly, the symbolic representation is superior as the address of a variable can change if other variables are placed in front.

PIC24 Instructions

Page 45: DSpic

How can the address of a variable be determined so that it can be placed in a register? For example, how is the address of x obtained?

For word operations, the address must be word aligned or a bad address exception will be generated.

PIC24 Instructions

Page 46: DSpic

A register direct operand corresponds to one of the working registers W0 .. W15. These operands only require 4 bits. Some instructions have 3 register direct operands.

Some instructions implicitly use W0. This is to maintain compatibility with earlier PICs.

PIC24 Instructions

Page 47: DSpic

A register indirect operand uses the contents of a working register as a data memory address. This corresponds to indirection and has the syntax [Ws] where Ws is one of W0 .. W15.

When a PIC is powered on, the hardware knows that the W registers are uninitialized. A W register must be written to before it can be used for indirection. If not, an exception is generated.

PIC24 Instructions

Page 48: DSpic

The register indirect operand type supports constant (literal) offsets. An example operand is [W1 + #4].

Two registers can also be used to generate an operand, for example: [W2 + W3].

This operand type also supports pre and post incrementing or decrementing, ie. [W1++]. The increment amount depends on the data size of the instruction.

PIC24 Instructions

Page 49: DSpic

A side effect of many instructions is modifying the status register (SR). This clearly applies to the compare instruction but also to other instructions.

The status register has 16 bits. Two of these bits are the N (negative) and Z (zero) bits. The N bit is set when an operation has a negative result and the Z bit when an operation has a zero result.

The status register is used for conditional branches. Thus, conditional branches depend on the last instruction that set the status register.

PIC24 Instructions

Page 50: DSpic

The move instructions copy data from one register to another, from data memory to/from a register or can copy a literal into a register. The default is a word move but byte (.B) and double word (.D) moves are also supported. Note: Some variations of the move instruction affect the status register (SR). Some examples are given below.

MOV WREG, 0x800 ; Store WREG to data memory MOV.B WREG, 0x801 ; Store LSB to memory MOV 0x2006, W3; ; Load W3 from data memory MOV W8, 0x1500 ; Store operation MOV.B #0x24, W6 ; Similar to MIPS li for 1 byte MOV #0x1234, W11 ; li for a word

PIC24 Instructions

Page 51: DSpic

There are more complex move operations that load or store by using a base-offset address technique. A base address is stored in a register and an immediate offset (10 bit signed) is added to generate a memory address. What is a sample application of this addressing mode?

MOV [W4 + 0x220], W5 ; Load

MOV W10, [W9 – 0x200] ; Store

PIC24 Instructions

Page 52: DSpic

There are also variations of the move instruction that can increment or decrement registers (pre or post) as they are working with the memory address contained in that register. Another variation performs a memory to memory move by building an address from the contents of two registers.

MOV [W0++], W8 ; Load into register W8

MOV W10, [W6--] ; Store into memory at address [W6]

MOV [W8], [W6+W7]

PIC24 Instructions

Page 53: DSpic

The math operations include ADD and SUB. These instructions affect the status register. Some examples with various addressing modes are given below.

ADD #0x1234, W8 ; Add an immediate value to register W8

ADD.B W4, #0xFF, W5 ; W5 = W4 + (-1)

ADD W6, W7, W8 ; W8 = W6 + W7

ADD W5, #0x0400, [++W6] ; Add and store (pre-increment)

SUB 0x1200 ; [0x1200] = [0x1200] – WREG

SUB 0x1200, WREG ; WREG = [0x1200] – WREG

SUB #0x200, W4 ; W4 = W4 – #0x200

PIC24 Instructions

Page 54: DSpic

The math operations also include multiply (MUL). The MUL operation can be in byte mode or word mode. The byte mode requires a 16-bit destination and the word mode a 32-bit destination. Some examples of MUL with various addressing modes are given below. The MUL operation involving a file register implicitly uses W3:W2 as the destination (similar to HI:LO) for word mode and W2 for byte mode. MUL does not affect the SR.

MUL 0x800 ; W3:W2 = [0x800] * WREG (unsigned) MUL.SS W0, W1, W12 ; W13:W12 = W0 * W1 (signed) MUL.SS W4, [++W8], W6 ; W7:W6 = W4 * [W8] MUL.US W2, [W3], W4 ; signed result = unsigned * signed

PIC24 Instructions

Page 55: DSpic

The math operations also include divide (DIV). There are variations such as a 16 bit by 16 bit divide or a 32 bit by 16 bit divide. The DIV operation is more complex to program as it does not execute in a single cycle. Due to this, the divide instruction requires a loop that is controlled with a REPEAT instruction (loops 18 times). DIV affects the SR.

PIC24 Instructions

Page 56: DSpic

Other math operations include negate (NEG), increment (INC, INC2), decrement (DEC, DEC2) and sign extend (SE). Some examples are given below.

NEG 0xA00, WREG ; WREG = - [0xA00] NEG 0xCC4 ; [0xCC4] = - [0xCC4] NEG [W5++], [--W8] INC W1, W2 DEC2 W3, [W4++]

PIC24 Instructions

Page 57: DSpic

The logical operations include and (AND), clear (CLR), complement (COM), inclusive or (IOR), set (SETM) and exclusive or (XOR). Most of these operations affect the status register. Some examples are given below.

AND #0xA0B0, W6 ; W6 = #0xA0B0 AND W6 CLR W0 COM.B 0xA00 IOR #0x3456, W2 ; W2 = W2 IOR #0x3456 SETM 0x880 ; Set [0x880] to 0xFFFF

PIC24 Instructions

Page 58: DSpic

The bit operations act on a single bit. There are the usual operations of testing a bit (BTST), clearing a bit (BCLR), setting a bit (BSET) and toggling a bit (BTG). These operations are equivalent to reading a word, masking out all but one bit and possibly writing the word. These operations are typically used for reading the state of a digital input or writing the state of a digital output. The BTST operation sets the Z flag in SR.

BCLR 0x400, #0x6 ; Clear bit 8 at address 400 BSET [W4++], #0x0 ; Set bit 0 BTG 0x1200, #0x2 ; Toggle bit 2 BTST 0x600, #0x4 ; Test bit 4, where is the result?

PIC24 Instructions

Page 59: DSpic

The compare/skip operations are used to implement simple jumps. A skip jumps over one instruction (which is usually a goto). This technique was used extensively with the early PIC processors but has been superseded with more modern techniques. The pseudo-code for a post-test loop is shown below. Note: This type of jump does not link and should only be used within a function.

StartLoop: … Test a bit and skip if it is clear Branch to StartLoop

EndLoop:

PIC24 Instructions

Page 60: DSpic

The compare/skip operations include bit test, skip if clear (BTSC) and bit test, skip if set (BTSS). A typical pattern is shown below. For what condition is the ‘Code here’ performed?

BTSC W0, #0 ; Skip next instruction if W0[0] = 0

GOTO Bypass; Code here

Bypass:

PIC24 Instructions

Page 61: DSpic

The program flow operations replace the older style skip and goto. The newer operations include branches, call and return instructions. There are also advanced operations for looping such as DO and REPEAT. The latter are similar to the high level looping operations.

There is also an operation RETFIE which means return from interrupt enable.

PIC24 Instructions

Page 62: DSpic

There are many variations for branch instruction. Some are listed below. The conditions such as GE (greater than or equal to 0) are obtained from the SR. Expr is the branch destination.

Branch unconditionally – BRA Expr Computed branch – BRA Wn Branch if greater than or equal – BRA GE, Expr Branch if greater than – BRA GT, Expr Branch if less than or equal – BRA LE, Expr Branch if less than – BRA LT, Expr Branch if negative – BRA N, Expr Branch if not negative – BRA NN, Expr Branch if zero – BRA Z, Expr Branch if not zero – BRA NZ, Expr

PIC24 Instructions

Page 63: DSpic

Recall that many operations set the SR. Another technique to set the SR is to perform a compare (CP) operation. Some compare instructions are shown below.

CP 0x1200 ; Compare file reg with WREGCP W4, #0x1234 ; Compare W4 with literal

(subtract)

PIC24 Instructions

Page 64: DSpic

The conditional branches are based on the status register (SR). Consider for example the following code where the loop should continue while W0 > 0. During an iteration, register W0 is decremented and this operation sets SR. The correct conditional branch tests that the value of W0 is non-zero.

MOV #10, W0 StartLoop:

DEC W0, W0BRA NZ, StartLoop

EndLoop:

PIC24 Instructions

Page 65: DSpic

The CALL instruction calls a function, its syntax is CALL Expr where Expr evaluates to a program address (typically an identifier in the program memory space).

CALL has some similarity to JAL in MIPS. However, it also differs in that CALL automatically pushes the return address onto the stack. There is no equivalent concept to the $ra register.

PIC24 Instructions

Page 66: DSpic

There are two alternatives to return from a function call, RETURN and RETLW (return with literal in W).

RETURN is used for a void type function. It pops the return address from the stack into the PC. Some sample code is shown below.

CALL _FUNC1…

_FUNC1:…RETURN

PIC24 Instructions

Page 67: DSpic

RETLW is used for a int type function. It writes a literal into a W register and pops the return address from the stack into the PC. An example is shown below that returns the value 10 (decimal) in register W0.

CALL _FUNC2

_FUNC2:

RETLW #0x0A, W0

PIC24 Instructions

Page 68: DSpic

The stack is required for calling functions and possibly for storing local variables. Register W15 points to the stack top (TOS – it is always word aligned). The PIC stack top (and implicitly the bottom) are set to 0x800 when the PIC is reset (ie. W15 = 0x800). Why?

The PIC stack grows upwards. Register W15 points to the first available stack word.

PIC24 Instructions

Page 69: DSpic

To push a word onto the stack requires a move (store) with a post-increment.

To pop a word from the stack requires a move (load) with a pre-decrement.

Pushes and pops can be manually performed as follows.

MOV W2, [W15++] ; A stack push

MOV [--W15], W0 ; A stack pop

PIC24 Instructions

Page 70: DSpic

However, there is no need to manually push and pop as there exists PUSH and POP instructions. These are recommended as they are simpler and will handle byte operations correctly. They also simplify additional extensions as shown below.

PUSH W2 ; Push a register

PUSH 0x1400 ; Push a data memory word

PUSH [W4 + W5]

POP W4

POP [W10++]

PIC24 Instructions

Page 71: DSpic

Based on the default locations for the global variables and the stack, there is a conflict. Both start at address 0x800 and go to higher addresses. How can this conflict be resolved?

On a vaguely related issue, does the PIC have a heap?

PIC24 Instructions

Page 72: DSpic

The globals / stack conflict is resolved by placing the stack at the end of the globals. The following code at the start of a program achieves this goal. It also sets the stack pointer limit register which will cause an exception if the stack overflows.

MOV #__SP_init, W15 ; Initialize the stack pointer

MOV #__SPLIM_init, W0

MOV W0, SPLIM ; Stack pointer limit

NOP

PIC24 Instructions

Page 73: DSpic

PIC24 I/O is performed via the special function registers (SFRs) that are memory mapped into the data space from 0x000 to 0x7FF.

The SFR names and addresses are declared in the include (p24FJ128GA010.inc) file. The #include directive should be uncommented in the source code file to make these declarations available.

PIC24 I/O

Page 74: DSpic

Some of the most basic PIC24 I/O ports are PORTA to PORTG. These are 16 bit ports.

When a port is configured as a binary port (inputs or outputs), each port bit corresponds to a pin on the chip. Thus PORTA corresponds to 16 pins when configured as a binary port.

To configure a binary port, there are related configuration SFRs named TRISA to TRISG (TRIS means TRI STATE).

PIC24 I/O

Page 75: DSpic

Upon reset, binary ports are set into the input state (a 1 setting in every bit - this is the electronically safe setting). To output to a port, its TRIS register must be set to the write state (a 0 in the bit corresponding to the pin).

This is an example of port multiplexing, a port bit (chip pin) can perform multiple operations. In addition, some ports can perform either analog or digital (binary) operations. This requires yet another configuration register to select between analog and digital.

PIC24 I/O

Page 76: DSpic

PORTA is in digital (binary) mode upon chip reset. The following code first initializes PORTA to output mode and then writes a binary pattern to that port. What is the state of the pins corresponding to PORTA? What is a sample application?

CLR.W W0

MOV.W W0, TRISA

MOV.W #0xF0, W0

MOV.W W0, PORTA

PIC24 I/O

Page 77: DSpic

On the Explorer16 demonstration board, the low order 8 bits of PORTA (corresponding to pins RA7 – RA0) are connected to 8 light emitting diodes (LEDs). What is the result of the following code on the LEDs?

MOV.W #0x0C, W0

MOV.W W0, TRISA

MOV.W #0x07, W0

MOV.W W0, PORTA

PIC24 I/O

Page 78: DSpic

If a port such as PORTD remains in the input state, then its pins can be read as follows. What data is placed into W0? What is a sample application?

MOV.W PORTD, W0

PIC24 I/O

Page 79: DSpic

On the Explorer16 demonstration board there are 4 active low push button switches. Two of the switches are connected to pins RD6 and RD7. Their states are given by bits 6 and 7 of PORTD when this port is in a read state. What is the role of the following code?

MOV #0x3F, W0

MOV W0, TRISA

loop:

MOV PORTD, W0

MOV W0, PORTA

BRA loop

PIC24 I/O

Page 80: DSpic

Another important element for control applications are timing intervals. The best solution to this problem is to measure these intervals with a timer that generates an interrupt after its period has elapsed.

This technique involves programming the timer and replacing the default interrupt service routine for that timer.

PIC24 I/O

Page 81: DSpic

The simplest delay technique is implemented with a loop. This delay type is dependent on the speed of the instruction clock. A sample delay function is shown below. This delay technique monopolizes the CPU. Note: Some NOP instructions can be added within the loop to increase the delay.

tmrDelay:

MOV.W #30000, W0

tmrLoop:

SUB.W W0, #1

BRA GE, tmrLoop

RETURN

PIC24 I/O

Page 82: DSpic

A more sophisticated delay technique programs and then polls one of the timers built into the PIC24.

The PIC24 has 5 16-bit timers named TMR1 to TMR5. Each timer has a corresponding control register T1CON to T5CON.

PIC24 I/O

Page 83: DSpic

In a control register, bit 15 is TON (0 = off, 1 = on). Bit 1 (TCS) is the clock source. When TCS is 0, the MCU clock serves as the source so the basic timer frequency is half the oscillator frequency.

There are two prescalar bits (5:4) that reduce the timer counting rate by dividing the basic frequency. The lowest timer frequency (1 / 256) is obtained by setting these bits to 11.

To obtain these settings, the control register is set to 0x8030.

PIC24 I/O

Page 84: DSpic

The following code initializes timer 1 with a frequency that is 1 / 512 of the CPU clock frequency. It also switches the timer on so that it will automatically count in the background.

MOV #0x8030, W0

MOV W0, T1CON

PIC24 I/O

Page 85: DSpic

A sample delay function is given below. The program could also interleave other operations.

delay:

CLR W0

MOV W0, TMR1

MOV #10000, W1

dloop:

; Other operations

MOV TMR1, W0

CP W0, W1

BRA LT, dloop

RETURN

PIC24 I/O