library of routines

Upload: laith-adhary

Post on 08-Apr-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/7/2019 Library of Routines

    1/57

    Library of Routinesfor PIC12F629

    Nearly all these instructions also work withPIC16F628. Just check on Port value(s) and

    first available file.see: Talking Electronics website

    A-E E-P P-Z

    See the article Start Here with PIC12F629 for helpful programming notes and a map of thefiles.The following is a list of sub-routines, ideas, and help for the PIC12F629. They apply to anyproject using the PIC12F629.

    They can be put into your program and modified in any way - to suit the input/output lines.The "Copy and Paste" version of these sub-routines can be found HERE.Your program should be created on a template in a text editor such as NotePad, usingblank12F629.asm as a starting layout. It provides the correct layout and spacing.An unusual problem you may get is a failure to compile your program due to hiddenformatting/characters. MPASM will not produce the needed .hex file if any problem exists in aprogram but it will produce a .lst file containing the faults. If you open .lst and see unusualmistakes, they will be due to hidden formatting characters. Simply retype all the wordingaround the mistake (in the .asm file) and the program will compile. Do not use EditPad as itproduces hidden characters.To use the Library of Routines below, go to the NotePad set of "Copy and Paste" Routinesand "Copy and Paste" them into your program in another NotePad, as needed.Additional sub-routines can be found in the PIC Programming Course. This is on thesubscription section of the website.

    Make sure each sub-routine uses a file (a register) with a name (a hex number) that doesn'tclash with any other sub-routine you have created.Make sure CALLs go to a sub-routine that has a RETURN (use retlw 00) to bring the microback to the correct pace in the program and create Labels that let you know what the sub-routine is doing.The following library is presented in alphabetical order. Using these sub-routines will get youstarted very quickly and will assist you with 70% - 90% of a new project.Read through the entire library so you know what is possible.Simply think of a word or requirement, go to the word and read about it. Many of the sub-routines are also available in the "Copy and Paste" section.Paste them into your program and modify them to suit. The micro will take each instructionand carry it out. Make sure you have a RETLW 00 that brings the micro back to Main.Get each sub-section working correctly before adding more instructions. Gradually build up

    your program and save it as a NEW NAME so it can be recalled if a major problem develops.Do not save it as the previous name as MPASM will sometimes not assemble it (it will think ithas already been assembled and - do nothing!!) and you will wonder why the improvementsdo not work!!

    Add a value to a File The PIC12F629 does not have a single instruction to add a number to a file. Two instructionsare needed to carry out this operation.

  • 8/7/2019 Library of Routines

    2/57

    AddMOVLW 0CChADDWF 2Eh,1

    ;Put CCh into W;CC will be added to the contents of file "2E."

    Add "bits" to a port - turn on bits or "lines."

    This is handy when more than one output line needs to be turned on.

    MOVLW 10hIORWF GPIO,1

    ;suppose GPIO has bits 0, 1 and 2 HIGH and we need; to turn on bit 5;Put 10h into W - this is bit 5;10h will be added to the contents of file "05."

    alternately, bit 5 can be SET

    bsf GPIO,5If more than one line needs to be made "HIGH" or "LOW," at the same time, you need to use:

    movlw xxhiorwf GPIO,1

    This is necessary as the PIC12F629 will fail to set two or more lines via the followinginstructions:

    bsf GPIO, 0bsf GPIO, 2

    The author has found the PIC12F629 will fail to set the second line.

    Address a File This means "to act on" or "work with" a file. It can be to "move a value into a file," "incrementa file," "decrement a file" or other similar operation. Only files can be addressed (theinstructions in the program cannot be address or altered). The files we are talking about arethe "empty" files from 20h to 5F. None of the program or the values in the tables can bealtered. The values in a table can be accessed and copied by a set of instructions covered inCALL Table.Typical addressing instructions are:

    MOVWF 2A,0DECFSZ 2A,1INCF 2A,1INCF 2A,0

    ;Copy file 2A into W;Decrement file 2A;Increment file 2A;will put the increment of file 2A into W but file 2A will not alter!!

    Addressing a Set of FilesA number of files can be used to store temporary data, such as the digits or letters of a score-board.This is sometimes called a "scratchpad" or "scratchpad area." The files should be sequentialto make programming easy.Suppose we have 8 files and need to address them with a simple sub-routine to output thedata to a display. The sub-routine is called INDIRECT ADDRESSING. See IndirectAddressing.

  • 8/7/2019 Library of Routines

    3/57

    ALL THE FLAGS AND BITSHere are some of the common flags and bits.For the other flags, see PIC12F629 Data Sheet (.pdf 4,926KB)

    bank select:

    bsf 03,5bcf 03,5

    selects bank 1 - this is where the OPTION register is accessed.selects bank 0 - this is the normal programming area

    carry 03,0 Test the carry bit:btfss 03,0 ;skip if a carry-out of the most significant bit has

    occurred.

    prescalerassigned toWDT

    bsf Option_reg,3or:bsf 81h,3

    see: Watchdog timerOption register is in bank 1

    prescalerassigned toTimer0

    bcf Option_reg,3or:bcf 81h,3

    Timer0 is in bank 0

    GPIO file 05h see input/output port. "Setting the port bits HIGH or LOW"

    TRISIO file 85h see "Setting the ports bits input or output"

    Status file 03 Contains the carry, bank select and zero flags.

    zero flagzero bit

    03,2 zero flag is bit 2 of file 03 (the STATUS file)1 = The result of an arithmetic or logic operation is zero0 = The result of an arithmetic or logic operation is not zeroYou can look at bit 2:btfss 03,2 ; skip if the zero bit isSET

    AND - see also Mask

    The AND operation will mask any or all the bits in a file. In this way you can "remove" any bitor the upper or lower nibble etc.The quickest way to perform the operation is as follows:To mask (remove) the lower nibble, it is ANDed with F0h (written as 0F0h)To mask (remove) the upper nibble, it is ANDed with 0Fh (can be written 00Fh)Place the value (say countA) to be operated on, into w:

    movf countA,wandlw 0F0h ;only the upper 4 bits will be in w.

    ARITHMETIC OPERATORS AND PRECEDENCE

    - see also Pseudo Instructions

    OPERATOR Example

    $Current/Return ProgramCounter

    goto $ + 3

    ( Left parenthesis 1 + ( d * 4)

    ) Right parenthesis (length + 1) * 256

  • 8/7/2019 Library of Routines

    4/57

    ! NOT (logical complement) if! (a == b)

    Negation (2's complement) 1 * length

    ~ Complement flags = ~ flags

    * Multiply a = b * c

    /Divide a = b / c

    % Modulus entry_len = tot_len % 16

    + Add tot_len = entry_len * 8 + 1

    Subtract entry_len = (tot 1) / 8

    Right Shift flags = flags >> 1

    >= Greater or equal if entry_idx >= num_entries

    > Greater than if entry_idx > num_entries

  • 8/7/2019 Library of Routines

    5/57

    Binary to HEX: see Decimal to Binary to HEX

    Binary Hex and Decimal numbersAny mixture of binary, Hex and decimal numbers can be shown in a program.Binary numbers are presented as: 0b00000000' or b'00000000' or B'00000000' or00000000b or b'0100' indicates the lowest 4.Hex numbers are shown as: 0x2 or 0x0F (= fifteen) or 0x3C or h' or $or h (must begin with 0 ....9)Decimal numbers are shown as: d'250' or decimal numbers without a prefix.

    ButtonseeSwitch

    bz - branch on zero flag being set to "1" See more instructions in "MACRO."

    NewSw timeout

    movfSw,0bz timeoutxxxxxxxyyyyyyyyy

    ;Move file "Sw" to W;IfSw file is zero, the result of moving it to w (or to itself) will;set the zero flag to "1" and the micro will goto "timeout."

    CALL see also StackCALL means to branch to, and return from a subroutine. It does NOT mean GOTO. GOTOmeans to branch unconditionally and maybe not return to the present routine. CALL means tobranch to another sub-routine and RETURN to the next address. Every CALL must have itsown RETURN or RETLW 00 to 0FFh statement.Use only RETLW 00. Do not use RETURN.When a CALL instruction is executed, the next address-value is placed on the stack and themicro goes to the location identified in the instruction.Do not "GOTO" a sub-routine that has a RETURN at the end of it. The micro will not knowwhere to return as the GOTO instruction does not put a return address into memory (thestack).The CALL instruction works to the full 1024 locations in a PIC12F629 chip.

    USING THE CALL INSTRUCTIONThe micro will come to CALL Delay in the sub-routine below. It will then advance down theprogram to Delay and carry out instructions until it reaches RETURN. The micro will thenmove up the program to the xxxxxxxxx line.

    CALL Delayxxxxxxxxx- - - - - - - -- - - - - - - -

  • 8/7/2019 Library of Routines

    6/57

    DelayDelA

    - - - - - - - -MOVLW 80hMOVWF 2ADECFSZ 2A,1GOTO DelARETLW 00

    ;Put 80h into W;Copy 80h into file 21A;Decrement file 21A;Loop until file 2A is zero

    CALL Table see also Table and Output a Table Value The instructions CALL Table uses the value in W and adds it to the Program Counter (PC -location 02 (file 02) - the ,1 indicates the value in W will be placed in the Program Counterfile) to create a JUMP VALUE to jump down a Table and pick up a value. The instructionbeside each value in a table places the value in W and makes the micro return to theinstruction afterCALL Table. The next instruction should be to move the value from W to afile.

    Call

    MOVF 2A,0CALL TableMOVWF 2C

    ;File 2A contains 05. Move it to W;W will return with 6D;Move 6D to file 2C

    Table

    ADDWF 02h,1RETLW 3FhRETLW 06hRETLW 5BhRETLW 4FhRETLW 66hRETLW 6Dh

    RETLW 7DhRETLW 07hRETLW 7FhRETLW 6Fh

    ;Add W to the Program Counter to create a jump.

    Carry - see also ROTATE for one of the operations involving CARRY. The carry bit is located in the STATUS register (file 03) and is bit 0.The carry bit is SET when the result of an operation is larger than 0ffh.The carry bit is SET when the result of an operation is less than zero.It is cleared by the instruction:BCF 03,0 - clear bit0 in file 03Carry is SET by the instruction:BSF 03,0To test the carry:BTFSS 03,0GOTO AAA ;The micro will go HERE if the carry is NOT set.GOTO BBB ;The micro will go HERE if the carry isSET.The carry is also used when a file is rotated left or right.When a file is rotated left, the MSB (most significant bit (bit 7) is passed into the carry and the

  • 8/7/2019 Library of Routines

    7/57

    carry-bit is passed into the file as bit 0. If you don't want the "carry bit" to affect the outcome ofthe operation it must be cleared before-hand, thus:

    bcf 03,0

    CBLOCK - (define a Block of Constants)This is a directive used for defining files that will be reserved for an application. The format ofCBLOCK is:

    cblock 0x20 ;define the start of the files. The first "file" or "register" for a 12F629 is20hLowbyte ;this will be file 20hMedbyte ;this will be file 21hHibyte ;this will be file 22h etc etc etcendcThis method of declaring variables is quite good, but macros cannot take advantage of it.The alternative to cblock is:

    Lowbyte equ 20hMedbyte equ 21hHibyte equ 22hcblock can use other files, starting at say 4Ch: The 3 files d1, d2 and d3 are files for adelay routine and are files 4Ch, 4Dh and 4Eh.cblock 0x4Cd1d2d3endcAnother method of defining files is:

    org 20hsave ds 1flag ds 2count ds 1csave ds 1temp ds 2ontime ds 1oftime ds 1timer ds 3freq ds 2

    mode ds 1rate ds 1hi ds 1low ds 1delay ds 3

    The compiler will allow one file (20h) for "save" and two files for "flag." timer will be given 3files.

  • 8/7/2019 Library of Routines

    8/57

    When writing the program, you write the instruction such as incf flag,1for the first flag fileandbtfss flag+1for the second flag file.

    Change Direction The direction of an input/output line (or a whole port) can be changed at any time during therunning of a program. The file we are loading or setting or clearing is file 85. It is in Bank 1.This file is called TRISIO.

    BSF 03,5BSF TRISIO,1BCF 03,5

    ;Go to Bank 1;Make GP1 input;Go to Bank 0 - the program memory area.

    BSF 03,5BCF TRISIO,1BCF 03,5

    ;Go to Bank 1;Make GP1 output;Go to Bank 0 - the program memory area.

    See also: SetUp for setting up the Input/Output lines. See Input for the instruction(s) to makea line Input. See Output to make a line Output. Lines are changed by setting or clearing bitsof the TRISIO register. This is called BIT MANIPULATION. This prevents touching (andupsetting) other lines.

    See Toggle to change the STATE of a line (from HIGH to LOW or LOW to HIGH).

    CompareTo compare two values, you can use XOR.To compare two numbers, they are XORed together and if they are the same, the Z flag willbe set. Take two numbers:number = 7A = 0111 1010W = 7A = 0111 1010Starting at the right hand end, ask yourself the question, "Is one OR the other a 1?" Theanswer is no. The next column. "Is one number OR the other a 1?" No BOTH the numbersare 1! so that's why the answer is NO. In this way every column has the answer NO, whenboth numbers match.When all the answers are Zero, the flag rises! to say the result is ZERO. In other words it is

    SET.To find the zero flag look in the STATUS register, bit 2, i.e. File 03,2.e.g: To compare two files:

    MOVF 2A,0 ;Move one file into WXORWF 2B,0 ;XOR W and 2BBTFSS 03,2 ;TestZ flag IfZ flag is SET (ie 1) the two files are the SAME!

    The same thing can be done by using the subtract operation:

  • 8/7/2019 Library of Routines

    9/57

    MOVF 2A,0 ;Move one file into WSUBWF 2B,0 ;Subtract W from 1BBTFSS 03,2 ;TestZ flag IfZ flag is SET (ie 1) the two files are the SAME!

    Same: Z flag is SET (ie 1) when the two files are the SAME!

    ComparisonThe contents of a file can be compared with the contents of the working register (W) todetermine their relative magnitudes. This is done by subtracting the contents of W from theselected file. By testing the Carry and Zero flags, 4 results can be obtained:E.g:

    MOVLW 22h ;Put 22h in WMOVWF 3C ;Move 22h to file 3CMOVLW 15h ;Put 15h in W

    SUBWF 3C,1 ;Subtract 15h from 22hBTFSS 03,2 ;TestZero flag

    OR

    BTFSS 03,0 ;Test Carry flagZero flag is SET if W = File value = MatchZero flag is CLEAR if no MatchCarry flag is SET if a borrow did not occur (W is less than or equal to file value)Carry flag is CLEAR if a borrow occurred (W is greater than file value)(Put a value into W and perform SUBWF). Test Carry:More than: Carry flag is CLEAR if W is greater than file value.Less than: Carry flag is SET if W is less than or equal to file value.Suppose a file (file 3E) is incremented to 8 such as in the Logic Probe with Pulser. We need

    to know if the file is 1, 2 or 3. The first thing to do is eliminate the possibility of zero.

    TestA MOVLW 00h ;Eliminate file 3E if it is zero,XORWF 3E,0 ;XOR file 3E with WBTFSC 03,2 ;Test the zero flag to see if file 3E is zeroGOTO TestA1 ;File 3E is zero

    The SUBWF operation below subtracts the W register (via a process called the 2'scomplement method) from file 3E and the carry flag in the Option register (file 03) will be SETif 3E is equal to W or more than W (i.e: 4 or more).

    MOVLW 04 ;Put 04 into W for subtract operationSUBWF 3E,0 ;Carry will be set if 3E is = or more than 4BTFSS 03,0 ;Test the carry flagGOTO Hi ;Go to another sub-routine such as "Hi"

    Here is the outcome for all the possibilities for file3E:

    If 3E = 0 C = 0 (we have eliminated the possibility of zero via the first 4 lines above)If 3E = 1 C = 0 (carry is zero - this is not the CARRY BIT it is theSET (1) or clear (0)

    indicator)If 3E = 2 C = 0If 3E = 3 C = 0 (carry is clear)If 3E = 4 C = 1 (carry is set)If 3E = 5 C = 1

  • 8/7/2019 Library of Routines

    10/57

    If 3E = 6 C = 1If 3E = 7 C = 1If 3E = 8 C = 1

    The carry bit in the Option file is bit 0. Therefore we test bit 0 of file 03:

    BTFSS 03,0The result in 3E can only be 1, 2, or 3.

    Config - configurationThe configuration word is located at address 2007h and is only accessed duringprogramming.'__CONFIG' directive is used to embed configuration data within .asm file.Note the double underbar at the front of "config."Some of the configuration settings:_CP_OFF & _WDT_OFF & _BODEN_OFF & _PWRTE_ON & _LVP_OFFEach setting has a single underbar and a "&" sign, with a single space between "&" sign.Here is an example of how the configuration word is created:; ----- Configuration Word -----------; Bandgap 11 Highest voltage (00 lowe; Unimplemented 000 Read as '0'; Data code protection 1 CPD disabled (0=enabled); Code protection 1 CP disabled (0 = program memenabled); Brown-out detect 1 BOD enabled (0=BOD disabled; GP3/MCLRE 0 digital I/O, MCLR in; Power-up timer 1 PWRT disabled (0=PW; Watchdog timer 0 WDT disabled (0=WDT ; Oscillator 100 INTOSC I/O on GP4 & GP5__config b'11000111010100'

    Oscillator:000 = LP oscillator Low power crystal on GP4 and GP5001 = XT oscillator Crystal/resonator on GP4 and GP5010 = HS oscillator HighSpeed crystal/resonator on GP4 and GP5011 = EC: I/O function on GP4 ClkIn on GP5100 = INTOSC oscillator I/O on GP4 & GP5101 = INTOSC ClkOut on GP4 I/O on GP5110 = RC oscillator I/O function on GP4 RC on GP5111 = RC oscillator ClkOut on GP4 RC on GP5

    CountIf you want to count the number of pulses from a push-button or switch, the easiest way is toincrement a file. A file will hold up to 255. The result is stored as a hexadecimal number from01 to FF.If you want to count to three, pre-load a file with 3 and decrement it and detect zero.

  • 8/7/2019 Library of Routines

    11/57

    Data Table - see DT below

    Debounce a Button (Switch) See Switch and Poll

    Debug This is not a term used in creating a program in PIC language, however we have twosuggestions for finding a "bug" or problem in a program.1. Go back to your previously saved version and note the differences in the programs. Try tovisually detect the fault.

    2. "Home-in" on the faulty section and see how far the micro is getting through by inserting aWait instruction. (See Wait) A LED on an output line will illuminate to indicate the micro hasreached the instruction.

    Decimal, Hex and Binary numbersAny mixture of binary, Hex and decimal numbers can be shown in a program.Binary numbers are presented as: 0b00000000' or b'00000000' or B'00000000' or00000000b or b'0100' indicates the lowest 4.Hex numbers are shown as: 0x2 or 0x0F (= fifteen) or 0x3C or h' or $or h (must begin with 0 ....9)Decimal numbers are shown as: d'250' or decimal numbers without a prefix.

    Decimal to Binary to HEX:

    0 0000 00000 1600010000

    10h 320010 000020h

    1 0000 00011 1700010001

    11h 330010 000121h

    2 0000 00102 180001 001012h 340010 001022h

    3 0000 00113 1900010011

    13h 35001000110

    23h

    4 0000 01004 2000010100

    14h 360010 010024h

    5 0000 01005 2100010101

    15h 370010 010125h

    6 0000 01106 2200010110

    16h 380010 011026h

  • 8/7/2019 Library of Routines

    12/57

    7 0000 01117 2300010111

    17h 390010 011127h

    8 0000 10008 2400011000

    18h 400010 100028h

    9 0000 10019 2500011001

    19h 410010 100129h

    100000 1010A 2600011010

    1Ah 420010 00102Ah

    110000 1011B 2700011011

    1Bh 43001010110

    2Bh

    120000 1100C 2800011100

    1Ch 440010 11002Ch

    130000 1101D 2900011101

    1Dh 450010 11012Dh

    140000 1110E 3000011110

    1Eh 460010 11102Eh

    150000 1111F 3100011111

    1Fh 470010 11112Fh

    480011 000030h 6401000000

    40h 800101 000050h

    490011 000131h 6501000001

    41h 810101 000151h

    500011 001032h 660100001042h 820101 001052h

    510011 001133h 670100 001143h 830101

    00110 53h

    520011 010034h 6801000100

    44h 840101 010054h

    530011 010035h 6901000101

    45h 850101 010155h

    540011 011036h 7001000110

    46h 860101 011056h

    550011 011137h 7101000111

    47h 870101 011157h

    560011 100038h 7201001000

    48h 880101 100058h

    570011 100139h 7301001001 49h 890101 100159h

    580011 10103Ah 7401001010

    4Ah 900101 00105Ah

    590011 10113Bh 7501001011

    4Bh 91010110110

    5Bh

    600011 11003Ch 7601001100

    4Ch 920101 11005Ch

    610011 11013Dh 770100 4Dh 930101 11015Dh

  • 8/7/2019 Library of Routines

    13/57

    1101

    620011 11103Eh 7801001110

    4Eh 940101 11105Eh

    630011 11113Fh 7901001111

    4Fh 950101 11115Fh

    960101 000060h 11201110000

    70h 1281000 000080h

    970101 000161h 11301110001

    71h 1291000 000181h

    980101 001062h 11401110010

    72h 1301000 001082h

    990101 001163h 11501110011

    73h 131100000110

    83h

    1000101 010064h 11601110100

    74h 1321000 010084h

    1010101 010065h 11701110101

    75h 133100000101

    85h

    1020101 011066h 11801110110

    76h 1341000 011086h

    1030101 011167h 11901110111 77h 135

    1000 011187h

    1040101 100068h 12001111000 78h 136

    1000 100088h

    1050101 100169h 12101111001

    79h 1371000 100189h

    1060101 10106Ah 12201111010

    7Ah 1381000 00108Ah

    1070101 10116Bh 12301111011

    7Bh 139100010110

    8Bh

    1080101 11006Ch 12401111100

    7Ch 1401000 11008Ch

    1090101 11016Dh 12501111101

    7Dh 1411000 11018Dh

    1100101 11106Eh 12601111110

    7Eh 1421000 11102Eh

    1110101 11116Fh 12701111111

    1Fh 1431000 11118Fh

  • 8/7/2019 Library of Routines

    14/57

    1441001 000090h 16010100000

    A0h 1761011 0000B0h

    1451001 000191h 16110100001

    A1h 1771011 0001B1h

    1461001 001092h 16210100010

    A2h 1781011 0010B2h

    1471001 001193h 16310100011A3h 179101100110

    B3h

    1481001 010094h 16410100100

    A4h 1801011 0100B4h

    1491001 010095h 16510100101

    A5h 181110110101

    B5h

    1501001 011096h 16610100110

    A6h 1821011 0110B6h

    1511001 011197h 16710100111

    A7h 1831011 0111B7h

    1521001 100098h 16810101000

    A8h 1841011 1000B8h

    1531001 100199h 16910101001

    A9h 1851011 1001B9h

    1541001 10109Ah 17010101010

    AAh 1861011 0010BAh

    1551001 10119Bh 17110101011

    ABh 187101110110

    BBh

    1561001 11009Ch 17210101100

    7Ch 1881011 1100BCh

    1571001 11019Dh 17310101101 ADh 189

    1011 11018Dh

    1581001 11109Eh 17410101110 AEh 190

    1011 1110BEh

    1591001 11119Fh 17510101111

    AFh 1911011 1111BFh

    1921100 0000C0h 20811010000

    D0h 2241110 0000E0h

    1931100 0001C1h 209

    1101

    0001 D1h 2251110 0001E1h

    1941100 0010C2h 21011010010

    D2h 2261110 0010E2h

    1951100 0011C3h 21111010011

    D3h 227111000110

    E3h

    1961100 010064h 21211010100

    D4h 2281110 0100E4h

    1971100 0100C5h 21311010101

    D5h 229111000101

    E5h

  • 8/7/2019 Library of Routines

    15/57

    1981100 0110C6h 21411010110

    D6h 2301110 0110E6h

    1991100 0111C7h 21511010111

    D7h 2311110 0111E7h

    2001100 1000C8h 21611011000

    D8h 2321110 1000E8h

    2011100 100169h 21711011001

    D9h 2331110 1001E9h

    2021100 10106Ah 21811011010

    DAh 2341110 0010EAh

    2031100 10116Bh 21911011011

    DBh 235111010110

    EBh

    2041100 1100CCh 22011011100

    DCh 2361110 1100ECh

    2051100 1101CDh 22111011101

    7Dh 237111001101

    EDh

    2061100 1110CEh 22211011110

    DEh 2381110 11102Eh

    2071100 1111CFh 22311011111

    DFh 2391110 1111EFh

    2401111 0000F0h

    2411111 0001F1h

    2421111 0010F2h

    2431111 0011F3h2441111 0100F4h

    2451111 0100F5h

    2461111 0110F6h

    2471111 0111F7h

    2381111 1000F8h

    2491111 1001F9h

    2501111 1010FAh

    2511111 1011FBh

    2421111 1100FCh

    2431111 1101FDh2541111 1110FEh

    2551111 1111FFh

  • 8/7/2019 Library of Routines

    16/57

    DecrementTo decrement a file, use the instruction: DECF 3A,1. This puts the new value back into thefile. Do not use DECF 3A,0 as the new value goes into W!To decrement a file twice, use:DECF 3A,1DECF 3A,1To halve the value of a file, the contents is shifted right:

    RRF 3A,1- the file must not have a bit in bit0.A file can be decremented until it is zero:DECFSZ, 3A,1To decrement W we can use the instruction: addlw -1

    Delay A delay sub-routine is needed for almost every program. One of the main purposes is to slowdown the execution of a program to allow displays to be viewed and tones to be produced.The shortest delay is NOP. This is a "do nothing" instruction that takes 1 micro-second.You will need one million "NOP's" to produce a 1 second delay.This is impractical as the program space will only allow about 1,000 instructions.

    The answer is to create a loop. If a file is loaded with a value and decremented, it will create ashort delay. The two instructions: DECFSZ 3A,1 and GOTO DelA will take 3uS. 80h loops =127 loops x 3 + 1 loop x 2uS + 2uS on entry + 1uS on exit = 386uS

    DelDelA

    MOVLW 80hMOVWF 3ADECFSZ 3A,1GOTO DelARETLW 00

    ;Put 80h into W;Copy 80h into file 1A;Decrement file 3A;Loop until file 3A is zero

    A simpler delay routine below decrements a file with 256 loops. Each loop is 4uS and theresult is slightly more than 1,000uS = 1mS. The routine exits with 00h in the file. On thesecond execution, the routine performs 256 loops - the file does not have to be pre-loaded.The longest delay (such as the one below) using a single file is approx 1mS.

    Del NOPDECFSZ 3A,1GOTO DelRETLW 00

    ;Decrement file 3A;Loop until file 3A is zero

    1mS delay

    NESTED DELAYSTo produce delays longer than 1mS, two or more files are needed. Each file is placed aroundthe previous to get a multiplying effect. The inner delay produces 256 loops, the output fileproduces 256 loops of the inner file. This results in 256 x 256 loops = 256mS.

    The simplest delay decrements a file to zero. At the end of an execution, a delay contains 00and this produces the longest delay, the next time it is used.This means a file does not have to be pre-loaded.The following is a two-file nested delay. The delay time is approx 260mS (say 1/4Sec):

    Del NOPDECFSZ 3A,1GOTO DelDECFSZ 3B,1

    ;Decrement file 3A;Loop until file 3A is zero;Decrement file 3B

  • 8/7/2019 Library of Routines

    17/57

    GOTO DelRETLW 00

    ;Loop until file 3B is zero

    260mS Delay

    If you want a delay between 1mS and 256mS, you will need to pre-load file 3B. For eachvalue loaded into file 3B, a delay of 1mS will be produced. A 125mS delay is shown below:

    DelDel1

    MOVLW 7DhMOVLW 3BNOPDECFSZ 3A,1GOTO Del1DECFSZ 3B,1GOTO Del1RETLW 00

    ;Load W with 125 for 125mS delay;Decrement file 3A;Loop until file 3A is zero;Decrement file 3B;Loop until file 3B is zero

    125mS Delay

    A 0.5 second delay:

    ; Delay = 0.5 seconds = 500,000 cycles; Clock frequency = 4 MHz

    cblock 0x20 ;delay files d1, d2 and d3 are at 20h, 21h and 22hd1d2d3endc

    Delay1

    Delay2

    movlw 0x0B0hmovwf d1movlw 17hmovwf d2

    movlw 0x02movwf d3decfsz d1, fgoto $+2decfsz d2, fgoto $+2decfsz d3, fgoto Delay2goto $+1goto $+1goto $+1retlw 00

    ;499994 cycles

    ;this sends the micro to: goto Delay2;2 cycle instruction that advances the; micro to the next instruction; 2 more cycles

    checked 3-2-08

    The goto $+2 instruction is a 2-cycle instruction that sends the micro 2-instructions down theprogram. This instruction has two advantages. It provides a delay of 2 microseconds @4MHzand saves creating a label.In the decrementing section of the sub-routine (Delay2), the instruction: goto $+2 makes themicro go to 2 instructions down the program. This is simply a new and novel way to produce adelay routine.The second goto $+2 sends the micro to: goto Delay2. The first instruction could have beengoto $+4 but this routine is designed to "waste" time and every instruction adds to the delay.

    A 2 second delay:

  • 8/7/2019 Library of Routines

    18/57

    ; Delay = 2 seconds = 2,000,000 cycles; Clock frequency = 4 MHz

    cblock 0x20 ;delay files d1, d2 and d3 are at 20h, 21h and 22hd1d2d3endc

    Delay1Delay2

    movlw 0x11movwf d1movlw 0x5Dmovwf d2movlw 0x05movwf d3decfsz d1, fgoto $+2decfsz d2, fgoto $+2decfsz d3, fgoto Delay2

    goto $+1goto $+1retlw 00

    ;1,999,996 cycles;this sends the micro to: goto Delay2

    ;2 cycle instruction that advances the; micro to the next instruction

    Code generated by http://www.golovchenko.org/cgi-bin/delayThe following sub-routine will produce a delay of "X" minutes and "Y" seconds.The following example make the micro wait EXACTLY 930,000,000 instruction cycles.i.e: 15 minutes 30 secondsExample:movlw 0x0F ;This will produce 15 minutes. This the "X" valuecall _WAIT_1Minmovlw 0x30 ;This will produce 30 seconds. This is the "Y" valuecall _WAIT_1s

    ; The following delays are calibrated for operation at 4MHz;; OPERATION: Create a literal in W. This literal represents themultiplier

    ; of the delay. Immediately call the function.;; Example:; movlw 0x0F; call _WAIT_1Min; movlw 0x30; call _WAIT_1s

    ;;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%cblock 0x20 - the names of the files below will start at file 20h;......minuteseconddecimilli

  • 8/7/2019 Library of Routines

    19/57

    micro;......endc;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%_WAIT_1Min ; W * 60,000,000

    movwf minutemovlw 0x3B ; 59 * 1,000,000

    call _WAIT_1smovlw 0x09 ; 9 * 100,000call _WAIT_100mmovlw 0x63 ; 99 * 1000call _WAIT_1mmovlw 0x63 ; 99 * 10call _WAIT_10usgoto dec4 ;

  • 8/7/2019 Library of Routines

    20/57

    movwf decimovlw 0x63 ; 99 * 1000call _WAIT_1mmovlw 0x63 ; 99 * 10call _WAIT_10usgoto dec2 ;

  • 8/7/2019 Library of Routines

    21/57

    ;1 second delay using timer1L and timer1H

    _1Sec

    movlw 05hmovwf delCnop

    decfsz tmr1L,1goto $-2decfsz tmr1H,1goto $-4decfsz delC,1goto $-6retlw 00

    Detect a value If a file has been incremented in a sub-routine you may want to know the value it contains.You may want to know its exact value or if it is higher or lower than a certain value.To see if it is an exact value, it is XORed with a known value. See XOR.To detect a particular value, they are XORed together. See XOR.You can also detect a particular value by BIT TESTING. You must make sure that all thenumbers being tested can be distinguished by testing a single bit. For example: 1, 2, 4, 8, 10hcan be tested via bits 0, 1, 2, 3, 4. But if 3 is included in your requirement, you cannot test asingle bit.

    DifferentTo find out if two numbers are different, they are XORed together. See XOR

    Divide Simple division such as divide by 2 can be performed by the RRF instruction. SuccessiveRRF's will divide by 4, 8, sixteen etc. Other divisions are beyond the scope of this course. Thenumber cannot have a bit in bit0, if an accurate division is required.

    DS or dsThis term can be seen in some programs, as:count ds 2sum ds 1dve ds 3It is the code for: "advances the load pointer by the specified value."Reserve the number of file locations. ORG must be set for this to work.It simply allocates two locations for count, one for sum and three for dve This allows theprogrammer to produce files for: count, count+1, sum, dve, dve+1, dve+2

  • 8/7/2019 Library of Routines

    22/57

    DT - Data TableThe DT directive (command) allows you to create a table without having to write:

    retlw 40hretlw 79hretlw 3Ahretlw 4Ch

    For example:SegTable ANDLW 0Fh ; convert a number in W to segment form

    ADDWF PCL,F

    DT 40h,79h,24h,30h,19h,12h,02h,78h,00h,10hDT 7Fh,7Fh,7Fh,7Fh,7Fh,7Fh

    Will compile to:SegTable ANDLW 0Fh ; convert a number in W to 7-segment form

    ADDWF PCL,Fretlw 40hretlw 79h

    retlw 24h etc

    DoubleTo double the value of the contents of a file, it is shifted LEFT (RLF 3A,1). The number mustbe less than 80h. (it must not have a bit in location bit7).

    EEPROM The PIC12F629 has 128 bytes of EEPROM, from 00h to 7F to permanently store data.If you need to store only a few bytes of data for a short period of time, use files that are notrequired for the running of the program. This information will be lost when power is removed.The 128 bytes of EEPROM requires a special set of instructions to place data into EEPROM.The actual writing time for this data is very long (in computer terms) and can be done in thebackground, while the main program is executing. A flag will SET when the data has beenwritten and this will allow another byte of data to be entered.Each EEPROM cell can be written about 1 million times.Before reading a value in a location in the EEPROM, it must be loaded with a value during"burning." To load the first location in EEPROM with a value, the f ollowing instructions areplaced in a program. The EEPROM starts at location 2100h and the term DE means: "defineEEPROM." There are 128 EEPROM locations and by following the layout in the second table,any location can be addressed during burning.

    ORG 2100hDE 43hEND

    ;Starting point of EEPROM;First EEPROM location holds the value 43h

    The locations in EEPROM:

  • 8/7/2019 Library of Routines

    23/57

    ORG 2100hDE 84h, 16h, 23h, 80h, 0CAh, 32h, 7Bh, 0A2hDE 34h, 53h, 25h, 02h, 0FFh, 20h, 03h, 04hEND

    ;Starting point;;;for up to eight lines

    READ EEPROM: The sub-routine to read a value in the EEPROM is shown below.

    EERead bsf Status, rp0movlw Config_addrmovwf EEADRbsf EECON1, rdmovf EEDATA,0bcf Status, rp0retlw 00

    ;go to Bank 1;;address to read;EE read;move data to W;back to bank 0

    WRITE TO EEPROM: The sub-routine to write to EEPROM is shown below.

    EEWrite bsf status,rp0bsf EECN1,WRENbcf INTCON,GIEmolw 55hmovwf EECON2movlw AAhmovwf EECON2bsf EECON,WR

    bsf INTCON,GIEbcf Status,rp0retlw 00

    ;bank1;enable write;disable interrupts;unlock write;;;:start the write

    ;enable interrupts;bank 0;Return

  • 8/7/2019 Library of Routines

    24/57

    End This is a directive, placed at the end of of program to tell the assembler to finish the job ofassembling the instructions into .hex code. The directive is:

    end

    End of TableThe end of a table can be detected in two different ways.If a value such as FF is not used in any of the data, it can be used as an End of Tablemarker. The sub-routine calling the table must look for 0FFh to detect End of Table.

    Table

    ADDWF 02h,1RETLW 3FhRETLW 06hRETLW 5BhRETLW 4FhRETLW 66h

    RETLW 6DhRETLW 7DhRETLW 07hRETLW 7FhRETLW 6FhRETLW 0FFh

    ;Add W to the Program Counter to create a jump.;0 format= gfedcba;1;2;3;4

    ;5;6;7;8;9;End of table marker

    The other method is to count the number of items in a table and make sure the sub-routinecalling the table doe not CALL values beyond this value.

    EqualTo detect if two files are equal, they are XORed together. See XOR.

    Equates "equ"Equates assign an easy to remember label to a numeric value. This value can be a file or bitin a file.e.g:delay1 equ 20h ;every time "delay1" is inserted into a program, the assembler will assignfile 20h.in your program:

    movlw 80hmovwf delay1 ;the assembler will put 80h into file 20hThe in/out pins on a 12F629 are 2,3,4,5,6 and 7.These are GP5, GP4, GP3, GP2, GP1 and GP0These correspond to GPIO,5 GPIO,4 GPIO,3 GPIO,2 GPIO,1 and GPIO,0 in a program.Suppose GPIO,3 is called "switch" and GPIO,5 is called "LED" (it drives a red LED).In the equates section of your program (at the top of your program) you can equate bit "3" ofthe GPIO file as "switch and bit "5" as "LED."The equates will appear as:

  • 8/7/2019 Library of Routines

    25/57

    switch equ 3LED equ 5in your program:

    btfss GPIO,switch

    orbsf GPIO,LED

    Error Message 302If you get an error message when MPASM is compiling your program to a .hex file, it will notproduce the .hex file.To find the error messages, open the .lst file.Some error messages are just a warning such as:

    Message[302] myfile.ASM 136 :

    Register in operand not in bank 0. Ensure that bank bits arecorrect.

    The above is a warning that you need to select the correct bank.You can remove the warning message by inserting the following at the top of your .asmprogram

    ERRORLEVEL -302 ;remove messages

    FSR See Indirect Addressing This is a special file called File Select Register. It has the address 04. It is not a file like the

    other files in the micro but a POINTER FILE and is used in conjunction with another file calledINDF.INDF has the address 00.INDF is not actually a file but a robot arm. It grabs the contents (or delivers contents) to a filepointed to by FSR. These are two special files (devices) that allow very powerful (lowinstruction) programming to be produced.For instance, if FSR is loaded with 2C, it will tell INDF to grab (or deliver) contents to file 2C.To do this, we need the instructions:MOVLW 2CMOVF 04If we now put 8Fh into INDF, the value will actually go into file 2C.This is called INDIRECT ADDRESSING.

    GOTO The GOTO instruction causes the micro to go to the address identified by a label such as"No" or "Yes."

    BTFSS GPIO,0GOTO No

    ;Is button pressed?;No

  • 8/7/2019 Library of Routines

    26/57

    NoYes

    GOTO YesRETLW 00MOVLW 3Fhetc

    ;Yes

    The instruction: goto $ + 2

    "$" means the current address."+ 2" means to advance two instructions down the program.

    btfss GPIO,0goto $ + 2instruction xinstruction yinstruction z

    ;this will end the micro to instruction y;the micro will advance to this instruction;the micro will never execute this instruction!!!!

    To go "up" the program, the goto instruction is:goto $3orgoto $0dhor $.16 (minus decimal sixteen). The instruction should be written without any gaps: $.16When writing a program, you must make sure the micro will get back to the "Main" routine.If you use a "call" instructions such as:

    call delay_1make sure the sub-routine has:

    retlw 00to get the micro back to "Main."You cannot use the instruction:

    goto delay_1as the "retlw 00" in the delay_1 routine will not take the micro back to "Main" as the returnaddress has not been remembered with a "goto" instruction.You can also define a location by writing the LABEL (in this case "Step") and an offset - in thiscase +1. The micro will go to "movwf tmr2." This has an advantage. It is easy to see, ratherthan writing $4, when a large number of instructions are to be counted.

    Step

    movlw 25movwf tmr2btfsc Sw2goto newpressdecfsz Sw2,fgoto Step+1retlw 00

  • 8/7/2019 Library of Routines

    27/57

    Halt Do not use the word "Halt" as a label, the assembler does not like it. Use Loop, Pause, Stop,Wait. See Loop and Stop. To create a "halt" instruction:

    Loop goto $ This will cause the microcontroller to keep looping theinstruction.

    Halve (Half)To halve (half - divide by two) the value of the contents of a file, it is shifted RIGHT (RRF1A,1). The number must be an even number (it cannot have a bit in bit0).

    HEX: see Decimal to Binary to HEX

    Hex, Binary and Decimal numbersAny mixture of binary, Hex and decimal numbers can be shown in a program.Binary numbers are presented as: 0b00000000' or b'00000000' or B'00000000' or00000000b or b'0100' indicates the lowest 4.Hex numbers are shown as: 0x2 or 0x0F (= fifteen) or 0x3C or h' or $or h (must begin with 0 ....9)Decimal numbers are shown as: d'250' or decimal numbers without a prefix.

    HigherTo find out if a number is higher than a know value, a comparison is made. SeeComparison.

    IncrementTo increment a file, use the instruction: INCF 2A,1. This puts the new value back into the file.Using INCF 2A,0 puts the new value also into W!To add two to a file, it can be incremented twice:INCF 2A,1

    INCF 2A,1To double the value of a file, the contents is shifted left:RLF 2A,1A file can be incremented until it "rolls over to zero." Normally a file is decremented to zeroand a skip occurs when it is zero. But the same effect can be produced by incrementing afile:INCFSZ, 2A,1To increment W, use ADDLW, thus: ADDLW 01 or ADDLW 3Bh

  • 8/7/2019 Library of Routines

    28/57

  • 8/7/2019 Library of Routines

    29/57

    RETURN

    The following instructions read files 21h, 22h, 23h, 24h, 25h, 26h, 27h and 28h and outputs toGPIO (file 05). Output Port 05 has only 5 lines: GP0, GP1, GP2, GP4 and GP5. GP3 ismissing and this makes it difficult to display values from a file.

    Loop1

    MOVLW 08MOVWF 20hMOVLW 21hMOVWF 04MOVF 00,0MOVWF GPIOCALL DelayINCF 04DECFSZ 20hGOTO Loop1RETURN

    ;8 loops of the program;File 20h is the decrementing file;Load W with start of 8 files;Load 21h into FSR;Copy file 21h (or next file) into W;Move W to output Port GPIO;Show value LEDs etc;Increment FSR to make INDF go to next file

    INDF See Indirect Addressing and FSRThis is a special file called INDirect File.INDF has the address 00.INDF is not actually a file but a robot arm. It grabs the contents (or delivers contents) to a filepointed to by FSR.This is used in an operation called INDIRECT ADDRESSING.

    Input The six bits of the in/out port GPIO can be made input or output by the value of the bits in a

    file called TRISIO. GP3 can only be INPUT.To make a line INPUT, the corresponding TRISIO bit must be "1."To make a line OUTPUT, the corresponding TRISIO bit must be "0."To make a line INPUT (or OUTPUT), the instructions must be placed inside BSF 03,5 andBCF 03,5.For example, to make the lowest line of GPIO, an INPUT, the following instructions areneeded:

    BSF 03,5MOVLW 01MOVWF GPIOBCF 03,5

    ;Go to Bank 1;Load W with 0000 0001;Make GP0 input;Go to Bank 0 - the program memory area.

    The other individual lines are:movlw 02 ;Load W with 0000 0010movwf GPIO ;Make GP1 inputmovlw 04 ;Load W with 0000 0100movwf GPIO ;Make GP2 inputmovlw 08 ;Load W with 0000 1000movwf GPIO ;Make GP3 input

  • 8/7/2019 Library of Routines

    30/57

  • 8/7/2019 Library of Routines

    31/57

    nop ;this instruction is equal to: "movlw 00"goto sub-1goto sub-2goto sub-3goto sub-4goto sub-5

    Label This is the name given to each sub-routine. It is placed in the first column of your program(called an assembly program).Some names cannot be used as they are reserved by the assembler. Keep the length to lessthan 8 letters. Do not use "-" or "/" Use "_" to separate.Here are some examples:Alarm Alarm_1 Beep Button Count Dec Delay Display Fast Find HeeHaw Inc Look Loop MainSend Show Siren Sound Sw Switch TableTable2 Table_3 Test Try Try_2 Toggle Tone Unit

    Less than - see Comparison

    Load a file This operation cannot be done directly. A number (a value) is called a LITERAL. It is loadedinto W then the value in W is moved to a file. The two instructions are:

    MOVLW 0FFh

    MOVWF 2A

    ;Load a value (called a Literal) (00 to 0FFh) into W

    ;Move the value in W to a file

    Look at an InputThere is no instruction called "look." If a switch or button is connected to an input line such asthe lowest line on GPIO, the instruction is:

    BTFSS GPIO,0GOTO NoGOTO Yes

    ;Is button pressed?;No;Yes

    This assumes the switch is connected to the positive rail and the input goes HIGH when thebutton is pressed.This instruction also works for a signal on line GPIO,1. You must make sure line GPIO,1 is anINPUT via the SetUp routine.The two instructions after BTFSS GPIO,1 can be "GOTO Yes", "GOTO No" by changing thefirst instruction. The decision will depend on the number of instructions for the "Yes" or "No"answer, as the instruction placed directly after BTFSS GPIO,1 must be a GOTO.

  • 8/7/2019 Library of Routines

    32/57

    BTFSC GPIO,1GOTO YesGOTO No

    ;Is button pressed?;Yes;No

    LoopThe action of looping is carried out for a number of reasons. The micro does not have a HaltorStop feature and must carry out instructions at all times. A loop will hold the micro in oneplace.To get out, a set of instructions such as "look" is needed inside the loop. These instructionssee if a button has been pressed etc. Alternatively, if the watchdog timer is SET, the micro willcome out of the loop and go to location 04. The instructions to create a loop are as follows:

    Loop NOPGOTO Loop

    To create a "loop" instruction:Loop goto $ This will cause the microcontroller to keep looping theinstruction.

    LowerTo find out if a number is lower than a know value, a comparison is made. See Comparison.

    Macro

    A Macro is similar to a sub-routine. You can call it from anywhere in a program. The aim of amacro is to save lines of code.Some assemblers have built-in macros and recognise abbreviations such as the following:Do not use these instructions unless you know EXACTLY what you are doing.fr = file registerFor instance, we will explain the following instruction in the table below:Branch on No Zero to addr = btfss 3, 2 goto addr. (file 3, bit 2 is the zero flag)Test the zero flag. Skip if it is set. In other words skip if the zero flag is set, but BRANCH if it isnot zero!The normal instructions are as follows:

    btfss 3,2goto tune1next instruction

    alternately, you can use:bnz tune1next instruction

    Mnemonicaddcf fr, dsubcf fr, d

    DescriptionAdd carry to frSubtract carry from fr

    Functionbtfsc 3, 0 incf f,dbtfsc 3, 0 decf fr,d

  • 8/7/2019 Library of Routines

    33/57

    negf fr, db addrbz addrbnz addrbc addrbnc addrskpcskpncskpzskpnzclrzsetzclrcsetctstf frdecbnz fr,addr

    Negate file register frBranch to addrBranch on Zero to addrBranch on No Zero to addrBranch on Carry to addrBranch on No Carry to addrSkip on CarrySkip on No CarrySkip on ZeroSkip on No ZeroClearZero flagSet Zero flagClear Carry flagSet Carry flagTest file register frDecrement fr, if zerobranch to addr

    comf fr, 1 incf fr,dgoto adddrbtfsc 3, 2 goto addrbtfss 3, 2 goto addrbtfsc 3, 0 goto addrbtfss 3, 0 goto addrbtfss 3, 0btfsc 3, 0btfss 3, 2btfsc 3, 2bcf 3, 2bsf 3, 2bcf 3, 0bsf 3, 0movf fr, fdecfsz fr goto addr

    A macro can be created to move a number (a literal) into a file, using a single instruction. This

    normally requires two instructions:movlw 64h ;put 64h into Wmovwf 2Ch ;move 64h to file 2C

    The single instruction we will create is:

    movlf 64h,2Ch ;this instruction will put 64h into file 2C. (a macro must be included in theprogram)

    To create a macro for the instruction "movlf" the following is placed at the top of yourprogram:movlf macro literal,file ;literal -> file

    movlw literal

    movwf fileendm

    When you write the instruction: movlf 4Ah,2Fh ;4A will be placed into file 2F.

    MainThe Main routine is constantly looped and generally consists of sub-routines that areCALLed.

    Main CALLSwitchCALL DisplayCALL BeepGOTO Main

    ;Loop Main

  • 8/7/2019 Library of Routines

    34/57

    Mask - see also AND for a "2-instruction" codeIf you want to remove a number of bits from a file, the operation is called MASKING.You can remove the high or low nibble (a nibble is a set of 4 bits) or any other bits. Anynumber from 0 - 7 can be obtained by masking (removing) bits 3,4,5,6,7, and leaving only bits0, 1 and 2.To mask (remove) the upper nibble, the number is ANDed with 0F. To mask the lower nibble,the number is ANDed with F0. (this is written: 0F0h in the program)

    number:W:

    answer:

    1001 01111111 00001001 0000

    MOVLW 97hMOVWF 2AMOVLW 0F0hANDWF 2A,1

    ;Put 97h into W;Move 97h into file 2A;put the "masking value" into W;AND 97h with file 2A. The result will be in file 2A.

    More than- see Comparison

    Move a file to W The contents of a file can be moved to W with the following instruction:MOVF 2A,0 The contents are actually COPIED. The original file still holds the contents.

    Move a file to another file The contents of a file can be moved to another file via the following instructions.It is firstly copied to W then W is copied to the new file:

    MOVF 2A,0MOVWF 2B

    ;The contents of file 2A is copied to W;W is copied to file 2B

    Multiply Simple multiplication such as multiply by 2 can be performed by the RLF instruction.Successive RLF's will multiply by 4, 8, sixteen etc. You need to be careful as this is called a"blind" operation.A number such as 80h (128) will not be doubled as 1000 0000 will be moved to the left and

    the top bit will be passed to the Carry. Only numbers up to 7F (127) can be doubled.To multiply by 2:

    RLF 2A,1 ;The contents of file 2A is doubled

    To multiply any two numbers together requires a program. Since the PIC12F629 does nothave any multiply function, it is carried out by successive ADDITIONS. A number from 01 to255 can be multiplied by 01 to 255.

  • 8/7/2019 Library of Routines

    35/57

    To multiply 75(4Bh) by 122(7A), 122 is added to a file 75 times. It needs two files to hold theanswer.

    M1M2

    CLRF 2BCLRF 2CMOVLW 7Ah

    MOVWF 2A,1MOVLW 4BADDWF 2B,1BTFSS 03,0GOTO M2INCF 2C,1DECFSZ 2A,1GOTO M1RETURN

    ;Clear the receiving file;Clear the receiving file;122

    ;file 1A holds 122;75;ADD 75 to file 2B;Test Carry bit in status;file. CLEAR = no carry; SET = carry

    The result is a 16 bit binary number of the form: file 2C, file 2B = 0000 0000 0000 0000To multiply two numbers and obtain a decimal result requires a different program.

    Nested DelaySee Delay

    Origin - ORGThis is a pseudo instruction (also called a directive) that tells the assembler where to placethe next instruction. ORG must have a value. ForORG 000, the real instruction will beplaced at memory location 000.ForORG 2Ch, the first instruction in Main will be placed at address location 2Ch as shownbelow:

    SetUpMain

    ORG 000MOVLW 08MOVWF TRISIOOPTION 0DFh- - - - - - - - - -- - - - - - - - - -ORG 2ChCALL SwitchCALL DisplayCALL BeepGOTO Main

    ;Start of program in memory;;;Next following instruction will be placed at location 2Ch

    Oscillator Calibration value

    call 0x3ff ;get the calibration value

  • 8/7/2019 Library of Routines

    36/57

    movwf OSCCALorg 0x3ffretlw 0x20END

    ;calibrate oscillator;OSCCAL calibration value is located at the last line of; program memory and has the instruction to return with; 20h in W

    Output a Table Valuesee also Table

    Table

    ADDWF 02h,1RETLW 3FhRETLW 06hRETLW 5BhRETLW 4FhRETLW 66hRETLW 6DhRETLW 7DhRETLW 07hRETLW 7FhRETLW 6Fh

    ;Add W to the Program Counter to create a jump.

    Output a Value The output port for a PIC12F629 is actually a FILE or REGISTER! It is file 05.

    The 6 lines of the port are called: GP0, GP1, GP2, GP3, GP4 and GP5.Each line can deliver approx 25mA. The maximum total current for the chip is about 150mA.An output line can be HIGH or LOW. Each output line corresponds to a bit in the fileassociated with the port. When the bit is SET, the line is HIGH. When the bit is CLEAR, theline is LOW.Before you can make a l ine HIGH or LOW, the file must be "configured." This means each bitmust be made an OUTPUT. This is done via the TRISIO file. This file is located at 85h - inBand 1.Any line can be made either an input or an output at any time during the running of a programand to make a line INPUT, the corresponding bit in the TRISIO file is made "1." To make aline OUTPUT, the corresponding bit in the TRISIO file is made"0."There are two ways to get to the TRISIO file. One is directly via the instruction:

    MOVLW 2BhTRISIO ;Load xx10 1011 into W;Make GP2 and GP4 output.

    The other is via the two instructions: BSF 03,5 and BCF 03,5. These instructions allow you togo to bank1 where the TRISIO file is located. It is in Bank1 and the TRISIO file is called 05.

    BSF 03,5MOVLW 3FhMOVWF 05

    ;Go to Bank 1;Load W with 0011 1111;Make all GPIO input

  • 8/7/2019 Library of Routines

    37/57

    BCF 03,5 ;Go to Bank 0 - the program memory area.

    Any lines that are made output can be made HIGH or LOW.

    MOVLW 16h

    MOVWF GPIO

    ;Load 0001 0110 into W

    ;Make GP1 and GP2 and GP4 HIGH.

  • 8/7/2019 Library of Routines

    38/57

    PauseTo create a "pause" instruction:Loop goto $ This will cause the microcontroller to keep looping theinstruction.or

    Loop nop

    goto Loop

    PULSE WIDTH MODULATION (PWM)To make a motor-driven toy (car, robot etc) travel at a slow speed (or any speed) the RPM(revolutions per minute) of the motor needs to controlled. You can do this by supplying lesscells (less "batteries") a lower voltage via a power supply or providing pulses of energy thatcause the RPM of the motor to increase or decrease. You can also add a resistance to one ofthe leads.One of the simplest ways is to provide pulses of energy and this can be done with transistors,IC's or a microcontroller.The following code allows 2 motors to be controlled via 16 steps, from 0 to 16. The codesimply delivers a value such as 4/16 to one motor and 12/16 to the second motor in 1/100th

    second.The value of the step is contained in file M1 (for motor-1) and M2 (for motor-2).

    ;M1 & M2 are the bits in Ghost file for the motors;PWM1 is the file for motor 1 speed (0-15);PWM2 is the file for motor 2 speed (0-15);Ghost file holds the bits (M1 & M2) to turn on/off each motor

    Preload the PWM files:

    movlw (0 to .15 - decimal 15)movwf PWM1movlw (0 to .15 - decimal 15)movwf PWM2

    DoPWM bsf Ghost,M1 ;turn motor 1 on

    bsf Ghost,M2 ;and motor 2movlw 1 ;preload W

    PwmLoop subwf PWM1,f ;sub 1 from PWM1btfss STATUS,dc ;was there a borrow from bit 4bcf Ghost,M1 ;yes so turn motor 1 offsubwf PWM2,f ;now do second channelbtfss STATUS,dcbcf Ghost,M2 ;turn motor 2 offmovf Ghost,w ;copy register to wmovwf GPIO ;move w to I/O registermovlw 1 ;reload Waddwf Count,f ;inc count but set flags

    btfss STATUS,dc ;have we been around 16 timesgoto PwmLoop ;no, so go around inner loopbtfss STATUS,z ;have we done 256 timesgoto DoPWM ;no so repeat outer loopretlw 0 ;done

    Push and Pop and "Save"Push and Pop are terms used when programming some of the "older style" microprocessorsand refers to the ability to store a value (in a file) and send it to a place called a "stack" andget it back later. The microcontrollers we are dealing with have lots of files and we rarely run

  • 8/7/2019 Library of Routines

    39/57

    out of them so the ability to save a value is not available. However when you write aninstruction such as CALL Del-1, the current address of your program is placed on the stack sothe micro can come back to the next instruction, after it has executed the instructions at thesub-routine called Del-1.If you want to save a value in a register, you will need to load it into "w" and from w to one ofthe unused files, thus:

    movf the file with the value,0 to w such as 3A,0movwf the file that will save the value such as 4B

    e.g: movf 3A,0 ; (the value in file 3A gets copied into the working register)movwf 4B ; (the value in the working register gets copied to file 4B)

    PollSee also Switch The action of POLLING means to "look at - on a regular basis." It generally refers to aninput device such as switch or push button. A push button can be pressed and released inless than 10th second and this means it must be scanned or polled 10 times a second(100mS).This means you have 100,000 machine cycles available between "looks."

    Most programs consist of a Main routine and this is looped on a regular basis. As a programgets larger and larger, the Main routine may loop at a slower rate (mainly due to delay sub-routines needed for some of the operations) and you may exceed the 100,000 limit.The answer is to place the "look" feature inside the delay sub-routine. The following sub-routine has a "Look" feature inside a Delay:

    DelayDelay1NotDelay2Main

    MOVLW 01hMOVWF 2CNOPDECFSZ 2A,1GOTO Delay1BTFSS 05,0GOTO NotBSF 2F,0RETLW 00BCF 2F,0BCF 2F,1DECFSZ 2B,1GOTO Delay1DECFSZ 2C,1GOTO Delay1RETLW 00CALL Delayother instructionsBTFSS 2F,0GOTO Main

    BTFSC 2F,1GOTO MainBSF 2F,1CALL ActionGOTO Main

    ;Approx 300mS per "unit";Look at push-button line on port A;Button not pressed;Set button-press flag;Clear button-press flag;Clear "action" flag;Has button been pushed?;No.

    ;Yes. Has "action" already been performed?;Yes.;No.

    The Delay sub-routine includes instructions to look at a button and set a flag (BSF 2F,0) whenit is pressed.The micro comes out of the Delay routine with the flag SET. The flag is then looked at in Main

  • 8/7/2019 Library of Routines

    40/57

    and the appropriate sub-routine is executed.This sequence may be executed very quickly and the micro may return to Delay before thebutton is released. The "action" flag (BTFSC 2F,1) prevents the action being carried out morethan once for a single button-press.When the button is released, both flags are cleared.

    Pseudo Instructions - these are additional Instructions understood by MPASM:

    Mnemonic Description Equivalent

    Operation(s) Status

    ADDCF f,d Add Carry to File BTFSC INCF

    3,0 f,d

    Z

    ADDDCF f,d Add Digit Carry toFile

    BTFSC INCF

    3,1 f,d

    Z

    B k Branch GOTO k -

    BC k Branch on Carry BTFSC GOTO

    3,0 k

    -

    BDC k Branch on DigitCarry

    BTFSC GOTO

    3,1 k

    -

    BNC k Branch on No Carry BTFSS GOTO

    3,0 k

    -

    BNDC k Branch on No DigitCarry

    BTFSS GOTO

    3,1 k

    -

    BNZ k Branch on No Zero BTFSS GOTO

    3,2 k

    -

    BZ k Branch on Zero BTFSC GOTO 3,2 k -

    CLRC Clear Carry BCF 3,0 -

    CLRDC Clear Digit Carry BCF 3,1 -

    CLRZ Clear Zero BCF 3,2 -

    LCALL k Long Call BCF/BSF BCF/BSF CALL

    0x0A,3 0x0A,4 k

    LGOTO k Long GOTO BCF/BSF BCF/BSF GOTO

    0x0A,3 0x0A,4 k

    MOVFW f Move File to W MOVF f,0 Z

    NEGF f,d Negate File COMF INCF

    f,1 f,d

    Z

    SETC Set Carry BSF 3,0 -

    SETDC Set Digit Carry BSF 3,1 -

    SETZ Set Zero BSF 3,2 -

  • 8/7/2019 Library of Routines

    41/57

    SKPC Skip on Carry BTFSS 3,0 -

    SKPDC Skip on Digit Carry BTFSS 3,1 -

    SKPNC Skip on No Carry BTFSC 3,0 -

    SKPNDC Skip on No Digit

    Carry BTFSC 3,1 -

    SKPNZ Skip on Non Zero BTFSC 3,2 -

    SKPZ Skip on Zero BTFSS 3,2 -

    SUBCF f,d Subtract Carry fromFile

    BTFSC DECF

    3,0 f,d

    Z

    SUBDCF f,d Subtract Digit Carryfrom File

    BTFSC DECF

    3,1 f,d

    Z

    TSTF f Test File MOVF f,1

    Z

    Pull-upsThe PIC12F629 has individual pull-ups of about 47k on each line, that can be activated viathe following code. When a line is made into a input, the pull-up is not active, but is re-activated when the line is changed to output.Pin 4, GPIO,3 (GP3) is an INPUT-ONLY pin and does not have a pull-up.In the following instructions, GPIO,5 will have a weak pull -up. A push-switch is connectedbetween GPIO,5 and ground. When the switch is pressed, the input will go LOW. This iscalled an active LOW input. GPPU is an active LOW enable bit. It is written: GPPU. In theprogram it is identified as NOT_GPPU as the "Word" document does not overlines. When this

    bit is cleared (bcf), pull-ups are enabled by individual pot latch values.

    movlw b'11101000' ;Specify GPIO port directionmovwf TRISIO ;Set GPIO ports as xxIOIOOObcf OPTION_REGbcf NOT_GPPU ;enable weak pull-upbsf WPU, 5 ;enable wpu on GPIO 5 only

    Random numbersee also MaskA random number can be created by monitoring the TIMER file and looking at this file when aplayer has pushed a button.

    Get_Random movf tmr0,0andlw 0x03movwf 27hretlw 00

    ;Read the PIC's timer register and put it in W;mask all but bit0 and bit1 to get values 0,1,2,3.;move random number to file 27h (theRANDOM ; number file).

    To get a random number: 0-7, mask all but bits 0,1,2: andlw 0x07The random number file can be incremented if zero is not needed (this will be the secondinstruction in the sub-routine above) and then "andlw" is carried out.

  • 8/7/2019 Library of Routines

    42/57

  • 8/7/2019 Library of Routines

    43/57

    Data can also be added to the EEPROM section. This is 128 bytes of data and can bechanged up to 1 million times. The data will be kept when the power is removed.

    Remove bits see AND and Mask

    Return - not used for PIC12F629, use:Retlw 00This instruction must be somewhere in each sub-routine if the sub-routine has been CALLED.It is generally at the end, but quite often programming will create a Return part-way through aroutine. The instruction to use for a PIC12F629 is: retlw 00 to retlw 0FFhSee CALL and GOTO for more details.RETLW 00 to FF - Return with Literal in WA sub-routine can carry out an operation and set a flag. Alternatively it can return with a valuein W.If a sub-routine generates two or three different results, the RETLW 00 to FF instruction canReturn with the appropriate value in W.RETLW 00 to FF is used for each value of data in a Table. (see Table)

    RotateThis is the same as SHIFT. All the bits in a file are moved to the left or right through theCARRY.Carry is located in the STATUS file (03,0).It requires 9 shifts (rotates) to get the bits back to the original position.The CARRY must be cleared (BCF 03,0) if you don't want it to appear in the file.RLF (Rotate Left File) increases the value of the contents (doubles the value).

    RRF (Rotate Right File) decreases the value of the contents (halves the value).The following two instructions will rotate the contents of a file register without loosing data inthe "Carry Flag".Rotate right or left can be implemented. Note that the carry flag is changed.Enter with "abcdefgh" and leave with "bcdefgha"

    rlf Register, w ;Load Carry with the highest bitrlf Register, f ;Shift left

    orEnter with "abcdefgh" and leave with

    "habcdefg"

    rrf Register, w ;Load Carry with the lowest bit

    rrf Register, f ;Shift right

    SameTo find out if two numbers are the same, they are XORed together. See XOR andComparison

  • 8/7/2019 Library of Routines

    44/57

    SetUpThe first sub-routine in a program is SetUp. It sets the direction for each Input/Output line andclears any other files to get them ready for incrementing etc.To make a line INPUT or OUTPUT, see INPUT, OUTPUT.Instructions between BSF 03,5 and BCF 03,5 are dealing with files files in Bank 1. For

    instance, if files 05 is loaded with 02, this is actually the TRISIO file. This file controls thedirection of the Input/Output lines of GPIO and when it contains 0's, all the lines are output.Note: GP3 is input only

    SetUp

    ORG 0BSF 03,5MOVLW 02MOVWF TRISIOBCF 03,5CLRF 2FCLRF GPIOGOTO Main

    ;This is the start of memory for the program.;Go to Bank 1;Load W with 0000 0010;Make GP1 input;Go to Bank 0 - the program memory area.;Clear flag file;Clear GPIO of junk

    Shift see Rotate

    SLEEP This instruction puts the micro to sleep. This is also called "power-down mode."The micro stops executing the program when it comes to this instruction.If the Watchdog Timer is enabled, it will be cleared but will keep incrementing.

    The In/Out lines maintain the status they had before SLEEP was executed.For the lowest consumption in SLEEP, all output lines must not drive any circuitry before theSLEEP instruction.On-chip pull-ups must also be turned off to reduce the current consumption during SLEEP.The micro will wake up from SLEEP via one of the following:1. Taking MCLR pin LOW2. Watchdog Timer wake-up (if watchdog is enabled)3. Interrupt from GP2/INT pin4. GPIO change5. Peripheral interrupt.On wake-up from SLEEP, the WDT is cleared.When the SLEEP instruction is being executed, the next instruction (PC + 1) is pre-fetched.For the micro to wake up through an interrupt event, the corresponding interrupt enable bit

    must be set (enabled). Wake up is regardless of the state of the GIE bit. If the GIE bit is clear(disabled) the micro continues execution at the instruction afterSLEEP. If the GIE bit is set(enabled) the micro executes the instruction afterSLEEP then branches to the interruptaddress (004h). In the case where the instruction following SLEEP is not desirable, the usershould have a NOP after the SLEEP instruction.The TO and PD bits in the STATUS register can be used to determine the cause of RESET.The PD bit, which is set on power-up, is cleared when SLEEP is invoked. The TO bit iscleared if WDT wake-up occurred.The SLEEP instruction is:

  • 8/7/2019 Library of Routines

    45/57

    sleepTo send the micro to the "sleep_micro" sub-routine, the following instruction is needed:

    goto sleep_microThe simplest sub-routine forSLEEP is:

    sleep_microsleep

    To set GPIO 3 for wake-up from sleep: This has been tested in Greeting card "DecisionMaker"

    bsf status, rp0 ;Bank 1movf GPIO,0movlw b'00001001' ;must clear the GPIF flag!!movwf INTCONbsf IOC,3sleepnop

    bcf status, rp0 ;bank 0goto xxx

    If the Watchdog timer is enabled, the micro will come out ofSLEEP and goto main.The watchdog will reset after 18,000uS (18m) and wake the micro.If 18mS is too short, a prescaler can be added to increase the WDT time by 2, 4, 8, 16, 32, 64or 128. The maximum time is 18mS x 128 = 2.3secThe micro contains an 8-bit prescaler register that can be assigned to Timer0 or Watchdog.This prescaler register is not readable or writable.To set the prescaler to the WDT, bit 3 of the OPTION REGister must be set. The instructionis:

    bsf STATUS, RP0 ;select bank 1

    bsf OPTION_REG,3

    ormovlw b'xxxx1xxx'movwf OPTION_REG

    bcf STATUS, RP0 ;select bank 0

    The three lowest bits of the Option register set the timing for the WDT:

    bsf STATUS, RP0 ;select bank 1

    movlw b'xxxxx000'movwf OPTION_REG ;WDT timer = 18mS

    or:movlw b'xxxxx001'movwf OPTION_REG ;WDT timer = 36mS

    or:movlw b'xxxxx010'movwf OPTION_REG ;WDT timer = 72mS etc etc

    or:movlw b'xxxxx111'movwf OPTION_REG ;WDT timer = 2,304mS = 2.3 Seconds

    bcf STATUS, RP0 ;select bank 0

  • 8/7/2019 Library of Routines

    46/57

  • 8/7/2019 Library of Routines

    47/57

    Sleep

    movf GPIO,Wbcf INTCON,GPIFbsf STATUS,RP0movlw 0xFFmovwf TRISIOsleepnopmovlw b'11101000'movwf TRISIObcf STATUS,RP0movf GPIO,Wbcf INTCON,GPIF

    ; Read GPIO clears Int-On-Change flag. Must read; into W not back to F as it reads port not the output; latch which may result in output data being; inadvertently altered.; Sel bank 1; Setup W for TRISIO all input; Write to TRISIO. Reduce power in sleep mode; Go to sleep;; Wake from sleep and set; TRISIO for input and output foryour project; Sel Bank 0; Read GPIO register; and clear GPIF flag in interrupt register

    The following set of instructions have been tried in an Alarm project. Some of the instructionsmay not be needed and you can try deleting and testing for yourself. The most important pointto remember is this: The micro goes to ISR (address 04) after waking up from sleep and theinstructions at address 04 must be included:

    org 0goto setupnopnopnopnopgoto Enable

    SetUp movlw b'00001111' ;0001 1111

    movwf GPIO ;Make GP 0 HIGH and GP5 LOW for piezo & GP4 lowbsf status,rp0 ;Bank 1

    movlw b'00011110'movwf trisio ;Make GP1,2,3,4 input GP0,5 outputmovlw b'10000110' ;Turn off T0CKI, prescaler for TMR0 = 1:128movwf option_regbsf intcon,3 ;enable GPIO state change intbsf intcon,7 ;enable global interrupt GIEbsf IOC,4 ;enables interrupt on GPIO 4bcf status,rp0 ;bank 0movlw 07h ;Set up W to turn off Comparator portsmovwf CMCON ;must be placed in bank 0

    movf GPIO,w ;clears the Int-on-change flagbsf status,rp0 ;Bank 1bcf intcon,gpif

    bcf status,rp0 ;bank 0nopsleepnop ;micro goes to ISR at address 04!!!!!!!!!

  • 8/7/2019 Library of Routines

    48/57

    SThis isanareawhereup to

    d

    addressesareplaced. TheseaddressareRETURNaddress.ehena

    f

    Ag g

    ismade, theaddressof thenext instruction inyourprogram isplacedon theSTA

    f

    K.Themicrowill go to thesub-routineyouhave

    f

    Ag g

    ed. In thissub-routineyoucanhaveanother

    f

    Ag g

    .

    This is thesecondf

    Ag g . In thesecondsub-routineyoucanhaveanotherf

    Ag g . In fact thiscanbedoneup to

    d

    times.Ifmore than

    d

    addressareplacedon thestack, the first address is lost. That h swhyyoucannot havemore than

    d

    f

    Ag g

    s.ehenareturn ismade, the

    f

    Ag g

    numberisreduced.The PI

    f

    12F629canhaveaf

    Ag g

    instruction thatf

    Ag gsanothersub-routineand thesub-

    routinef

    Ag g

    sanothersub-routineand that sub-routinef

    Ag g

    Sanothersub-routineuntild

    f

    Ag g

    saremade.The

    d

    thsub-routinewill have aRETLWi i

    togoback the theprevioussub-routineandeachsub-routinewill haveaRETLWi i until finally themicroreturns toMain.Theanimationbelowshowsa

    f

    ALL inasub-routinef

    ALLinganothersub-routineand thissub-routine

    f

    ALLsanothersub-routine. TheP p q r p s

    mt q u v

    w

    x

    pmakes themicrocarryout

    the instructions.Note: Return isused in

    h y i

    d

    instruction-set andRetlwi i

    isused inh

    629 instruction-set

    :

    The PIf

    12F508or509hasonlya2-stack"and the low-cost PI

    f

    microreserved forhigh-

    quantityorders)hasonlya"2-stack." It is important torealise thissoyourprogramsareportable toothermicro's. Youcanhavea

    f

    ALL fromMainandaf

    ALL from thesub-routine,but thesecondsub-routinemust onlyhaveaRETLW00.

    S sees lso

    s

    iw

    . Themicrocontrollerdoesnot haveaS

    w

    op instruction.

    onot use theword"Halt"asa label,theassemblerdoesnot like it.UseLoop, Pause, Wait. SeeLoop.Tocreatea"waiting loop"use the following instructions:

    LoopNOP OTOLoop

    ;Hold themicro ina loop

    When testingaprogram, youmayneed toknow if themicrocontrollerhasadvanced toacertainpart of theprogram.

  • 8/7/2019 Library of Routines

    49/57

    Insert the instruction: GOTO Wait.Insert the following instructions. They should include an output to a LED etc so you can provethe micro has entered the loop.

    Wait NOPMOVLW 07h

    MOVWF GPIOGOTO Wait

    ;Hold the micro in a loop

    ;Output a HIGH to LEDs

    Store Data The PIC12F629 has two ways to store data.If you need to store only a few bytes of data for a short period of time, use files that are notrequired in any of the running of the program.This information will be lost when power is removed.If you want to store data permanently, the PIC12F629 has 128 bytes of EEPROM.This requires a special routine - found under EEPROM.

    Sound The following program produces a "rising Sound."

    soundsound1sound2sound3

    movlw 0F0hmovwf tempbsf GPIO,0movf temp,0movwf soundhighnopnopnopnopnopdecfsz soundhigh,1goto sound2bcf GPIO,0movf temp,0movwf soundlownopnopnopnopnopdecfsz soundlow,1goto sound3

    decfsz temp,1goto sound1retlw 00

    ;;Piezo bit HIGH;piezo bit LOW

    SUB The following SUBTRACT operations are available:

  • 8/7/2019 Library of Routines

    50/57

    sublw 00 - 0FFh - subtract w from literal -NOT subtract literal from wsubwf file,w - subtract w from file (result stored in w)subwf file,f - subtract w from file (result stored in file)

    Here is an example of the sub(tract) operation:

    movlw 0Eh - the value 0Eh is loaded into w

    movwf count - 0Eh is moved to a file called "count." This gets a value into a file.movf count,w - the value in "count" is moved to wsublw 0Fh - subtract w (0Eh) from literal (0Fh)

    0000 1111

    - 0000 11100000 0001

    Note: the last digit is INVERTED. This is a handy way to invert a digit.

    SWAP

    PIC language has a SWAP NIBBLES instruction. It swaps the HIGH nibble with the LOWnibble. Swapping INDF (file 00) actually swaps the nibbles in the file pointed to by FSR.

    SWAPF 2A,1 ;Before: File 2A = 81h After: File 2A = 18h

    SWAP THE CONTENTS OF TWO FILES Example: File 2C = 81h

    File 2D = 47hFile 2E = temp storage

    MOVF 2C,0

    MOVWF 2E,1MOVWF 2D,0MOVWF 20C,1MOVF 2E,0MOVWF 2D,1

    ;Move 2C to W

    ;Move W to 20E;Move 2D to W;Move W to 20C;Move 2E to W;Move W to 2D

    To swap the contents of two files without using a temporary file:

    movf X, wsubwf Y, waddwf X, fsubwf Y, f

    Another way to swap the contents of two files without using a temporary file:

    movf X, wxorwf Y, fxorwf Y,wmovwf Xxorwf Y, f

    ; Get X; Y is now X^Y; W is now (X^y)^X==Y (say OldY); Now X is OldY; finally Y is (OldX^Y)^Y==OldX

  • 8/7/2019 Library of Routines

    51/57

    SWAP THE CONTENTS OF A FILE WITH W Example: File 3C = 81h W = 47h

    after operation: File 3C = 47h W = 81h

    XORWF 3C,1XORWF 3C,0XORWF 3C,1

    Switch(button, key)see also Poll There is no difference between "Switch," "Button" and "Key." They all refer to a push buttonthat has momentary action. It can be an individual push button, one of a number of buttons orin a matrix of buttons such as a keypad.With all button instructions, there are three important things to remember. They aremechanical devices and their action is very slow in "microprocessor-time." They produce a lotof pulses when pushed and also when released (this is called switch-noise or switch-bounce).In any button routine, you must also prevent a button-press being registered more than once.Many sub-routines already have a switch or button feature included in them. Select anexisting sub-routine or use the following.The most important part of adding a switch or button routine is creating the debouncefeature.This is to prevent "double-counting" when the button is pushed or released. Try slow-pressingand slow-release to see if the program produces a false result. If the program "double-counts," you will have to increase the debounce-time.Debounce can take up a lot of computer-time. Debounce is a delay routine that "masks"(hides - or disallows) the time when the button is pressed or released, so that only one pulseis detected. Instead of producing a separate debounce routines, you may be able to use thetime taken to execute other sub-routines. In other words, the program looks before and afterthe execution of another routine and if the button is still pressed, the micro detects it as a"button-press."Finally, you need to detect the first press of a button and prevent the program operating onthe button during the second pass of the program.The basis of detecting a button-press consists of 6 separate items that must be placed in thefollowing order:There are two flags. Bit0 in file 1F is the Debounce Flag and Bit1 in file 1F is the ButtonPressed flag.The microprocessor executes Main and CALLs Sw. IfSw detects a key-press, two flags areSET. The first is the Button Pressed flag and the second is the Debounce flag.The micro returns to Main and tests the Button Pressed flag to see if it is SET. If is is SET,the micro goes to a sub-routine such as CALL Increment, where a value can be incremented.The Button Pressed flag is then cleared and the micro CALLs Sw. If the switch is stillpressed, the micro will return. The program is looking for the button to be released. When the

    button is released, the Sw sub-routine is ready to detect another button-push.

    SetUp

    BSF 03,5MOVLW 01MOVWF TRISIOBCF 03,5CLRF 2FGOTO Main

    ;Go to Bank 1;Put 01 into W;Make GP0 input;Go to Bank 0;Clear the button-press file

  • 8/7/2019 Library of Routines

    52/57

    SwSw1Sw2MainMain2

    BTFSS 05,0GOTO Sw2BTFSC 2F,0RETLW 00DECFSZ 2A,1GOTO Sw1BTFSS 05,0GOTO Sw2BSF 2F,1BSF 2F,0RETLW 00BCF 2F,0RETLW 00CALL SwBTFSC 2F,1GOTO Main2Display the valueson a display etc.GOTO MainCALL Increment

    BCF 2F,1GOTO Main

    ;Test the button. Button is "Active HIGH";Button not pressed;Button pressed first time? Test debounce flag;Button already pressed. Return to Main;Create short delay;Look again;Is switch still pressed?;It was only noise;Button Pressed. Set button-pressed flag;Set debounce flag;Return to Main;Clear debounce flag;Return to Main;Test button-press flag to see if button was pressed;Button pressed;Button not pressed;Increment the display. (you provide the routine)

    ;Clear the button-press flag

    Table seealso Output a Table Value and CALL Table Suppose you need to turn on LEDs to produce the pips on the side of a dice (die). This canbe done via a table.In a sub-routine, a value between 1 and 6 is created and put into "w" and Table is called thus:

    movlw 03h ;any value 1 - 6 is put into wcall Table ; the micro will go to the table and return with 5Bhmovwf temp1 ; 5Bh will be put into the temporary file

    To prevent the micro jumping beyond the end of the table, the instruction:

    andlw 06h is used when the table contains 6 elements.The layout for a Table is shown below:

    Table

    andlw 06hADDWF pcl,1nopRETLW 3Fh

    RETLW 06hRETLW 5BhRETLW 4FhRETLW 66hRETLW 6Dh

    ;this prevents micro jumping beyond end of table;Add W to the Program Counter to create a jump.;the micro jumps here for "movlw 00"

  • 8/7/2019 Library of Routines

    53/57

    Toggle The state of a line can be changed from High to LOW or vice versa to create a tone or otherfeature.The instructions below do not know the initial condition of the line. They simply reverses thestate. The instructions are:

    MOVLW 01hXORWF GPIO,1

    ;Put 01 into W;XOR 01 with GPIO, lowest line (GP0)

    The following instructions apply to the other lines.

    MOVLW 02hXORWF GPIO,1MOVLW 04hXORWF GPIO,1MOVLW 10hXORWF GPIO,1MOVLW 20hXORWF GPIO,1

    ;Put 0000 0010 into W;XOR 02 with GPIO, for GP1;Put 0000 0100 into W;XOR 04 with GPIO, for GP2;Put 0001 0000 into W;XOR 10h with GPIO, for GP4;Put 0010 0000 into W;XOR 20h with GPIO, for GP5

    Tonesee also Beep When a line is taken HIGH then LOW at a rapid rate, a tone is produced in a piezo orspeaker. A buffer transistor (amplifier) may be needed.The simplest tone takes a line HIGH, then executes a delay. The line is taken LOW and adelay is executed. This process is repeated. The following routine shows how a tone isproduced. The micro never comes out of the Tone sub-routine. It is only suitable as an "end

    of the line" sub-routine.

    Tone

    NOPDECFSZ 2A,1GOTO ToneMOVLW 02hXORWF GPIO,1GOTO Tone

    ;Put 02 into W;XOR 02 with GPIO. Toggle GP1

    To get the micro out of the Tone routine is must have a "duration." The pitch of the tone canalso be changed:

    ToneTone1Tone2

    MOVLW 10hMOVWF 2BMOVLW 02hMOVLW 2ANOPDECFSZ 2A,1GOTO Tone2MOVLW 02hXORWF GPIO,1DECFSZ 2B,1

    ;The duration of the tone or "beep";The length of HIGH and LOW - frequency of tone;Put 02 into W;XOR 02 with GPIO. Toggle GP1

  • 8/7/2019 Library of Routines

    54/57

    GOTO Tone1RETURN

    TRISIO also known as "tris"The file that determines the in/out state of each line (pin) for the in/out Port is the TRISIO file.It is located in Bank1 of the microcontroller. It has the value 85 for PIC12F629 to control theGPIO lines. For a PIC16F628 it is 85h for PortA and 86h for PortB. For the PIC10F200series, the tris register is not given an address number and is only accessed by the mnemonic"trisgpio"To access the tris register.GPIO has GP0, GP1, GP2, GP3, GP4 and GP5. Eg: MOVLW 0FFh will only affect the 6input lines of GPIO. Bits 6, and 7 of a value will not have any effect.There are two ways to get to the TRISIO file. It can be accessed directly by adding thefollowing two instructions directly into your program at any location:Note: We have found the instruction: movwf tris, DOES NOT WORK for some micros.Use the instructionsBSF 03,5 and BCF 03,5

    MOVLW 01hMOVWF TRISIOormovlw 01htris gpio

    ;Put 01 into W;Make GP0 an input and all others output;this instruction has been tested and works for 12F629

    The following instructions apply to the other lines: GP3 is input ONLY

    PortA:

    MOVLW 02hMOVWF TRISIO

    MOVLW 04hMOVWF TRISIOMOVLW 08hMOVWF TRISIOMOVLW 10hMOVWF TRISIOMOVLW 20hMOVWF TRISIOMOVLW 3FhMOVWF TRISIO

    ;Put 0000 0010 into W;Make GP1 an input and all others output

    ;Put 0000 0100 into W;Make GP2 an input and all others output;Put 0000 1000 into W;Make GP3 an input and all others output;Put 0001 0000 into W;Make GP4 an input and all others output;Put 0010 0000 into W;Make GP5 an input and all others output;Put 0011 1111 into W;Will make all input! (except GP3)

    The TRISIO file can also be accessed by inserting BSF 03,5 BCF 03,5 instructions into yourprogram.The BSF 05,3 instruction takes you to Bank1 where the TRISIO file is located. When inBank1, the TRISIO file is file 05. See: SetUp for details of the instructions to be insertedbetween BSF 03,5 and BCF 03,5.

  • 8/7/2019 Library of Routines

    55/57

    BSF 03,5movlwb'00000011'movwf trisBCF 03,5

    ;Go to Bank 1;Go to Bank 0 - the program memory area.

    Wait see also Stop. When testing a program, you may need to know if the microcontroller has advanced to acertain part of the program.Insert the instruction: GOTO Wait.Insert the following instructions. They should include an output to a LED etc so you can provethe micro has entered the loop.

    Wait NOPMOVLW 07hMOVWF GPIOGOTO Wait

    ;Hold the micro in a loop;output

    Watchdog Timer (WDT) The PIC12F629 has an inbuilt timer that increments all the time. It has a normal time-outperiod of 18mS (18,000 instruction-cycles). You cannot turn the timer on or off via theprogram. It is turned on (or off) during the burning of the program by setting WDT in the__config file.To turn the watchdog timer off: & _WDT_OFFTo turn the watchdog timer on: & _WDT_ONIf it is active (turned ON) the micro will go to 000 (reset) after 18,000uS.This action has a purpose.

    If a program is badly designed, it may "run off the end of the program" and start executing"junk" commands. A glitch may cause the micro to go to an incorrect part of a program tocause it to "Freeze." To prevent this from occurring, the WDT takes the micro back to thebeginning and starts the program over again.To prevent the WDT constantly resetting a program, the WDT must be constantly reset viathe instruction CLRWDT. This gives the programmer another 18,000 instructions beforehaving to reset the WDT.To keep WDT constantly reset, CLRWDT must be placed inside delays.Normal programming (experimenting etc) is carried out with WDT OFF.If 18mS is insufficient a prescaler can be added to increase the WDT time by 2, 4, 8, 16, 32,64 or 128. The maximum time is 18mS x 128 = 2.4sec

    Weak Pull-Up Resistors The PIC12F629 has inbuilt weak pull-up resistors (47k) for each of the 8 input lines. Theseresistors are ONLY enabled when any line is INPUT.To enable this feature:

    bcf OPTION_REG,7 ; enable weak pull-ups (Option_Reg address: 81h)(bank1)

    bsf WPU, 5 ; enable wpu on GPIO 5 only (WPU addNo weak pull-up available on GP3.

  • 8/7/2019 Library of Routines

    56/57

    XOR - XOR detects a MATCH!XOR is called exclusive OR.It means the only time the output of a gate is HIGH is when ONE (and ONLY one) of theinputs is HIGH.When two numbers are XORed together, the result is "1" when one (and only one) of the

    numbers is "1." [The OR function is called inclusive OR see IOR].To find out if two numbers are the same, they are XORed together. Since each binary digitwill be the same (i.e. either a 0 or 1) the result will be 0000 0000. The result will set the zeroflag in the status (03) file and by testing bit 2 (the Z flag) you can skip when SET.You also have to decide where you want the result to be placed. If you don't want the value ofthe file to be altered, the result should be put into W.Example: To see if file 2E holds the value 3C. (file 2E does contain the value 3C)

    MOVLW 3CXORWF 2E,0

    ;Put 3C in W;XOR 3C with file 2E and put the result into W.

    The micro will XOR file 2E with the value 3C.We know file 2E contains the value 3C, so the operation is:W: 0011 11001E: 0011 1100

    0000 0000 - this answer will be put into WIn this example, 3C is put into file 2E and the XOR operation is carried out:

    MOVLW 3CMOVWF 2EXORLW 3CBTFSS 03,2

    GOTO clearGOTO SET

    ;Put 3C in W:Put 3C into file 2E;XOR 3C with file 2E and put the result into W.;Test the Zero flag

    The zero flag will be set. (The zero flag is SET to show the answer is zero) i.e: a MATCH! andthe program will go to the line GOTO SET.

    Zero FlagThe zero flag is found in the STATUS register (file 03). It is bit 2. When the result of anoperations is zero, the zero flag is SET. In other words it is = 1.

    Zero a file A file can be made zero in two ways. To zero a file is the same as clear a file.The instruction CLRF 1A makes the contents zero.

    CLRF 2A ;Make file 2A zero.

    You can load 00 into W and move W to a file:

  • 8/7/2019 Library of Routines

    57/57

    MOVLW 00MOVWF 2A

    ;Put 00 into W;Make file 2A zero.

    Zero in a file(test for) To see if a file is zero, move it in and out of itself. The Z flag will be affected. If it is SET, the

    file contains 00h.

    MOVF 2A,1BTFSS 03,2______________________

    ;Move 2A in and out of 2A;Test the zero flag;Micro goes here if 2A is NOT zero;Micro goes here if 2A is zero.