You are on page 1of 45

Date Day Time (hours)

19-02-2018 Monday 13:30-15:30

Lab 1 - Creating an MPLAB X Project


Objective
Lab Exercise 1 shows how to create, edit, and build projects with MPLAB® X IDE. This lab is a
step by step walk through of MPLAB X project development. An MPLAB X project is created
and an existing C source file is then added to the project. The lab continues with the editing of the
source file and the successful build of a project. The lab includes exercises to demonstrate some
useful file and data manipulation features of MPLAB X IDE
Materials
Hardware Tools (Optional)

Software Tools

Exercise Files Download link for windows


https://microchip.app.box.com/s/mi5bkb7x0sc3ru8fvf9ilyynr1ryp8jh
Procedure
1. Project Creation
Open MPLAB X IDE
Close any open projects in MPLAB X IDE by right clicking on the project name and
selecting Close or by going to File and choosing Close All Projects.
2. Start Project Creation
Click the New Project icon to start the project creation process
3. New Project Window
Select “Microchip Embedded” then “Standalone Project”.
4. Processor Selection
Select “16-bit MCUs (PIC24)” from the ‘Family’ pull down menu, then select
“PIC24FJ128GA010” from the ‘Device’ menu.

Click Next.
5. Header Selection
No header is needed; select “None”
6. Hardware Selection
Select “Simulator” under Hardware tools when asked to select a tool.

Click Next.
7. Compiler Selection
Open the XC16 plus box, if not already open, and select an installed version of the XC16
compiler

Click Next.
8. Project Name and Folder Selection
Click the Browse button and navigate to the folder where you want to create and save your
project. Say it is C:\MTT\TLS0101
On the line marked Project Name type in Lab01.
Notice MPLAB® X filling in the Project Folder line with C:\MTT\TLS0101\Lab01.X

Click Finish
9. Move Source Files into the Project Folder

Using a file manager program (such as Windows Explorer) copy the C file ‘Lab01’ from
the folder “C:\MTT\TLS0101\Lab01 Source files” to the newly created folder
“C:\MTT\TLS0101\Lab01.X”

10. Adding Files to the Project


Right click on the Source Files folder in the project window
Select Add Existing Item
Highlight the ‘Lab01’ file in the folder C:\MTT\TLS0101\Lab01.X
Ensure the radio button labeled “Relative” in the lower right border of the dialog box is
checked
Click Select

Project window after source file has been added to a project


11. Open the Editor
Double click on the Lab01.c file to open editor

Scroll down so the main() and delay() functions are visible in the editor window
This a very simple program designed to build confidence in your ability to build a project
and run it in MPLAB® X.
Upon exiting reset, the PIC® clears PORTA, then configures PORTA pins 0:7 as outputs.
It then enters an infinite loop that outputs an alternating pattern to PORTA resulting in the
effect of blinking the eight LEDs connected to PORTA. The delay function between each
toggle of the LEDs is necessary since LEDs require several ms to turn on or off, whereas
the PIC® can toggle in a few hundred ns.
12. Build the Project
Click the Clean and Build Project icon to build the project

Congratulations! You have finished Lab 1


Project Directory Structure
Once a project has been created, a directory structure that resembles the one below, will have been
set up. Two of the project's sub-folders, build and dist will not be created until you build your
project for the first time.

Italicized directory names are the only ones you have any control over with respect to naming. The
structure is fixed and may not be altered without destroying the integrity of the project.
MyProjects
The directory specified as the project location when the project was created. Any directory may
be chosen for the project location, but it is usually best to keep it close to the root directory (e.g.
C:\ on Windows) to keep file paths short.
ProjectName.X
The project directory created by the IDE to contain all of the projects files. The directory's name
is simply the project's name with a ".X" appended. In most cases, this is where all of your source
files and header files will be placed. You may also create subdirectories for them or place them in
directories external to your project.
build
Contains all of the intermediate files (*.o, *.o.d) generated by the compiler and/or assembler that
are used by the linker to create the output files. The intermediate files are sorted by project
configuration and then by debug versus production images.
dist
Contains all of the output files (*.elf, *.hex) generated by the linker. The output files are sorted by
project configuration and then by debug versus production images.
default
This directory (under both build and dist) contains files for the default project configuration. If you
don't create any project configurations, this directory will be named default, otherwise there will
be one or more directories at this level with the names of the project configurations you created.
debug
Contains files generated when the project was built in debug mode.
production
Contains files generated when the project was built in release mode.
nbproject
Contains your project's settings, such as which files are included, which tools are selected, and so
on.
private
Contains project settings unique to your machine.
Modifying Project Properties
Video Tutorial: https://youtu.be/2wgRntFmEjw
Step-By-Step Tutorial
What is the Project Properties window!
The project properties window is a central location from which you may control all aspects of your
project. Some of the things you can do from this window include:
Select/change the device, debug tool, and compiler
Configure the linker, compiler and assembler build options
Configure paths to directories used by your project
Configure debugger and programmer options
Specify scripts to execute before or after a build
How to open the Project Properties window?
The Project Properties Window is a utility to allow you to modify project parameters.
There are three methods you can use to open the project properties window.
Method 1: From the Projects Window
1. Right click on the top node of the project
2. Select Properties from the bottom of the very tall pop-up menu.

