PSECT udata_acs ;  Use RAM memory
global Val1, Val2, temp, gcd; Global access
Val1:  DS 1   ; Assign one byte to val1
Val2:  DS 1   ; Assign one byte to Val2
temp:  DS 1   ; Assign one byte to temp
gcd:   DS 1   ; Assign one byte to temp


PSECT code
main:
    MOVLW 0x0F    ; 0x0F -> WREG (15 decimal)
    MOVWF Val1    ; WREG -> Val1 (Val1 = 15)
    MOVLW 0x0A    ; 0x0A -> WREG (10 decimal)
    MOVWF Val2    ; WREG -> Val2 (Val2 = 10)
    
    MOVF Val1,W   ; Val1 -> WREG
    MOVWF Ux      ; WREG -> [Ux]
    MOVF Val2,W   ; Val2 -> WREG
    MOVWF Vx      ; WREG -> [Vx]

gcd:
    MOVF Vx, W                  ; [Vx] -> WREG
    BZ final                     ; check if [Vx] == 0 if true go to final

    
    MOVFF Ux, temp		; [Ux] -> temp
    MOVF Vx, W                  ; [Vx] -> WREG
    CALL remainder              ; caluating the remaninder and calling the remainder subroutine

    MOVFF Vx, Ux                ; [Vx] -> [Ux]
    MOVFF temp, Vx              ; [temp] -> [Vx]
    BRA gcd                     ; Go back to start of loop
    
remainder:
    SUBWF temp, F               ; temp - [Vx] -> temp  repeated subtraction of [Ux] from [Vx]
    BC remainder		; Carry = 1 the subtraction is positive and continue subtracting
    ADDWF temp, F               ; If Carry = 0 the subtraction is negative and we stop , [Vx] -> temp
    RETURN                      ; Return from subroutine
final: MOVFF Ux, gcd            ; [Ux] -> [gcd]
done: goto done			; All done


PIC microcontrollers are a very useful and versatile tool for use in many electronic projects. They are very inexpensive and easy to find. They are also very powerful and many are capable of speeds up to 64 MIPS using the internal oscillator block, about 16 times faster than most comparable AVR microcontrollers. PICs are also easy to program, however getting the project set up can some times be tricky. These instructions will walk through the process of setting up the software, creating a new project, and programming some very simple functions to test the configuration and ensure everything is working. They are designed to be very open ended; after the project is created and the basics are finished the reader is encouraged to explore all the features and extras not covered in these instructions. Also you will find that these instructions will start out walking through step by step, but as the instructions near the end the reader is encouraged to explore other ways of accomplishing the tasks and make the project their own.
What you will need To build a project with a PIC microcontroller only requires a few items.
 PIC microcontroller
 These instructions are for programming a PIC18F series MCU, although others are similar.
 Obtained from Microchips website.
 Microchip allows students with valid .edu email addresses sample PIC's for free!
 The PIC I am using to create these instructions is a PIC18F22K80
 PICkit 3 In-Circuit Debugger
 Available from Microchip.
 Costs $45 for general public, and #34 with student discount if you have an .edu email address.
 There are also other programmers which will work just as well; however, this is the best one for starting out.
 Breadboard and breadboard wires
 LEDs, buttons, potentiometers, or anything else you would like to connect to the PIC
Step 1: Build Hardware

 Build Hardware
Before doing any programming the first step is to build the hardware. Although the PIC18F portfolio is very large, many of the chips have several commonalities. For more detailed information see the "Guidelines for Getting Started with PIC18Fxxxx Microcontrollers" section in your devices datasheet. For detailed pin-outs of the PIC microcontroller see the "Pin Diagram" section in your devices datasheet.

