Sie sind auf Seite 1von 30

See discussions, stats, and author profiles for this publication at: https://www.researchgate.

net/publication/321254378

MPLAB Programming

Chapter · November 2017

CITATIONS READS
0 4,666

1 author:

Rajeevan Arunthavanathan
Memorial University of Newfoundland
10 PUBLICATIONS   1 CITATION   

SEE PROFILE

Some of the authors of this publication are also working on these related projects:

Hand Gesture Communication System View project

A fault diagnosis and prognosis approach for process system based on hybrid model. View project

All content following this page was uploaded by Rajeevan Arunthavanathan on 23 November 2017.

The user has requested enhancement of the downloaded file.


PIC PRINCIPLES AND APPLICATIONS OF
MICROCONTROLLER MICROCONTROLLERS

Practical Approach | Rajeevan.A


Introduction
This book contains information about the practical work of the microcontroller module.

Work book start by looking at how to use the MPLAB development IDE. This is a very well
designed IDE that can use to develop both assembly language and C programs for the PIC.

The MPLAB IDE will have been set up so that it can use the Hi-Tech C Lite compiler. This is a
very good compiler that produces good tight machine code from a C program.

This work book also looking at a Mickro C program, this will help to the students to write a
complicated controller program using in a simple way in Micro C program.

Finally student will find details on how to develop and test a PIC assembly language program
using MPLAB, and also how to use the PPP PIC programmer (which is available in the EE
laboratory) to download the machine .HEX file produced by the assembler to PIC
Microcontroller.

Later student will learn how to used MPLAB/Mikro C to develop C programs and download
them to PIC Micro board and test it using development board or implemented circuit board

Please note: Student can only have one PIC in one of the DIL sockets at one time; having
more than one PIC installed in the PIC micro board could damage the board.

Enjoy and Happy Programming!

Rajeevan.A

Faculty of Engineering

Sri Lanka Institute of Information Technology


MPLAB Introduction
MPLAB is the package that has been designed specifically for the development of software for
the PIC series of microcontrollers. It is an excellent package, easy to use, incorporating editor,
assembler, and simulator and programming software. Thus all the tools are available to wire
assembly language programs, assembly programs into machine code, test the resulting code with
the simulator and program a PIC microcontroller. The only additional hardware required is a PIC
programmer, which plug in to the serial/USB port to the PC.

The simplicity and low cost of the development system (MPLAB is freely available in
www.microchip.com) and PIC series of microcontrollers themselves has made this series of
microcontrollers extremely attractive to industry and has also opened this area of electronic
control to the enthusiast and hobbyist.
Getting start with MPLAB
The following text and figures illustrate the procedures required to edit, assemble, simulate and
program a PIC device with the MPLAB environment.

1. Open MPLAB software

2. Go to the project and choose project wizard, 3. Select the device,


4. Select Microchip MPASM Toolsuite. 5. Create a new project,
If there’s a red X showing anywhere, MPLAB
needs to know where the tools are, namely
C:\Program Files\Microchip\MPASM Suite.

6. Next, Project Wizard offers to add some 7. Give final approval, and your project will be
files to the project. In this time skip this created:
window and use much better user interface to
add files at the next step. So just click next at
this screen:

Target PIC Microcontroller

File location
8. Now empty project is created with no files in it. To create or add an .ASM file,
As a first step, adding a linker script to your project is strongly
recommended. This tells the MPASM suite to use a more modern method
of generating .HEX file which will get around an old 62- character limit on
path lengths.

To add Link scripts, Right-


click on Linker Scripts,
navigates to
C:\Program
Files\Microchip\MPASM
Suite\LKR, and picks the file
that matches your processor.
Check “System” so MPLAB
will know you want to use the
“canned” linker script without
editing it.

9. Now create or add an .ASM file.

Right-click on Source Files, navigates to your .ASM file, and add it. Or choose File, New, type
in at least part of the file, save it, and then add it. When it complete project will look like:

Now you have a working


environment with an editor for your
file, and the file is shown in the
contents of the project. To open
your .asm file if it’s not already
open in the editor, just double-click
on it.
Practical Session 1: MPLAB Program introduction
In this session student will get the basic knowledge of the software (MPLAB) and the software
programe.