Method 2: From the File Menu


From the main menu, select File ▶ Project Properties (ProjectName) where ProjectName is the
name of the project whose properties you want to view.

If you have multiple projects open, you should see one entry in the File menu for each of them.
Method 3: From the Dashboard Window
If the Dashboard window is open:
Click on any file in the Projects Window to select the project.

In the Dashboard window's sidebar, click on the Project Properties icon:


Project Property Categories

General
The general category provides a place for you to include additional source code directories for the
IDE to search when the code is not found in the top level of the project folder.

Conf: [default]
This is the category that will be selected by default every time you open this window. The default
configuration is where you select the microcontroller, debugger/programmer and build tool
(compiler or assembler) for the project. All of the other categories below this one are tied to the
selections you make here (notice that they are all indented one or more levels in the tree structure
of the category list). A project will always have at least one configuration which will be the default.
However, you may create multiple configurations to suit a variety of scenarios for building the
project.
Debugger/Programmer
This category's title will change, along with its contents in the right hand pane depending on
which hardware tool you have selected in the configuration node above. The contents of the
right hand pane will vary greatly depending on which hardware tool you have selected (such as
MPLAB ICE3, REAL ICE, or PICkit 3) or simulator. As a general rule, things like memory
ranges to program, voltages, clock sources and speeds, and a variety of other debug options may
be controlled from this category.
Settings for specific tools
MPLAB® REAL ICE™ in-circuit emulator
MPLAB ICD 3 in-circuit debugger
PICkit™ 3 in-circuit debugger
MPLAB X Simulator

MPLAB X Simulator: The MPLAB® X IDE includes a powerful discrete-event simulator for:
PIC® Microcontroller (MCU) Families
dsPIC® Digital Signal Controller (DSC) Families
The simulator is integrated into MPLAB X IDE (integrated development environment). The
simulator debugging tool is designed to model the operation of Microchip Technology's MCU
and DSC devices to assist in debugging software for these devices.
Features
MPLAB X Simulator allows you to:
 Modify object code and immediately re-execute it
 Inject external stimuli to the simulated processor - stimulus is the simulation of hardware
signals
 Set pin and register values at pre-specified intervals
 Trace the execution of the object code
 Code coverage to detect “dead” code areas
 Extract data for validation

Building/Loading
This category is used to select macros or scripts to execute before and/or after building the
project. Most of the time, this won't be used. But when you need to add a little extra functionality
such as copying or moving some files around before or after the process, this feature helps to
automate the entire procedure.
Compiler Suite Global Options
The compiler suite's global options contain settings that apply to the entire compiler toolchain
and will affect the entire build process as a whole.

Assembler Settings
Assembler settings provide full control over how the assembler builds your code, references
files, and what information it should provide as its output.
Compiler Settings
The compiler settings provide full control over how the compiler builds your code, optimizies
your code, and which memory model it uses.

Linker Settings
The linker settings control the overall build process, locates and integrates library code and
specifies which diagnostic outputs are desired.
Debugging with MPLAB® X IDE
There are several Essential Elements of Debugging
 Starting a debug session
 Controlling program execution
 Observing Special Function Registers (SFRs)
 Observing or modifying memory content
 Modifying SFRs or memory content
 Ending a debug session
In the next few pages of this tutorial shows how to perform each of these steps.
Preparing to Debug a Project
Debug Startup Options
1. Open the Project Properties Window
MPLABX's debug startup option is configured in the Options Window
To open the Options Window PC and Linux user's will need to select Tools>Options
from the toolbar