Note: VDD = Positive Voltage and VSS = Ground.
 Connect the MCLR pin through a 1kΩ resistor to VDD.
 Connect a 0.1μF capacitor between every pair of adjoining VDD-VSS pairs or AVDD-AVSS pairs.
 Connect a 10μF capacitor between VCAP and Vss.
 Connect MCLR pin to pin 1 of the PICkit 3.
 Connect VDD to pin 2 of the PICkit 3.
 Connect VSS to pin 3 of the PICkit 3.
 Connect PGD pin to pin 4 of the PICkit 3.
 Connect PGC pin to pin 5 of the PICkit 3.
 Leave pin 6 of the PICkit 3 unconnected.
 Connect any analog inputs to pins with ANx functionality where x is a number.
 Connect any digital inputs or outputs to pins with Rxy functionality where x is a letter identifying the port, and y is a number identifying the bit.
For my example I have an LED connected between RA0 and ground, the wiper of a potentiometer connected to AN1, and a DPST switch connected to RA2. You may find it easier to program the PIC if you have sketched down a schematic of your circuit.
Step 2: Get Software

 Get Software
 Get Software
 Get Software
These instructions will use XC8 compiler and MPLAB X IDE by Microchip. This step will explain how to get these tools and ensure they have been installed correctly.
 To get the latest version of the software visit Microchips website at http://www.microchip.com/pagehandler/en-us/family/mplabx/
 Select the software for your OS and follow the standard installation instructions.
Note: If you are using Windows 8 you may need to run the installers in compatibility mode for Windows 7.
 Once the software is installed, start MPLAB X
 In the menu bar select Tools->Options
 In the Options dialog select the Embedded tab and ensure XC8 is listed in the Toolchain list.
 If it is listed select OK and move on the next step.
 If it is not listed ensure that instillation has completed, and click Scan for Build Tools button.
 If still not listed, look on Microchips forum for help with your specific problem.
Step 3: Create New Project

 Create New Project
 Create New Project
 Create New Project
 Create New Project
In this step we will create a new project based on a template from Microchip.
 On the menu bar select File->New Project...
 In the new file dialog box expand Samples and select Microchip Embedded
 In the project box select PIC18 C Template
 Select Next
 Give the project any name you like
 Choose a location to save the project to in the Project Location box
 Leave the Project Folder as default options
 Check "Set as Main Project" box
 Select Finish
The project will now show up in Project Explore on the left hand side of the screen.
Step 4: Build Parameters

 Build Parameters
 Build Parameters
 Build Parameters
 Build Parameters 6 More Images
Before we can get started programming we need to set the build parameters.
Create Configuration
 Right click on the project name in the projects tool bar.
 In the Project Properties dialog select Manage Configurations...
 In the Configurations dialog select New
 In the New Configuration Name dialog enter Default and click OK
 In the Configurations dialog make sure Default is selected and click Set Active
 Click OK in the Configurations dialog
Set Configuration Properties
 In the Project Properties dialog select "Conf: [Default]" in the Categories list
 In the Device box type the name of the device you are using. In my case PIC18F26K80
 In the Hardware Tools list select PICkit3
 In the Compiler Toolchain select XC8 (v...) Where ... is the version you have installed.
 Select Apply
 Under Conf: [Default] select PICkit 3
 For Option categories select Power
 Check "Power target circuit from PICkit3
 Select Apply.
 Under Conf: [Default] select XC8 compiler
 For Option categories select Optimizations
 Set "Optimization Set" to "none"
 Select Apply
 Click OK to close the dialog box
Test the Configuration To test the configuration click the clean and build button (the one with the hammer and broom). Text will start scrolling in the output window at the bottom of the page. If everything is successful the this text will say BUILD SUCCESSFUL (total time: ...). If you get an error, go back through this step making sure that you did not miss anything, and that everything was applied.
Step 5: Set Configuration Bits

 Set Configuration Bits
 Set Configuration Bits
 Set Configuration Bits 2 More Images