Program in the MPLAB environment are assembled and simulated as projects, but before a
project can be constructed the program must first be written using the MPLAB text editor. To
invoke the text editor go to the file menu and select New source. The editor screen should
appear. Type in the following program,

Sample Program:
; First program using MPLAB to add two numbers and store the result
; The first value is stored in file register (RAM) 0x0C
; The second value is stored in file register (RAM) 0x0D
; The results is stored in file register (RAM) 0x0E
;
; -------------- Program Equates ----------------------------------
;
value1 equ 0x0C
value2 equ 0x0D
result equ 0x0E
W equ 0
F equ 1
;
; ------------- Main Program ---------------------------------------
;
org 0x00
start movlw .5 ; Move 5(dec) into w
movwf value1 ; Store in value1
movlw .3 ; Move 3(dec) into w
movwf value2 ; Store in value2
;
movf value2,w ; Move value2 to w
addwf value1,w ; Move value1 to w
movwf result ; Store result
;
;
clrf value1 ; Clear value registers
clrf value2

clrf result
;
goto start
;
end

Task
 Save the program as My_first.asm
 Add the .asm file in to source file
 Simulate the program using MPLAB SIM
 View the file registers value1 value2 and result while running the program.
Assembling the program into machine code

To assemble the program into machine code go to the project menu and select ‘Make Project’.

MPLAB will be attempt to assemble My_first.asm into machine code. Any errors incurred
during assembly will be indicate which means going back into the text editor and correcting the
errors before attempting to assemble the program again. The program must obviously be
reassembled after every change made.

When the program assembles correctly – ‘Success no Errors’ will be displayed.

Simulation
Simulation is a very important aspect of software development and should be carried out every
time a program is written or edited to ensure correct operation, before programming a device.
To simulate the program using MPLAB, first of all open My_first.asm if it is not open.
Open the file register window by clicking on relevant hotkey or from the View. This allows
changes of the W register, I/O ports and all other registers to be observed as the program is
single stepped.
Randomize all file (RAM) locations prior to simulation so that changes can be observed as the
program is single stepped.
From debug menu select MPLAB SIM, this will activate the simulator by MPLAB software.
Run the simulation by using ‘Animate’ hot key. File registers used in the program should be
observed changing value (turning red) as the program is single stepped.
Try to follow and understand the changes observed as the program is single stepped.
Practical Session 2: Simulation of Output
In this session student will learn how to configure and simulate outputs that would normally be
available at the I/O pins of PIC device.
To configure the Input and Output of the microcontroller following steps need to be done using
special purpose registers.
Step1: Need to switch from Bank 0 to Bank 1 to access the TRIS register. To do this set the
STATUS register, which is at address 03h (or can be written as 0x03 to represent the HEX
values.), bit 5. (Refer 16F datasheet)
BSF 03h, 5 (BSF – Bit Set File register)

These instructions using two operands, which are the STATUS register address 03h, and the
literal number 5 which correspond to the bit number. Therefor once the instruction executes
STATUS register bit 5 will be set to 1 and bank 1 will be activated.
Note: To set the corresponding bit value to 0, BCF (Bit Clear File register) instruction will be
used.
Step 2: Need to configure the corresponding port as an input or output.
TRIS register is used to configure the corresponding port as an input or
output.
If TRS bit set to 1, appropriate port will be configured as an input.
If TRS bit set to 0, appropriate port will be configured as an output.
Example: if PORT A pin number 0 and 4 needs to be an input and rest of the pins are output
following code will be generated to complete the operation.
MOVLW b’10001 ; move binary value 10001 to W register

MOVWF 85h ; move W register value in to the file register 85h (TRISA)

PORT A pin RA4 RA3 RA2 RA1 RA0


Binary 1 0 0 0 1
Input/Output In Out Out Out In

Now port is ready to use as an input/output.


Step 3: read or write the port with appropriate data.