Macintosh users can open the Options Window by selecting mplab_ide -> Preferences
from the toolbar
2. Select the Debug Options
When the options window opens the following needs to be done
A. Select the Embedded Icon (shown here highlighted in Blue)
B. Select "Generic Settings"
C. Select from the Pull Down menu on the row title "Reset @" the desired Debug Start
up Option
i. to pause at RESET
ii. to pause at beginning of main (shown below)
iii. to run
D. Select "OK"

Debug Tool Selection


The user has the responsibility of informing MPLAB® X IDE which debug tools to use for a
particular project. Upon installation MPLAB X IDE provides the ability to debug using either the
MPLAB X software simulator or one of Microchip Programmer/Debuggers. Currently Microchip
offers three programmers/debuggers: PICKit™ 3, MPLAB ICD 3, and the MPLAB REAL ICE.
Each of these programmer/debuggers offers different levels of performance and features.
Selecting a debug tools is done on a project by project basis. The project to be debugged must be
opened before the debug tool can be selected.
Select the Debug Tool to use
In the hardware section of the project properties window select one of the available hardware tools
are the programmer/debugger. You are allowed to select the Microchip Supplied HW tools such
as the ICD3, PICKit3, REALIce, or StarterKit. While they are not technically hardware tools the
Microchip Software simulator and Lab Center's Proteus VSM software simulator are available to
use as debuggers.
MPLABX will search the system for available development tools. If a programmer/debugger is
found the Hardware tools box will populate with the serial number of the attached device.

Confirm the Selection


After you have selected the Hardware tool to use select "Apply" then "OK".

Running A Debug Session


After ensuring the desired debug startup option has been set and ensuring the appropriate

programmer/debugger has been chosen, a Debug Session can be started by clicking on the
Debug Project Icon.
Four things will happen when a debug session has been initiated:
1. The project will build
2. MPLAB® X IDE will connect to the selected debug tool and download the built image
3. The Debug Icons will appear on the Toolbar
4. The application in the PIC® MCU will run according to the debug startup option
An illustration of MPLAB X IDE's user interface immediately after a debug session has been
started. This example shows the operation when the Debug Startup option is set to MAIN.
Debug Icons

When a debug session has been started a new toolbar will appear.
The Debug icon toolbar contains 9 buttons which allow for program control and ease of debugging.
Looking at Global Variables and SFRs
Global Variables (variable with fixed addresses and scope) can most easily be view by the Watches
Window. When the Watches Window is opened the user can add a list of variables to "watch".
Each time the debug session pauses the program the value of the items being watched is updated.
PIC Special Function Registers SFRs work just like Static variables and can be added to any
Watches Window
To open the Watches window select Window->Debugging->Watches from the toolbar. The
Watches window will appear as a tab in the lower right hand corner ( the Output Window). Right
clicking anywhere in the Watches window will allow you to add or delete Watches.
For more information: http://microchipdeveloper.com/mplabx:watches-window
Observing Local Variables
Local Variables (variables who exist only on the stack) can be view by the Variables Window.
When the Variables Window is opened the variables who are 'local' to the active function are
displayed. The user has the choice of selecting all local variables or just those 'near' the program
counter.
To open the Variblees window select Window->Debugging->Variables from the toolbar. Just like
the Watches window the Variables Window will appear as a tab in the lower right hand corner (the
Output Window). The three icons on the left hand side of the Variables window allow you to
modify the range of the local variables displayed or to add Watches to the Variables window.
For more information: http://microchipdeveloper.com/mplabx:settingvariableswindow
Finishing the Debug Session
When the debugging has been complete and you wish to create an image which can run in the PIC
MCU without the need of a programmer/debugger two step are needed. The first step is to end the
debug session. Once the debug session has been ended you will need to create the production ready
image.
To end the debug session click on the "Finish Debug Session" icon
---------------------------------------------
Lab 2: Using the Simulator
Objective
Lab 2 picks up where Lab 1 ends. Now that we can create a project, enter code, and build the
project, we need to verify the code works before we run it on hardware. To verify the code, we
will use the MPLAB® X simulator. This lab reviews how to build a debug version of a project and
send it to the MPLAB® X simulator. Once the simulation session has started, this lab reviews how
to control the program execution. This lab provides the basics of observing the program to ensure
the correct lines of code are executed. This lab also reviews how to monitor and control program
variables and the PIC® Special Function Registers (SFRs)
Procedure
1. Open Lab02 Project
Close any previously opened projects by right clicking on the project name and
selecting Close
Click the Open Project icon
Browse to C:\MTT\TLS0101\Lab02.X and select Open Project
Double click on Lab02.c under Source Files to open the C file in the editor window
Lab2.c toggles eight I/O pins which are connected to LEDs. Observe the variable
definitions of ctr and delayVal. The variable ctr is incremented each time the main
loop executes. The variable delayVal is used to control the amount of time in the delay
routine. Altering delayVal affects the amount of time consumed by the delay function.
These two variables are used during the debugging session.
2. Select Simulator as the Hardware Tool
Select Lab02 from the project list
Right click
Select “Properties”
Click Conf:[default]
Under “Hardware Tools”, verify that Simulator is selected
Click OK