The next step is setting the configuration bits. The configuration bits tell the MCU its initial conditions for when it turns on. They are used to set the clock source and speed, watchdog time configuration, and other similar features. Configuration bits are device dependent, so check the data sheet for the chip you are using for more information.
 In the project explorer expand Source Files and open configuration_bits.c
 Remove all the text below the #endif line
 Notice a new tab has opened at the bottom of the screen
 Set the bits as needed for your project. Since these are chip dependent, check the data sheet for more information about what each does. Some common settings follow:
 Extended Instruction Set -- Should be set to OFF when using template
 Oscillator -- Used to select the processor. Unless you are using an external crystal, leave set as Internal RC oscillator. See data sheet for other oscillator configurations. Note: CLKOUT will allow for easier debugging, and should be turned on if available.
 PLL Enable -- Will allow for future use of the PLL. Note: this will not turn on the PLL, it will only enable it. It is recommended to enable it.
 Watchdog Timer -- The watch dog timer is used to ensure the processor will not lock up. It however makes it much harder to debug. It is recommended to disable it while initially programming, and only enable it after the project is nearly done.
 Code/Table Write/Read protects -- Used to disable writing or reading to certain ranges of memory. Leave all of these disabled.
 If unsure about a setting, it is usually safe to leave it default.
 After all configuration bits have been set, click the "Generate Source Code to Output" button at the bottom of the panel.
 The panel will now switch to the Output tab. Select all the text in this tab and copy it to the clip board
 Paste it at the bottom of the configuration_bits.c file and pres save.
 Clean and build the project again by clicking the broom and hammer icon.
 Ensure the build was successful. Also check to make sure there was no errors in the output
If everything has worked move on to the next step. If there are errors or warnings fix them before moving on.
Step 6: Configure Oscillator

 Configure Oscillator
 Configure Oscillator
 Configure Oscillator
The next step is to start programming; however, before we get to the application code we must program the system code. The system code are the low level functions such as configuring the oscillator and basic delay functions.
Determining Settings
Before we can program the settings, we must choose what speed we would like to run at. For this example I will use 16MHz as most PIC's can run at this speed. For my configuration I will use the 4MHz postscaller from the HF-INTOSC, and the 4x PLL giving an output frequency of 4MHz*4x=16MHz
 In the datasheet find the section labeled Oscillator Configurations
 The first thing listed in this section is Oscillator Types. If you are using the internal oscillator then use the settings relating to INTIO1
 On the next page or two you will find a schematic drawing of the oscillator similar to the one shown. It is helpful to trace the signal on this drawing to ensure the correct speed is being selected.
 The next step is to program these settings to the MCU. This is done by setting registers. The first register to set is OSCCON.
 IDLEN -- used to control the action of the sleep command. Can be left as default.
 IRCF -- Oscillator selection. Since I am using HF-INTOSC/4 (4MHz) I will need to set this to a binary value of 101
 OSTS -- Read only bit
 HFIOFS -- Read only bit
 SCS -- clock select bits. Since I am using the internal oscillator, I will set to 1x where x can be 0 or 1
 The next register is OSCCON2; however, this register is mostly read only and not important at this point
 The last oscillator configuration register is OSCTUNE. We will not tune the frequency for this project, however we must use this register to turn on the PLL using the PLLEN bit.
Applying Settings
 Return to MPLAB
 In the project explorer under Source Files open system.c
 At the bottom of this file is the function ConfigureOscillator. Remove the comments in that function.
 To set the bits of a register type in all caps the register name, followed by the lowercase word bits and then a period and the bit name.
 To set the bits follow that with an equal sign. To use binary type 0bXXXX where XXXX is the binary number. Lastly end the line with a semi-colon.
 Set all the bits as determined above for the OSCCON register. Example: OSCCONbits.IRCF = 0b101;
 Do the same for all other needed oscillator registers. See below for an example of a finished ConfigureOscillator function.
 When finished build and check for warnings/errors

/** * Configure the clock source and speed */void ConfigureOscillator(void){
    OSCCONbits.IRCF     =0b101;
    OSCCONbits.SCS      =0b00;
    OSCTUNEbits.PLLEN   =0b1;}
Step 7: Wait Milli-Second Function