Follow the following program and write it and simulate using MPLAB, this will give a better
understand about port configuration.
Program:
; ----------------------------------------------------------------------
; A simple program to illuminate the LED
; LED which is connected to RA3 need to be illuminate
; ----------------------------------------------------------------------
;
; -------------------- Select the project target -----------------------
;
list p=16f88
;
; -------------------- Program Equates ---------------------------------
;
status equ 0x03
trisa equ 0x85
porta equ 0x05
W equ 0
f equ 1
;
;
; --------------------- Main Program -----------------------------------
;
org 0x00
;
start bsf status,5 ; Select Bank1
movlw 0x00 ; Set PortA to all outputs
movwf trisa
bcf status,5 ; Select Bank0
;
;
movlw 0x00 ; Turn off all LEDs
movwf porta
;
;
bsf porta,3 ; Turn on LED 3
;
stop goto stop ; Stop
end

Task 1: Assemble the program into machine code and simulate the program and analyze the
PORTA register.

Task 2: Rewrite the program to turn ON and OFF the led, and switch should connected with pin
RA0. Test the program using stimulus file (fire high and low to RA0 whenever required.)

Task 3: Design the hardware circuit using single LED and a switch (LED should connect to pin
RA3 and switch should connected to pin RA0).
Answer
Task 2 Program
; ----------------------------------------------------------------------
; A simple program to illuminate the LED
; LED which is connected to RA3 need to be illuminate
; pin RA0 configur as an input.
; RA0 will be turn ON/OFF the LED
; ----------------------------------------------------------------------
;
; -------------------- Select the project target -----------------------
;
list p=16f88
;
; -------------------- Program Equates ---------------------------------
;
status equ 0x03
trisa equ 0x85
porta equ 0x05
ansel equ 0x9B
W equ 0
f equ 1
;
; --------------------- Main Program -----------------------------------
;
org 0x00
;
Start bsf status,5 ; Select Bank1
movlw 0x01 ; Set RA0 pin as an input and all other as output
movwf trisa
clrf ansel ; set all portA as digital ports
bcf status,5 ; Select Bank0
;
;
test btfss porta,0 ; check if switch ON
goto test
bsf porta,3 ; Turn on LED
test2 btfsc porta,0 ; check if switch OFF
goto test2
bcf porta,3 ; turn off LED
;
goto test ; check the seitch again
end

btfss – bit test file register and skip the next instruction if bit is set.
btfsc – bit test file register and skip the next instruction if bit is clear.
Practical Session 3: Flashing LED using delay loops
In this session student will learn how to create the time delay using counters/general purpose
registers. Counter delay will be created using crystal oscillator and the principles behind the
delay loop will be explain using instruction execution time.
Instruction execution time

According to PIC microcontroller datasheet almost all the instructions are executed in one
instruction cycle (which is include fetch decode and execution). One instruction cycle takes
exactly four clock cycles.

At a clock frequency of 4 MHz, one Instruction cycle takes 4 x 250ns = 1us. Therefore at 4 MHz
clock most instructions execute in 1us.

The only instructions which take two instruction cycles are instructions which modify the value
of the program counter. For an example, GOTO instruction, however instruction like DECFSZ
(or DECFSS) can take either one or two instructions. When the outcome of the decrement is not
equal to zero, the next instruction is executed and the instruction takes only one instruction cycle.
When the result is zero the program counter will be modify and the next instruction will be
skipped, therefore instruction takes two instruction cycles.

Create a counter clock using delay loops

The principle of the delay is that count down a general purpose register from a previously set
number, and when it reaches zero, its stop counting. The zero value indicates the end of the
delay, and program will continue.
Following steps will be needed to create a delay loop,
Step 1 Need to define a constant to use as our counter / address a general purpose register to use
as a counter.
count equ 0x2F ; create a counter variable
Step 2 Set an initial/preset value to define counter however maximum value can be 255 if the
register is 8bit (28)
movlw 0xff ; move 255 value to w register
movwf counter ; move w register value to counter file register
Step 3 Decrease the counter by 1 until its reach zero.
decfsz counter,1 ; decrement the file register (counter) until it get zero.