3. Setting the Simulator to start at the beginning of main() function


From the “Tools” pull down menu select “Options”
Select the Embedded icon
Select the “Generic Settings” tab
Ensure the “Debug startup” is set to ‘Halt at Main’
Click OK

4. Starting the Debug Session


Build a debug version of the open project by clicking on the Debug Project icon
You will notice that clicking the “Debug Project” icon will build the project,
download it to the simulator, start the simulator session, and run until the program
enters the main()function.
Observe the green code highlight on the first line within main(); The simulation has
started but stopped at this place in the code. The green line indicates the current
position of the PC during a debug session.
Notice the addition of the Debug Toolbar

5. Step Into
Click “Step Into” icon to execute one line of source code. Notice the PC
increment as the green line goes to the next line in code.

We could continue to step through the program one line at a time to get to a place
of interest but this may be time consuming.
Place the cursor on the line of code containing the instruction LATA=0x55;
Right click and select Run to Cursor
Place the cursor over the LATA to observe the that the value of LATA is all zero

Click Step Into to load 0x55 into LATA


Place the cursor over LATA and observe the new value

6. Breakpoints
To set a breakpoint, click the mouse on the number in the left column of the source window
corresponding to the code LATA = 0xAA; The red line indicates a break point has been set
and the simulation will stop on this line of code.

Click the Continue icon and notice the simulation stop at the breakpoint.

7. Step Over
Click “Step Into” once so the PC is pointing to the call to the function delay()

We would like to execute the delay() function and halt on the line containing ctr++;. We
do not wish to step through delay() instruction by instruction. We also do not wish to set a
breakpoint in the main code after the call to delay().
To execute a function and stop the program after the function has executed select the Step
Over icon
Notice the simulation completes the delay() function then pauses when it returns

Set a breakpoint each of the lines of code containing the LATA assignment statements

Click the Continue icon several times, noticing the simulation progress through the
breakpoints
Verifying the accuracy of the data
The program executes the code in the expected order, but does the program do the correct
thing? In order to determine if the code is making the correct decisions we have to observe
what information the PIC® MCU sees and the data it outputs. To do this we will set up
a Watch Window to observe program variables and some of the PIC® MCU Special
Function Registers (SFRs).
8. Setting up the Watches Window
From the Window menu select Debugging ,then Watches

MPLAB® X IDE will display the Watch Window


9. Adding an Item to the Watches Window
Right click in the Watches Window and select New Watch
Highlight the radio button “SFR’s”
Select LATA from the scrolling menu of Special Function Registers (SFR) on the
PIC24FJ128GA010.
Click OK

Repeat steps above to add the variable ‘ctr’ from the list of “Global Symbols”
Click the Continue icon several times to observe the changes in the value
of LATAand ctr. LATA should change after each click of Continue. The variable ctr
should change every other time Continue is clicked.
Click the Reset icon to reset the processor
Observe that the Watches Window entries revert to 0 and the program counter is set to the
beginning of main();
Remove all break points from the source code by clicking once on each pink breakpoint
box in the margins of the source code.
10. Running the Simulation
Click the Continue icon to start the simulation. Wait 5 to 10 seconds, then click
the Pause icon.

