Lab 2
An Introduction to Assembler &
Building Programs
1
Writing in Assembler
Left-most space
Assembler
format: label instruction operand(s) ;comment
optional
For example:
label comment
instruction
comment
;now switch on red led
Start bsf status,5 ;select memory bank 1
addwf counter
operands 2
Assembler Directives
These look like Assembler mnemonics, but are instructions to the (Cross-)
Assembler program itself. They differ from one Assembler to the other, though
there does tend to be some similarity.
Assembler Directive Summary of Action
list implement a listing option*
#include include additional source file
org set program origin
equ define an assembly constant; this
allows us to assign a value to a label
end end program block
Example MPASM Directives
3
Representing Numbers
Radix Example Representation
Decimal D‘255’
Hexadecimal H‘8d’ or 0x8d
Octal O‘574’
Binary B‘01011100’
ASCII ‘G’ or A‘G’
4
Assembler File Structure (Simple Form)
Files that the Assembler
(e.g. MPLAB) generates
For us, this will be
MPLAB Executable File
.hex
Source File List File
Assembler
.asm .lst
Written by you, as a text
file, in Assembler format
Error File
.err
5
The PIC
16 Series
Instruction
Set
6
Arithmetic operations
7
logic operations
8
Data movement operations
9
Control operations
10
Miscellaneous operations
11
A First Program
;******************************************************************
;Very first program
;This program repeatedly adds a number to the Working Register.
;TJW 1.11.08 Tested 1.11.08
;******************************************************************
;
; use the org directive to force program start at reset vector
org 00
;program starts here
clrw ;clear W register
loop addlw 08 ;add the number 8 to W register
goto loop
end ;show end of program with "end" directive
12
Introducing MPLAB
Continue here with
the MPLAB tutorial
from page 86 of the
book.
13
Example
Assume you have a switch and an LED, the switch and
LED are connected as shown. Write a program that turns
the LED on if the switch is closed, and turns the LED off if
the switch is not closed.
14
These are the Special Function
Registers, which allow the CPU
to interact with the peripherals msb is “bank
select bit”
(Status register).
General purpose memory
15
;
;specify SFRs
status equ 03
porta equ 05
trisa equ 05
portb equ 06
trisb equ 06
;
org 00
;Initialise
start bsf status,5 ;select memory bank 1
movlw B’00000010'
movwf trisa ;port A according to above pattern
movlw 00
movwf trisb ;all port B bits output
bcf status,5 ;select bank 0
;
;The “main” program starts here
movlw 00 ;clear all bits in ports A and B
movwf porta
movwf portb
loop movf porta,0 ;move port A to W register
movwf portb ;move W register to port B 16
goto loop
end
Another way
BSF STATUS, RP0 ; select bank 1
BSF TRISA, 1 ; set RA1 as input
BCF TRISB, 1 ; set RB1 as output
BCF STATUS, RP0 ; select bank 0
loop BTFSC PORTA, 1 ; if A1 is 0 don't set B1
BSF PORTB, 1
BTFSS PORTA, 1
BCF PORTB, 1
GOTO loop
17
18