decfsz - Decrement the file register by the number that follows the
comma. If reach zero, skip the next instruction.
Samples program for a create a different clock
Reminder: The mid - range microcontroller registers are contain only 8 bit registers, there for
limiting delays are only implemented using one register, the maximum delay routine that can
make from single bit is, less than 750us.
All instruction (except loops) takes 1 instruction cycle
The skip instructions take 1 clock cycle unless they skip – 2 instruction cycles
The GOTO instruction takes 2 instruction cycles.

Following sample program written as a subroutine to create a specific delays.


500us delay
Delay_500us
movlw .166 ; 1 cycle
movwf Loop_500us ; 1 cycle
Loop decfsz Loop_500us,1 ; (165x1) + 2
goto Loop ; 165x2
retuen

Total cycle for this loop,


1+1+(165x1)+1+2+(165x2) = 499 cycles
However if 4 MHz clock used, each instruction cycle will be taken 1us therefore above
subroutine will create 499us delay.

Generally this method will be used to create small delays. Still sec/hour delays can be crated
using this method with loop in to loop method. However to generate a high delays timer can be
used or MikroC/HighTechC program will be used.
Sample Program
; ---------------------------------------------------------------------------
; A simple program to illuminate and LED connected to RA3 of PORTA
; The LEDs are connected to PORTB
; change the program to flash the LED within 70us
; ---------------------------------------------------------------------------
;
;
list p=16f88
;
; -------------------- Program Equates --------------------------------------
;
status equ 0x03
trisa equ 0x85
porta equ 0x05
del_500 equ 0x2c
W equ 0
f equ 1
;
;
; --------------------- Main Program ---------------------------------------
;
org 0x00
start bsf status,5 ; Select Bank1
movlw 0x00 ; Set PortA to all outputs
movwf trisa
bcf status,5 ; Select Bank0
;
;
Movlw 0x00 ; Turn off all LEDs
movwf porta
;
;
;
bsf porta,3 ; Turn on LED 3
call delay_500 ; call 70us delay
bcf porta,3 ; Turn off LED 3
goto start ; goto start and continue
;
;
; ---------------------- Delay loop -----------------------------------------
;
delay_500 movlw .166
movwf del_500
loop decfsz del_500,1
goto loop
return
;
;
End

Task
Assemble the program into machine code and simulate the program and analyze the stop watch
and PORTA register.
Practical Session 4: Flashing LED using Timer delay
In previous session student gets the complete knowledge of delay creation using general purpose
registers, in this session student will learn about the special purpose register which is allocated
for time delays known as timers.

Mid-range PIC family has one to three timers depending on the family, timer can use either as
timers to generate delay or as counters to count events happening outside the microcontrollers.
Timer 0 and Timer 1 will be considered in the session and Timer 2 discussed later.

Timer 0 configuration and operation

Timer 0 can be used as an 8bit timer in mid-range family but in 18 series it can be used as an 8-
bit to 16-bit wide register.

Following registers are associated with TMR0 register; therefore these registers need to be preset
before use the TMR0. (Refer complete register details from appropriate datasheet)

Step 1 configure OPTION register


From the option register following bits need to be configure,

 The source of the input for TMR0 need to be select by bit T0CS.
 TMR0 can be selected as the source for the prescaler by clearing the PSA.
 The required prescaler value selected by PS0 to PS2 bits, depend on time delay.
 Bit PSA must be cleared after prescaler setting.

Step 2 configure INTCON register to set timer interrupt.


From the INTCON register following bits need to be configured.

 Global interrupt bit (GPIE) and Timer0 interrupt bit (T0IE) need to enable by the
program.

Step 3 calculates and preset the TMR0 value,

TMR0 = 256 – (Overflow time) / (4 x TOSC x Prescaler)

Step 4 Timer0 overflow interrupt flag (T0IF) must be check by the program, whenever TMR0
get overflow flag set to logic 1 and it should cleared by the program before continue.
Sample program 1

Following program illustrate the basic configuration and very basic program for TMR0, program
written to illuminate the LED and blink it on every 1s time.

TMR0 value calculation

Assume that design used 20MHz crystal oscillator, 1:256 prescaler.