Observe how the variable ctr has been incrementing during this simulation.
11. Ending the Debug Session
Congratulations! You have finished Lab 2 and learned how to build a debug version for the
simulator, set breakpoints, add SFRs and variables to the Watches Window and control
program flow.
The last remaining item in this lab is to inform MPLAB® X IDE to end the debug session. To
accomplish this task click the Finish Debugger Session icon
--------------------------------------------------
Lab 3: Debugging on Hardware
Skipped
Lab 4: Navigating Projects
Objective
In this lab you will work with a project containing four pre-written C source files. From the main()
function you will be provided techniques on how to navigate between the files, how to locate the
source code for a given function, how to easily find a variable’s definition, and how to determine
the overall flow of a project. The lab concludes with a debugging tip which allows you to determine
the sequence of function calls invoked when a break point is reached.
Procedure
1. Open Lab04
Close any open project by right clicking on the project name and selecting “Close”
Click the Open Project icon
Browse to and open the project C:\MTT\TLS0101\Lab04.X
2. Resetting MPLAB® X IDE Windows
To help make the procedures in this page more closely resemble your experience we
will close all existing source code and place the window locations to their default
location. The easiest way to do this is to Reset the Windows
Windows -> Reset Windows
MPLAB X IDE will disappear for a second or two. When it returns you should notice
changes to the graphical user interface setup

Clean and build the project


3. Open the Dashboard
The dashboard gives you an overview of the project features and settings. From this
window you will be able to verify the processor being used, the
simulation/programming tool, and the version of the compiler.
To open the dashboard click the mouse on top of the bar labeled Lab04 – Dashboard
Quite often as you start projects you will need to refer to the datasheet for the particular
device being programmed. For a user connected to the internet, the Dashboard screen
allows you to access and download the datasheet for the device being used.
Click on the “PDF” image in the left margin of the Dashboard window. When prompted
select “HTML Browser Download from Microchip Website”
If you are connected to the internet you can observe your computer browser retrieve
the datasheet for the PIC24FJ128GA010 family from www.microchip.com

Close the browser


4. Navigation Window
Next, open the Source Files folder from the Projects Window

Highlight Lab04.c. The Navigation Window populates with the elements found in
Lab04.c
From the Navigation Window double click on main()
You should observe the source code for Lab04.c open up and the “blue” bar go to the
line of code corresponding to the item selected from the Navigation window
The program is an infinite loop in which data is input, modified, and output. After each
output the main loop executes a delay function.
You may notice that the getInput(), the delay(), and the outputData() functions are all
located in separate source files.
5. Call Graph
Highlight the main() function in the source window.
Right click and select Show Call Graph

Once the Call Graph opens observe the graphic representation of the functions called
by main()
From this view you should be able to get some idea of how the project calls are linked.
On the left hand side of the Call Graph window you should see a hierarchy of the calls.
Open the graphics to the delay() function by clicking on the plus box (+) next to delay

You will notice the visual call graph change after the delay() function has been expanded.
Open both the getInput(), and outputData() functions from the hierarchy window and
notice the changes to the call graph.

6. Rearranging the Call Graph

Practice moving the objects in the Graph Window to match the graphic to the left. This
graph illustrates how the function smallDelay() is called from three separate functions.
7. Navigating between Files and Functions
From the Call Graph Window double click on the box “main”. This will open up the source
code file containing main() in Lab04.c
Observe the blue line over the function header for main()

While holding the Control Key (CTRL) down place the mouse over the call
to getInput() in Lab04.c
Observe that a Hyperlink appears as well as a description of the object being highlighted.
With the CTRL button held, place the cursor over the call to getInput(); and left click the
mouse.

To return to the calling function select the “Go Back to..” button located near the upper
left hand corner of the editor dialog box.
Using the hyperlink navigate icon (CTRL+ click) and the “Return” icon navigate
to delay(), outputData(), and calculate().
After a brief inspection it should become apparent the function “smallDelay()” is called
from three separate functions.
8. Debugging a "Nested Function"

Click on the line number to place a breakpoint on the line of code incrementing
the smallDelayVarin delays.c

Build a debug version of the project by selecting the Debug Project icon.
The project will build and a debug session will start
The simulation will pause at the beginning of main()
We are now ready to simulate.
Click the Continue icon and watch the program proceed to the breakpoint
in smallDelay().
You will see the code window stop with a green line over the line of code with the
breakpoint.
You will also see a comment in the debug console window letting you know where the
simulation halted. In this case the code stopped at line 5 in delays.c.

9. Call Stack

To determine who called a function we will introduce the Call Stack.


Open the call stack by:
Windows->Debugging->Call Stack