One of the most useful functions is wait_ms. This however is not a function in the standard library, and will need to be programmed by you. For this implementation there will be a loop which will hold the processor until the given time has passed.

PIC18F microcontrollers need 4 clock cycles to execute one line of assembly code. Therefore with a clock of 16MHz, lines will be executed at 4 million lines per second = 4000 lines per milli-second. Since a for loop will take one instruction each time for the comparison, and two for the operation one for the body of the loop, it will work perfectly. We just need the for loop to loop 1000 time per milli-second.
 In system.c create a new function at the bottom of the file of type void wait_ms(uint16_t time)
 Below is the completed function
/**
 * Wait for a given number of milli-seconds using busy waiting scheme.
 * @param time - time in ms to wait.
 */
void wait_ms(uint16_t time)
{
    static long timel = 0;
    timel = time * 1000l;
    for( ; timel; timel--);// no initial condition, while time is >0, decrement time each loop
}
 Open system.h in the Header Files folder in the project browser
 At the end add the line void wait_ms(uint16_t); to prototype the function.
 Change line 8 from 8000000L to 16000000L
 Build and check for errors/warnings


there are the errors of the build

make  -f nbproject/Makefile-default.mk dist/default/debug/gcd.X.debug.elf
make[2]: *** [nbproject/Makefile-default.mk:101: build/default/debug/newAsmTemplate.o] Error 1
make[1]: *** [nbproject/Makefile-default.mk:85: .build-conf] Error 2
make[2]: Entering directory '/Users/apple/MPLABXProjects/gcd.X'
make: *** [nbproject/Makefile-impl.mk:39: .build-impl] Error 2
"/Applications/microchip/xc8/v2.50/bin/xc8-cc" -c  -mcpu=18F452  -D__DEBUG=1  -mdebugger=none   -mdfp="/Applications/microchip/mplabx/v6.20/packs/Microchip/PIC18Fxxxx_DFP/1.6.159/xc8"  -fno-short-double -fno-short-float -memi=wordwrite -O0 -fasmfile -maddrqual=ignore -xassembler-with-cpp -mwarn=-3 -Wa,-a -DXPRJ_default=default  -msummary=-psect,-class,+mem,-hex,-file  -ginhx32 -Wl,--data-init -mno-keep-startup -mno-download -mno-default-config-bits -std=c99 -gdwarf-3 -mstack=compiled:auto:auto:auto   -o build/default/debug/newAsmTemplate.o  newAsmTemplate.asm 
newAsmTemplate.asm:12:: warning: (1522) RAM access bit operand not specified, assuming banked memory
newAsmTemplate.asm:14:: warning: (1522) RAM access bit operand not specified, assuming banked memory
newAsmTemplate.asm:16:: warning: (1522) RAM access bit operand not specified, assuming banked memory
newAsmTemplate.asm:17:: warning: (1522) RAM access bit operand not specified, assuming banked memory
newAsmTemplate.asm:18:: warning: (1522) RAM access bit operand not specified, assuming banked memory
newAsmTemplate.asm:19:: warning: (1522) RAM access bit operand not specified, assuming banked memory
newAsmTemplate.asm:21:: error: (845) symbol "gcd" defined more than once
newAsmTemplate.asm:22:: warning: (1522) RAM access bit operand not specified, assuming banked memory
newAsmTemplate.asm:27:: warning: (1522) RAM access bit operand not specified, assuming banked memory
newAsmTemplate.asm:35:: warning: (1522) RAM access bit operand not specified, assuming banked memory
newAsmTemplate.asm:37:: warning: (1522) RAM access bit operand not specified, assuming banked memory
newAsmTemplate.asm:17:: error: (800) undefined symbol "Ux"
newAsmTemplate.asm:19:: error: (800) undefined symbol "Vx"
(908) exit status = 1
make[2]: Leaving directory '/Users/apple/MPLABXProjects/gcd.X'

BUILD FAILED (exit value 2, total time: 417ms)