Calculate the maximum time delay that can create by TMR0, therefore TMR0 should equal to
zero.

Overflow time = 4 x TOSC x Prescaler x (256 – TMR0)

Overflow time = 4 x (1/20) x 256 x (256 – 0) us

= 13107.2 us = 13.1072 ms

From the above analysis, using a single loop TMR0 cannot create 1s delay, therefore program
should call the TMR0 several time; this can done by looping instruction.

Simple looping algorithm

 Create 10ms delay using TMR0


 Call the time delay 100 times using counter loop, to crate the 1s.

10ms delay using TMR0

From the equation,

TMR0 = 256 – (Overflow time) / (4 x TOSC x Prescaler)

TMR0 = 256 – [(10,000) / (4 x (1/20) x 256)]

= 60.6875

TMR0 value cannot be in decimal point therefore value 60 taken in to account, (10ms delay will
not be accurate this can be affect the long delays, however in later chapter student will learn how
to make the delays with less error)
Sample Program 1
; ----------------------------------------------------------------------
; A simple program to illuminate the LED
; LED which is connected to RB3 need to be illuminate
; LED blink every 1s delay
; ----------------------------------------------------------------------
;
; -------------------- Select the project target -----------------------
list p=16f88
; -------------------- Program Equates ---------------------------------
;
status equ 0x03
trisa equ 0x85
porta equ 0x05
trisb equ 0x86
portb equ 0x06
;
ansel equ 0x9b
;
tmr0 equ 0x01
option_r equ 0x81
intcon equ 0x8b
;
TOIF equ 2
W equ 0
f equ 1
counter equ 0x0c
;
; --------------------- Main Program -----------------------------------
;
org 0x00
start bsf status,5 ; Select Bank1
movlw 0x00 ; set PortB to an outputs
movwf trisb
movlw b'00000111' ; refer option register
movwf option_r ; prescaler set to 1:256
movlw b'00100000' ; TMR0 interrupt enable
movwf intcon
bcf status,5 ; Select Bank0
clrf portb
;
bsf portb,3 ; turn on led
;
; ---------------------- Timer Program -------------------------------
;
movlw 0x64 ; load counter register with 100
movwf counter
;
; ---------------------- TMR0 Program --------------------------------
;
clrf tmr0 ; clear timer
movlw 0x3c ; load TMR0 with 60
movwf tmr0
wait0 btfss intcon,TOIF ; check T0IF get 1
goto wait0 ; cnt loop until TMR0 gets overflow
bcf intcon,TOIF ; clear T0IF bit
;
wait1 decfsz counter ; decrement counter by 1
goto wait0 ; cnt TMR0 loop until counter get 0
;
bcf portb,3 ; turn off led
end

Task 1
Assemble the program into machine code and simulate the program and analyze the stop watch
TMR0 and PORTB register.

Task 2
Modify the above program with the switch, system should turn on the LED and blink when
switch turn on and LED should off when switch turn off.

Task 3
Create following three different delays using TMR0
 20 s
 5 minutes
 1 hour

Very simple algorithm to create 1 hour delay

 Create 10ms delay using TMR0


 Call the time delay 100 times using counter loop, to crate the 1s.
 Call the entire loop for 30 times using counter1 loop, to create 30s delay
 Call the 30s delay for 120 times using counter2 loop, to create 3600s delay
Practical Session 5: Seven Segment display using look up table

Basic 7-segment display operation already discussed in semester 1, from it to illuminate the 7-
segment display decoders and encoders used. In this session student will learn how to illuminate
the 7-segment display using microcontroller programming.

Look up table used in the program to store the 7-segment display truth table. Generally look up
tables are used to change data from one form to another. In this case look up table used to
convert the binary value to display value.

Look up table create

Assume common anode 7-segment display connected to microcontroller PORTB and following
table shows the configuration of PORTB.

Number RB7 RB6 RB5 RB4 RB3 RB2 RB1 RB0


0 1 1 0 0 0 0 0 0
1 1 1 1 1 1 0 0 1
2 1 0 1 0 0 1 0 0
3 1 0 1 1 0 0 0 0
4 1 0 0 1 1 0 0 1
5 1 0 0 1 0 0 1 0
6 1 0 0 0 0 0 1 1
7 1 1 1 1 1 0 0 0
8 1 1 0 0 0 0 0 0
9 1 0 0 1 1 0 0 0