When the call stack is first opened the contents may not be updated.
To update the call stack window press the Continue icon.
The simulation has proceeded to the second instance of the break in smallDelay().
Observe the output of the call window
Each time a breakpoint is reached the call stack will let you know the active ‘thread’ of
function calls. You will observe the function and line of code being executed. At any
breakpoint you can see the ‘trail’ of function executions leading to the breakpoint
Click the Continue icon several more times and you will observe a pattern of the calls
into smallDelay().
By looking at the output of the Call Stack window you should be able to see the code cycle
through getInput(), outputData(), and delay();

10. Moving the Variables Window

To see what the calling functions see, we will open up the Variables window to show us
the local variable
Select: Window->Debugging->Variables
For this example we wish to move the Variables window out of the MPLAB® X frame and
onto our desktop. While this example shows how to move the Variable Window any
MPLAB® X window can be moved in this manner.

Grab the Variables Window by putting the mouse over the title bar and holding down the
left mouse button. While keeping the left mouse button down drag the window completely
away from MPLAB®X IDE. Deposit it onto your desktop by releasing the left mouse
button.
Reset the simulation by clicking the Reset icon.
Ensure the Call Stack window is open
Place the Variable Window where it can be seen
Click the Continue icon

The simulation will stop at the breakpoint within smallDelay(); The Variable window
should display the smallDelayVar variable. The call stack will show the functions which
called smallDelay().
Note: If the variables don’t appear in the Variables window toggle the upper left side button
inside the Variables window.

From within the Call Stack Window double click on the line
indicating getInput() called smallDelay()
Observe the Variables window change to display the local variable within
the getInput() function. The source window will also show the calling function with a grey
bar over the line of code calling the subroutine.
Click Continue and inspect the status of the calling function local variables by
clicking on the function that called smallDelay() to see the Variables window populate.
To put the Variables Window back into MPLAB X IDE grab the title of the Variables
Window (NOT the large banner but the word “Variables”). While holding the left mouse
button drag the window back into MPLAB X IDE. Before letting go of the left mouse
button be sure you position the Variables Window where you want it to re-appear when it
is opened. MPLAB X IDE will let you know where you are positioning a Window by
display an orange outline.
HINT: Use the Window->Reset from step 2 of this lab if you experience trouble resetting
the Window location manually
End the debug session
---------------------------------------
For C-Language Program
Pragmatic:
#pragma config FWDTEN = OFF, JTAGEN = OFF
Pragma: In computer programming, a directive or pragma (from "pragmatic") is a language
construct that specifies how a compiler (or other translator) should process its input. Directives are
not part of the grammar of a programming language, and may vary from compiler to compiler.
They can be processed by a preprocessor to specify compiler behavior, or function as a form of in-
band parameterization.
In some cases, directives specify global behavior, while in other cases they only affect a local
section, such as a block of programming code. In some cases, such as some C programs, directives
are optional compiler hints, and may be ignored, but normally they are prescriptive, and must be
followed. However, a directive does not perform any action in the language itself, but rather only
a change in the behavior of the compiler.
Another C construct, the #pragma directive, is used to instruct the compiler to use pragmatic or
implementation-dependent features.
Watchdog Timer
The primary function of the Watchdog Timer (WDT) is to reset the microcontroller, in the event
of a software malfunction, by resetting the device if it has not been cleared in software. It can also
be used to wake the device from Sleep or Idle mode.
The WDT is enabled or disabled by the FWDTEN (CW1<7>) Configuration bit. When the
FWDTEN Configuration bit is set, the WDT is enabled.
Joint Test Action Group (JTAG) is the common name used for a debugging, programming, and
testing interface typically found on microcontrollers, ASICs, and FPGAs. It enables all
components with this interface to be tested, programmed, and/or debugged using a single
connector on a PC board which can daisy chain them together.
I/O PORT CONTROL REGISTERS
All I/O ports have four registers directly associated with the operation of the port, where ëxí is a
letter that denotes the particular I/O port:
1. TRISx: PORTx Data Direction Control register
2. PORTx: I/O Port register
3. LATx: PORTx Data Latch register
4. ODCx: PORTx Open-Drain Control register
Each I/O pin on the device has an associated bit in the TRIS, PORT, LAT and ODC registers