The look up table for this,

display addwf pc ; add w register with pc


retlw b'11000000' ;0
retlw b'11111001' ;1
retlw b'10100100' ;2
retlw b'10110000' ;3
retlw b'10011001' ;4
retlw b'10010010' ;5
retlw b'10000011' ;6
retlw b'11111000' ;7
retlw b'10000000' ;8
retlw b'10011000' ;9

addwf – add w register value to file register.


retlw – return the w register with literal value.
Code operation

If system needs to display 0 following steps needed,

Step 1 program should move 0 into w register and it should call the look up table.

In the look up table first line says addwf to pc, this will add the W register value with the
program counter, since W = 0 then PC = PC + 0, therefore in next execution next line of the table
will be execute and literal value b'11000000' will be return with w register.

Step 2 To illuminate the 7-segment display, W register value should loaded to appropriate output
register (PORTA/PORTB)

Another example,

If system needs to display 6, Program should move 6 into w register and it should call the look
up table.

In the look up table first line says addwf to pc, this will add the W register value with the
program counter, since W = 6 then PC = PC + 6, therefore in next execution seventh line of the
table will be execute and literal value b'10000011' will be return with w register.
Sample program

; ------------------------------------------------------------------------
; A simple program for a 7-segment display
; program written for HP 488 demo board
; PortA 0-3 used to select one of four 7segment
; PortB used to illuminate 7-segment LED
; ------------------------------------------------------------------------
;
list p=16f88
;
; -------------------- Program Equates -----------------------------------
;
Pc equ 0x02
status equ 0x03
trisa equ 0x85
porta equ 0x05
trisb equ 0x86
portb equ 0x06
;
tmr0 equ 0x01
option_r equ 0x81
intcon equ 0x8b
TOIF equ 2
;
count equ 0x45
counter equ 0x55
W equ 0
f equ 1
;
check equ 0x88
;
; --------------------- Main Program --------------------------------------
;
org 0x00
start bsf status,5 ; Select Bank1
movlw b'00000' ; Set PortA to outputs
movwf trisa
movlw 0x00 ; set PortB to outputs
movwf trisb
movlw 0x00
movlw b'00000111' ; refer option register
movwf option_r ; prescale set to 1:256
movlw b'00100000' ; TMR0 interrpt enable
movwf intcon
bcf status,5 ; Select Bank0
;
Movlw 0x00 ; Turn off all LEDs
movwf portb
movlw b'00001' ; point 1st 7-segment display in the demo board
movwf porta
;
; ---------------------- counter program ----------------------------------
;
clrf count ; clear counter
;
; ---------------------- Timer Program 1s delay ---------------------------
;
delay movlw 0x64 ; load counter register with 100
movwf counter
;
; ---------------------- TMR0 Program --------------------------------
;
clrf tmr0 ; clear timer
movlw 0x3c ; load TMR0 with 60
movwf tmr0
wait0 btfss intcon,TOIF ; check T0IF get 1
goto wait0 ; cnt loop until TMR0 gets overflow
bcf intcon,TOIF ; clear T0IF bit
;
wait1 decfsz counter ; decrement counter by 1
goto wait0 ; continue TMR0 loop until counter get 0
;
; ---------------------------------------------------------------------------
incf count ; increment counter
movfw count ; move count value in to w register
call display ; call subroutine
movwf portb ; load portb register with return value
clrf W ; clear W register
goto delay ; goto delay loop
;
; ---------------------- Look up table ------------------------------------
;
display addwf pc ; add w value with program counter
retlw b'11000000' ;0
retlw b'11111001' ;1
retlw b'10100100' ;2
retlw b'10110000' ;3
retlw b'10011001' ;4
retlw b'10010010' ;5
retlw b'10000011' ;6
retlw b'11111000' ;7
retlw b'10000000' ;8
retlw b'10011000' ;9
end

Task 1

Assemble the program into machine code and simulate the program and analyze the W register
and PORTB register.

Task 2

Using Demo board HP 488 analyze the display.

Task 3

Modify the program to count 00-99 using two 7-segment displays.


Practical Session 6: Analogue to Digital Conversion

In electronic systems, controller units must be interface with sensors and actuators to
communicate with outside world. These sensors and actuators can be digital or analogue I/O
devices. However microcontrollers are digital devices and therefore to interface with analogue
devices microcontroller needs to convert the analogue values in to digital value, or to connected
with analogue actuators digital values to analogue values.

This chapter introduces the basic concept of A/D conversion process and controlling program to
communicate microcontroller (which will have internal A/D convertor) with analogue sensors.

In Mid-Range microcontrollers ADCON 0 and ADCON 1 registers will be used to configure the
A/D conversion.

ADCON 0 register used to configure A/D conversion clock, A/D conversion channel and also
used to Enable the conversion and check the statues of the conversion.
A/D conversion clock bits ADCS1: ADCS0 will be selected according to the device operating
frequency.

ADCON 1 register used to configure the result format and port configuration.
A/D conversion result format will be depend on ADFM bit value,

Code operation

1. Configure Input and output ports

2. Configure the A/D module:

• Configure analog pins/voltage reference and digital I/O (ADCON1)


• Select A/D input channel (ADCON0)
• Select A/D conversion clock (ADCON0)
• Turn on A/D module (ADCON0)

3. Wait the required acquisition time.

4. Start conversion:
• Set GO/DONE bit (ADCON0)

5. Wait for A/D conversion to complete, by either:


• Polling for the GO/DONE bit to be cleared (with interrupts enabled); OR
• Waiting for the A/D interrupt

6. Read A/D result register pair (ADRESH: ADRESL), clear bit ADIF if required.

7. For the next conversion, go to step 1 or step 2, as required. The A/D conversion time per
bit is defined as TAD. A minimum wait of 2TAD is required before the next acquisition
starts.
Sample program

; ----------------------------------------------------------------
; Analog to digital conversion
; PortA,1 (RA0) connected with RA1
; Voltage range 0-5 V
; -----------------------------------------------------------------
;
; Target PIC
;
list p=16f877
;
; ------------ Program Equates ------------------------------------
;
status equ 0x03
trisa equ 0x05
porta equ 0x85
trisb equ 0x06
portb equ 0x86
trisc equ 0x07
portc equ 0x87
;
tmr0 equ 0x01
option_r equ 0x81
;
intcon equ 0x0b
;
adcon0 equ 0x1f
adcon1 equ 0x9f
adresl equ 0x9e
adresh equ 0x1e
;
; ------------- main program ----------------------------------------
;
org 0x00
;
start bsf status,5
movlw 0xff ; PortA --> input
movwf trisa
movlw 0x00 ; PortB --> output
movwf trisb
movlw 0x00
movwf trisc ; PortC --> output
movlw b'00000000'
movwf option_r
bsf adcon1,7 ; all ports set as analogue
bcf status,5
;
; AD module configuration
;
ad movlw b'10000001' ; ON A/D conversion and AN0 as port
movwf adcon0
call delay ; call acquisition time
bsf adcon0,2 ; start conversion
loop btfsc adcon0,2 ; check the status
goto loop
;
bsf status,5
movf adresl,w ; ADRESL --> portb
bcf status,5
movwf portb
movf adresh,w ; ADRESH --> portc
movwf portc
goto ad
;
; ----------- time delay ------------------------------------------------
;
delay clrf tmr0 ; clear timer
movlw .200 ; load TMR0 with 60
movwf tmr0
wait0 btfss intcon,2 ; check T0IF get 1
goto wait0 ; cnt loop until TMR0 gets overflow
bcf intcon,2 ; clear T0IF bit
end

Circuit simulation

D1 – LED  LSB

D10 – LED  MSB

Verification

Given voltage range 0 V – 5 V


Binary range 0 – 210 = 0 – 1024

Therefore 1 V binary (digital)

1024 / 5 = 204.5 = 0011001101

View publication stats

Das könnte Ihnen auch gefallen