In PIC24F family there are two sets of 16 I/O ports, RA0 through RA15 and the RB0 through
RB15. These are our two main PORT registers. They are called PORTA and PORTB and you will
deal with them all the time. Before you start playing with the port pins, you should declare their
type. Each one can be Input or Output. There is also an analog state, but this will be discussed on
the advanced section. On power on of the PIC or after a reset, all ports become inputs. This is done
to avoid driving an output pin directly to the VDD or VSS.
Setting the type of the port pins (Input or Output): TRIS Registers
To define the type of an I/O pin, you use the TRIS register. There are two TRIS registers, the
TRISA and the TRISB that corresponds to the 16 pins of each port set, the A and the B. The TRIS
registers are 16-bit registers. The LSB (Less significant bit) corresponds to pin #0 and the MSB
(Most significant bit) to the pin #7. When one bit of this register is set to '1', the corresponding
port pin shall become an input. When it is set to '0', then this port pin shall become an output.
PORT Registers
Data on an I/O pin is accessed via a PORTx register. A read of the PORTx register reads the value
of the I/O pin, while a write to the PORTx register writes the value to the port data latch. This will
also be reflected on the PORTx pins if the TRISx is configured as an output and the multiplexed
peripherals (if any) are disabled.
Many instructions, such as BSET and BCLR, are read-modify-write operations. Therefore, a write
to a port implies that the port pins are read, the value is modified and then written back to the port
data latch. Care should be taken when read-modify-write instructions are used on the PORTx
registers when some I/O pins associated with the port are configured as inputs. If an I/O pin
configured as an input is changed to an output, at some later time, an unexpected value may be
output on the I/O pin. To avoid this, first write to the associated PORTx bit and then change the
direction of the pin as an output.
In addition, if read-modify-write instructions are used on the PORTx registers while I/O pins are
configured as outputs, unintended I/O behavior may occur based on the device speed and I/O
capacitive loading. Figure 12-2 illustrates unintended behavior that occurs if the user application
attempts to set I/O bits, 0 and 1, on PORTA, with two consecutive read-modify-write instructions
in the PORTA register. At high CPU speeds and high capacitive loading on the I/O pins, the
unintended result of the example code is that only I/O bit 1 is set high.
LAT Registers
The LATx register associated with an I/O pin eliminates the problems that could occur with read-
modify-write instructions. A read of the LATx register returns the values held in the port output
latches instead of the values on the I/O pins. A read-modify-write operation on the LATx register,
associated with an I/O port, avoids the possibility of writing the input pin values into the port
latches. A write to the LATx register has the same effect as a write to the PORTx register.
The differences between the PORTx and LATx registers can be summarized as follows:
1. A write to the PORTx register writes the data value to the port latch.
2. A write to the LATx register writes the data value to the port latch.
3. A read of the PORTx register reads the data value on the I/O pin.
4. A read of the LATx register reads the data value held in the port latch.
Any bit and its associated data and control registers that are not valid for a particular device will
be disabled. That means the corresponding LATx and TRISx registers, and the port pin, will read
as zeros.
ODC Registers
Each I/O pin can be individually configured for either normal digital output or open-drain output.
This is controlled by the PORTx Open-Drain Control register, ODCx, associated with each I/O
pin. If the ODC bit for an I/O pin is ë1í, then the pin acts as an open-drain output. If the ODC bit
for an I/O pin is ë0í, then the pin is configured for a normal digital output (ODC bit is valid only
for output pins). After a Reset, the status of all the bits of the ODCx register is set to ‘0’. The open-
drain feature allows a load to be connected to a voltage higher/lower than VDD on any desired
digital only pins by using external pull-up resistors. The maximum open-drain voltage allowed is
the same as the maximum VIH specification and the minimum is VSS. The ODCx register setting
takes effect in all the I/O modes, allowing the output to behave as an open-drain even if a peripheral
is controlling the pin. Although the user could achieve the same effect by manipulating the
corresponding LAT and TRIS bits, this procedure will not allow the peripheral to operate in Open-
Drain mode (except for the default operation of the I2Cô pins). Since I2C pins are already open-
drain pins, the ODCx settings do not affect the I2C pins. Also, the ODCx settings do not affect the
JTAG output characteristics as the JTAG scan cells are inserted between the ODCx logic and the
I/O.
----------------------------
For Assembly Language Program
Create project
Add files:
header file: p18f45k20.inc
path: microchip\mplabx\mpasmx
linker file: 18f45k20_g.lkr
path: microchip\mplabx\mpasmx\lkr
source file: add new file with .asm extension and write down the following assembly language
code:

You might also like