Posts tagged ‘programming’

Conditional Jumping in PIC16 Assembly

PIC Microcontrollers have a funky way of handling conditionals. I’d like to present a set of macros I’ve made to make this easier to use, as well as explain the basics behind the technique in general.

Most MCU’s I’ve worked with before PICs had nice simple conditional statements… The mnemonic was usually to the effect of “branch if x to destination”. Not so on the PICs.

On a PIC, we have to do an operation between the data to test, then either skip the next instruction or not, based on the results of this test.

Take the instruction “BTFSS” meaning “Bit-test F, Skip if Set”. This instruction takes a register and a bit number, and will jump over the next instruction if that bit number in the register is set. For example:

We have 2 registers, REG1 and REG2. We want to know if the value in REG1 equals the value in REG2. A quick, simple way to do this is first to load one into W, then subtract the other from it, with the result going in to W as not to destroy one of the variables. This sets the “ZERO” bit in the STATUS register to either 1 if the operation resulted in a 0, or 0 otherwise. We know if the operation resulted in 0 the two values are equal, so we can code like so:

  movf REG1, w
  subwf REG2, w
  btfss STATUS, Z
    goto NOTEQUAL
  ; they were equal
  ; they weren't equal

So we can test for equality.

We can also macro-ize it for ease of use…

BEQ macro REG1, REG2, DEST	; branch if REG1 == REG2
  movf REG2, W			; W <- REG2
  subwf REG1, W			; W <- REG1 - REG2
  btfsc STATUS, Z		; if result was nonzero: skip out
    goto DEST			; otherwise jump

This gives us a macro we can call with 2 registers and a destination, and have it jump there if the condition ends up being true, and just pass on through if it’s not true. Much, much easier to use.

The other tests: inequality, less than, greater than, less than or equal to, greater than or equal to and so on follow a similar pattern. They are all covered in the “” file I use quite often. I have both register-register comparisons and register-literal comparisons in there. Feel free to grab a copy and use it in your next project.


PIC buttons (interrupt-based)



Previously, in PIC buttons (polling) we saw how to poll for the state of a line connect to a button, that is all fine and good but really that is not the best way to do them. The “real” way to interface with external components like that is through interrupts, a slick feature.

Interrupts provide you with lots of freedom in your code. They allow you to sit back, relax, and be told when an event occurs, and not be forced to sit and wait for it to happen.

For this program, the schematic and circuit are practically the same, the only thing that changed location is the button.

Instead of looping over and over again, we simply wait, using a goto $ we are essentially goto’ing the same address over and over, “goto here, goto here, goto here…” ad nauseum. A common technique is also to use a SLEEP command, which puts the PIC in a low power mode and halts the program counter. Same effect to the user though. You of course could do ‘real’ work too instead of just burn cycles.

Once the button is pressed and released, the PIC will generate an interrupt, forcing the program to goto memory location 4. This is labeled in the code as ISR (Interrupt Service Routine).

For this program we are using the RB0/INT Interrupt. This interrupt occurs when there is a low-high change in PORTB,0. It can also be configured for high-low as well.

To enable this, we set INTCON,INTE. This bit says we want to know if a change occurs. To enable interrupts in general, we must then set INTCON,GIE. This lets all enabled interrupts occur.

We then wait for the interrupt. Once it occurs, GIE is automatically cleared so we can’t have them inside each other, and blink the LED a couple times. We then clear the interrupt flag, saying we’ve handled the interrupt (INTCON,INTF). We then re-enable interrupts and return from the interrupt: retfie.

It should be noted that if we were using more than one interrupt type, we would have needed to check the flag bits to find out which one interrupted us. We then handle it, and clear its flag. The PIC is somewhat crippled in this manner. Any and all interrupts generated and thrown into address 4 and “we” have to figure out which one occured. Many higher end MCU’s will have a table of addresses to jump to for each particular interrupt type, we then code in each location the correct routine and the processor knows which to call based on what happens.


PIC buttons (polling)


Polling for button input, how useful! This is pretty brief and gives a good idea how to let buttons control your programs execution.

In this tutorial I’ve switched from using an oscillator to using a crystal. This changes the design a bit. Using the 2 OSC pins, OSC1/OSC2 (CLKOUT/CLKIN) they hook to the crystal in parallel. Then the two sides of the crystal are connected to ground via two capacitors, in this case 18pF. The speed and capacitance needed varies, and can be seen in most any PIC MCU datasheet as to how to lay it out. It will also be in my schematic.

Please note this is essentially NO DIFFERENT than the oscillator. It is simply a different means of providing a clock signal. You can swap in the oscillator to the normal CLKIN pin and it will work just fine.

For this program, we’ll start the processor, and wait for a button to be pressed. After it has been pressed we’ll essentially execute the LED blinker from before.

Polling is extremely simple. Polling is the act of checking something for a certain state to occur. In our case, we poll PORTB,4 waiting for it to go low. Once it does, we continue on and start blinking.

Circuit Image

Circuit Image

Another topic that needs to be covered is that of Pull-Up resistors. In order for a button to be able to change from 0 to 1 (Ground to 5V) we need a way to protect everything from a short circuit. We do this with a Pull-Up (or Pull-Down in some cases) resistor. For our case, we connect PORTB,4 to +5V via a 10k resistor. So when we fire up the program, the PIC sees PORTB,4 as HIGH. We then connect our button to PORTB,4 on one side, and Ground on the other. Now, when we press the button, PORTB,4 is connected to ground and is now LOW. A short circuit between +5 and Ground would occur if not for the resistor, which being 10k limits the current to a measly 500uA, nothing to worry about. Once the button is released, Ground is disconnected and the pin returns to a HIGH state.

Reading the code, you may also notice the _BANK macro has changed a bit. I’ve simply modified it to encompass all possible BANK configs instead of using 4 different macros for each. Reading through it can give you a little insight as to how the conditional assembler works. It’s a bit like C/C++ and a bit like BASIC. Quite nice and handy.

A final new bit is the _MCLRE_OFF in the __CONFIG line at the beginning. This frees us from having to pull _MCLR high to keep from a RESET condition. Just keeps our parts count down. :)

Now for the new section of code.

  btfsc PORTB,4
    goto $-1

That’s polling, yup, that’s it. All it is doing is a bit test on PORTB,4, waiting for it to become clear (Ground). The goto line is telling it to go 1 instruction back ($ means the address of the current instruction, $-1 means one before, the btfsc). Once that pin becomes 0 it skips the loop forcing it to check, and lets it continue on down to the blinker!


PIC LED blinker (busy-wait)

LED blinker #1 circuit schematic


Beyond all doubt, the #1 beginning program in microcontrollers is the LED blinker. It’s super simple, and teaches the concept of pin voltages and busy-waits. Here is a busy-wait LED blinker program, and a walkthrough building it in MPLab.

First, the delay. This is a busy-wait delay program, busy-wait means you just burn instruction cycles for the delay, keeping the MCU “busy”. There’s a tiny bit of math behind them. First, the clock speed is 20MHz, the instruction frequency is (clock/4) so our instructions are executing at 5MHz. This gives us a period of 200ns per cycle.

I created two delay functions, for versatility, and for LCD stuff which will come later but it’s handy here. One is a “DELAY_US” which will delay a specified amount of microseconds. This is done by wasting 5 cycles (5*200ns = 1us) a specified amount of times (less than or equal to 255us, since I only made an 8-bit “delay” variable). We can learn the cycle times from the data sheet, and make it work from there.

Next, I created a “DELAY_MS” which delays a specified amount of milliseconds. Same 8-bit limitation of max 255ms, but that’s enough to have fun with… It simply calls DELAY_US a few times with specified amounts of delay, adding up to 1000us (=1ms) and repeats as many times as we tell it to.

These delays are used to make the LED blinking visible, otherwise it would blink faster than we could see (if at all, it takes a cycle or two for the pin to change state so it might not even change if we just toggle it every other cycle).

Here’s a little more PIC architecture information. The PIC’s data registers are broken into “banks” (bank 0, 1, 2, 3). Meaning you cannot get at them all at the same time, although some are mapped to all banks so you CAN get at them, important ones. We usually hang out in bank 0… This usually isn’t a problem, just something you need to remember. The data sheet illustrates it pretty well. When it comes up I’ll clarify things about it.

Also, for the I/O pins. Since they’re bi-directional, you need to choose which direction to set them to. Input or output. This is done by setting the tri-state register for the given port, for example PORTA’s tris register is called TRISA (not tough!). You set the direction of a specific bit, by setting the bit of the TRIS register to either 0 or 1, 0 meaning OUTPUT and 1 meaning INPUT. Not tough to remember: 0 = Out and 1 = In.

Source Code

Ok, first you need to make sure you have MPLab from

Once you have MPLab, download the LED Blinker (busy-wait) source code.

MPLab is a nice IDE, you’ll need to create a “project” and then pick your chip, and add the asm file to it (called a “node”). All code is going to be indented 2 spaces, labels will not be indented at all, assembler directives are either 1 or 2 spaces in…

First few lines are kinda simple, the title directive just sets a title for your project…

 title  "LED Blinker Tutorial 1"

LIST R = DEC sets the default “radix” for the program, meaning the number base. So if I put 100 in a line somewhere, it means 100 DECIMAL. If I changed it to LIST R = HEX, then if I put 100 in somewhere, it means 0x100, TOTALLY different. I find DEC easier to work with, and you can still use 0x whatever and it means HEX so you get the best of both worlds.

Next we INCLUDE the “” which will give us nice little names for our registers so we don’t need to remember their addresses, how nice of Microchip.

Then the __CONFIG line, arguably the ugliest line of code while still being fairly simple. You can see the list of __CONFIG’s in the “” file, they’re simply setting the configuration of certain chip features, the ones I have listed do this: _CP_OFF copyprotect OFF, you can set the copyprotect bits to make your chip unreadable, this is only good for a production product, don’t use it. _WDT_OFF, watchdog timer off, watchdog timer is there for mission-critical applications, it’s constantly running and needs to be reset constantly, if it isn’t reset it will reset the chip (assuming your program has locked up), we don’t need it here. _HS_OSC specifies a high speed oscillator, it’s in the data sheet. _PWRTE_ON turns on the power up timer delay, it’ll make the MCU wait a bit before executing to make sure voltage is stable, oscillator is stable, etc… _LVP_OFF – low voltage programming, dun’need it… _MCLRE_ON makes us hold MCLR high, instead of letting the chip do it…

; Variable declarations
 CBLOCK 0x20
DELAY,DELAYTMP			; delay function variables...

Now to the variable declarations, the CBLOCK directive lets us just list out our variable names, and the assembler will assign addresses for us, this is handy. The 0x20 is the starting address of general-purpose registers in BANK 0. We list em out, then end it with ENDC.

; Macro declarations
BANK0 macro           		; Switch to BANK0
  bcf STATUS,RP1
  bcf STATUS,RP0
BANK1 macro           		; Switch to BANK1
  bcf STATUS,RP1
  bsf STATUS,RP0
  movlw TIME
  movwf DELAY
  call DELAY_MS
  movlw TIME
  movwf DELAY
  call DELAY_US

Next the Macro’s… Macro’s are one of the coolest features of MPLab, it’s kinda like an inline C function, and kinda like a #define. When called, the code is dumped into where it was called from, but you can use variables in it, and even arguments to customize it’s compiling, stuff I’ll show in later programs.

Anyways, you make one by saying: NAME macro in the first column, then code. End it w/a endm. The ones I have are fairly simple and re-usable. BANK0 sets the bank bits to get us into BANK 0, go figure. BANK1 sets them to get us into BANK1, crazy!

DELAY_MILLI takes the TIME argument and loads it into W, next it moves W to the register labeled DELAY. Then it calls our illustrious DELAY_MS function which will be explained in detail down below… DELAY_MICRO does the same damn thing with DELAY_US!

; Program code
 org 0
  goto MAIN
 org 4
  ; interrupt handler

PAGE is a pagebreak for printing, though it doesn’t work for me. :)

org 0 tells the assembler to start assembly at address 0, our first instruction is to jump (goto) the label MAIN.

org 4 starts us in the Interrupt address of PIC’s… This is kind of strange and will be explained later on, for now just accept it as fact…

And if you’re wondering if we lost space for 3 instructions between 0 and 4, you’re right. :)

; Subroutines
DELAY_US			; busy wait of DELAY us
				; 200ns instruction period assumed
  nop				; (1)
  nop				; (2)
  decfsz DELAY,f		; test DELAY count (3)
    goto DELAY_US		; loop if not done (4,5)
  return			; gtfo (4,5)
DELAY_MS			; busy wait of DELAY ms
				; dependant upon DELAY_US being accurate
  movf DELAY,w
  movwf DELAYTMP		; save DELAY time
DELAY_MS_LOOP			; inner loop
  movlw 245			; load 245 (1)
  movwf DELAY			; into DELAY (2)
  call DELAY_US			; wait 245us (3-249)
  movlw 245			; load 245 (250)
  movwf DELAY			; into DELAY (251)
  call DELAY_US			; wait 245us (252-498)
  movlw 245			; load 245 (499)
  movwf DELAY			; into DELAY (500)
  call DELAY_US			; wait 245us (501-747)
  movlw 246			; load 246 (748)
  movwf DELAY			; into DELAY (749)
  call DELAY_US			; wait 246us (750-997)
  decfsz DELAYTMP,f		; test DELAYTMP count (998)
    goto DELAY_MS_LOOP		; loop if not done (999,1000)
  return			; gtfo (999,1000)

Next we have our subroutines, the delays, I have these before the main lines of code just out of habit, it’s not required.

DELAY_US… Pretty simple really, we start out by burning 2 cycles, so we’ve waited 400ns so far, next we decrement our counter, and test if it’s zero, if it isn’t, we goto DELAY_US, looping again, if not, we return. The test itself takes one cycle (600ns so far) and either the goto or return take 2 cycles (1000ns = 1us) so we have our microsecond delay!

DELAY_MS works on the same principle, it’s accurate enough for this! :)

; Mainline of code
  bcf TRISA,2			; PORT A, bit 2 is our output pin.
  bsf PORTA,2  			; set her.
  DELAY_MILLI 250		; wait 1/4 sec
  bcf PORTA,2			; clear her!
  DELAY_MILLI 250		; wait 1/4 sec!!!!
  goto LOOP_BEGIN		; forever... :o

MAIN is our label for the beginning of the code, jumped to by the first line up @ org 0. BANK1 gets us into BANK 1 so we can set our bit direction, we clear bit 2 of TRISA making bit 2 of PORTA our output pin, then we hop back to BANK 0…

Then our introductory programming teachers worst nightmare, a purposely created infinite loop. We label the beginning, then set our pin high, shutting off the LED (as you’ll see in the wiring diagram). We wait 250ms via our handy delay function, then clear the bit, turning the LED on, we wait again and loop ad nauseum.

‘end’ tells the assembler to give up…


Alright, so we have our program, we run the assembler by clicking the weird funnel icon or by going to Project -> Build Node (or All). It’ll crunch and come up with no errors (of course).  Then just toss it into the programmer and feed the chip your tasty code.


The assembled circuit

The assembled circuit

Wire up the circuit as in the schematic at the top of the page. Hopefully it illustrates to you why the LED is on when the bit is off, and off when the bit is on… The LED is a typical ~2V yellow LED… Wired up it should look something like the image.


Hook up +5V and Gnd, and fire it up! If everything is set up correctly you’ll get a steady blinking LED!

Something to try

Connect a momentary switch to the _MCLR line, wired to Ground on the other side. Pushing the button will reset the chip, releasing it will start it over from the beginning of the program, of course it will do the same stuff, but this demonstrates how the reset buttons work. I also highly recommend changing the code to add a more interesting blink pattern, longer/shorter delays, and other stuff to get used to modifying code…


The PIC16 instruction set

The instruction set is your window into controlling these chips to do your bidding. Knowing what the chips understand helps you come up with a plan of attack to solve your particular problem.

We need to get some basic info out of the way. The way variables are handled are through registers, these are 8-bit data buckets in the MCU. Also, the PIC’s used here are loosely an Accumulator based architecture, meaning most all operations have one destination, the accumulator known as the W register in PIC land, although you can usually redirect the result to a register… Your other registers are in the “register file” which is your data RAM.

Alright, now we’re getting to the interesting stuff. The instruction set is the list of all commands that the MCU understands. I’ll list them out and briefly describe what they do and what they are used for.

There is also a STATUS register in this chip, various bits of it respond to various operations. Consult the datasheet for more information on this.

  • f = name/address of register
  • b = bit # (0 – 7)
  • d = destination (0 for W, 1 for the register specified in f)
  • k = literal value, an immediate, a number or address

Byte-oriented file register operations

Instruction Description
ADDWF f,d adds W and f together
ANDWF f,d bitwise AND: W & f
CLRF clears f (sets it to 0 = 0x00 = 0000 0000)
CLRW clears W (sets it to 0 = 0x00 = 0000 0000)
COMF f,d compliment f (inverts. COMF of 0010 0101 = 1101 1010)
DECF f,d decrement f (f = f – 1)
DECFSZ f,d decrement f, skip next instruction if result is zero
INCF f,d increment f (f = f + 1)
INCFSZ f,d increment f, skip next instruction if result is zero
IORWF f,d bitwise OR: W | f
MOVF f,d move f (used to load a register into W: MOVF temp1,w)
MOVWF f move W into f
NOP no-op. no operation occurs this cycle, useful in delays or waits
RLF f,d bitwise rotate left through the carry bit
RRF f,d bitwise rotate right through the carry bit
SUBWF f,d subtracts W from f
SWAPF f,d swap nibbles in f (nibble = 4bits, half-byte)
XORWF f,d bitwise XOR: W ^ f

Bit-oriented file register operations

Instruction Description
BCF f,b clears bit ‘b’ in register f
BSF f,b sets bit ‘b’ in register f
BTFSC f,b test bit ‘b’ in register f, if it is clear -> skip the next instruction
BTFSS f,b test bit ‘b’ in register f, if it is set -> skip the next instruction

Literal and control operations

Instruction Description
ADDLW k add k to W
ANDLW k bitwise AND: W & k -> W
CALL k call a subroutine at address k
CLRWDT clear the ‘watchdog timer’
GOTO k goto or jump to address k
IORLW k bitwise OR: W | k -> W
MOVLW k move literal (immediate) k into W
RETFIE return from interrupt
RETLW k return from subroutine with literal k in W
RETURN return from subroutine
SLEEP go to sleep mode (low-power standby)
SUBLW k subtract W from literal (immediate) k
XORLW k bitwise XOR: W ^ k -> W

PIC programming tools

There are several tools needed to get started in programming the PICs. I’ll briefly cover some software to develop in and hardware to load the chip.


I use the MPLab package by Microchip. It’s an excellent IDE and is available free for download at their site.

As I go through examples I will introduce specific features of MPLab, I find this the easiest way to do it, rather than listing them out and assuming you’ll get em right away…


KIT96 Programmer

KIT96 Programmer

On the hardware end is the actual device to send the data to the chip! For this I use kit 96 from It is a P16PRO compatible programmer, is quite easy to build, and looks pretty nice once it’s put together, a quality product. There is software available for it at, and costs a mild registration fee to fully program anything beyond a 16F84(a).

There are other programmers but I must say this is by far the nicest programmer you’ll find short of the professional versions. And even some pro versions leave quite a bit to be desired.

The programmer operates on a wall-wart power adapter and a PC parallel port (yet programs the chips serially). I have added a 40-pin wide ZIF socket on mine to facilitate bigger PICs, and make it WAY easier to put chips in and take them out…

Number bases and logic

Embedded programming requires at the very minimum a casual understanding of binary, hexadecimal, and logical operations. Here is a brief overview of these operations and a few sample uses.


Binary is all computers understand. It is a numbering system quite different than our “base-10″ system. In “base-10″ or decimal numbers, every digit has 10 possible values, 1,2,3,4… (hopefully you know this!). In binary, there are 2, only 2. These are typically represented by 1 and 0, but it can be a bird and a dog, up/down, left/right, front/back, black/white, ANYTHING, as long as it’s only two.

Quick Info on Binary:

  • a binary digit is known as a ‘bit’
  • 4-bits are called a nibble (or nybble)
  • 8-bits are called a byte
  • binary numbers are typically grouped into nybbles for readability and ease of conversion to HEX

So here’s a binary number: 0110 1000. An 8-bit number. Now what IS the number? Well it’s 104 obviously!

Here’s how we translate binary to decimal. First we need to disect our 8-bit number:

bit #

Bit 0 is known as the LEAST SIGNIFICANT BIT, and bit 7, the MOST SIGNIFICANT BIT. Bit numbers are increasing LSB to MSB. You get the value 104 by adding 2^(bit #) of all bits that are 1. So for this number it’s: (2^6 + 2^5 + 2^3) = 64+32+8 = 104.

The maximum value of an X-bit number is (2^X)-1. And the maximum number of different values that can be represented by an X-bit number is 2^X. So an 8-bit number can have 256 different values, and a max value of 255 (ranging 0-255 gives us 256 nums).

I guarantee you there are better tutorials on binary out on the net, search around, I’m going for quick-n-dirty here! :)


Hex is binary’s big brother in a way… It’s on the other side of the spectrum from binary to decimal, in hex, each digit can be 16 different values (0,1..8,9,A,B..E,F). So our 104 from before becomes: 0x68. The notation “0x” is typical to denote a hex number.

Lets try another number in more detail; 190. In binary that is: 1011 1110. So in hex we have 0xBE.

An easy way to do bin->hex is when the binary number is broken into nybbles, you can picture each nybble as 1 hex digit. The max value of a 4-bit number is 15, F in hex, so the conversion is pretty easy!

0110 1010 1101 1111 0010 1011 -> 0x6ADF2B











With blue being the input, or numbers being operated on, and green being the result.

  • AND – The AND (&) op. results in a 1 if and only if both inputs are 1.
  • OR – The OR (|) op. results in a 1 if either input is 1. (inclusive or)
  • XOR – The XOR (^) op. results in a 1 if strictly ONE input is 1, and the other is 0.
  • NOT – The NOT (!) op. flips the bit, if the input is 1, the result is 0. (a.k.a. compliment)

This is BARELY scratching the surface of logic, but it’s enough to get us by. Here are typical uses for these operations:

AND (&)

AND is good for “masking out” bits. If you wanted to get rid of a few bits in a number, while leaving the others unchanged, AND is what you’d use. Example: I have a 8-bit number, but I only want the upper 4-bits. My number is 0101 1010 = 0x9A. To mask these out, I create the “bitmask” 1111 0000 = 0xF0. The 1’s are the bits I want to keep, the 0’s what I want to get rid of.

0x9A & 0xF0 = 0x90 = 0101 0000 (lower bits have been removed)

OR (|)

OR is just the opposite. It is used for “setting” bits, while leaving the rest unchanged. If you have a byte, and need to set a couple bits in that byte, you “OR them in”. Example: I have a byte, and I want to set bits 0,3,6. My number is 1011 0110 = 0xB6. To OR them in, I make a “bitmask” of 0100 1001 = 0x49. The 1’s are the bits I want to SET, the 0’s the bits I want to leave alone.

0xB6 | 0x49 = 0xFF = 1111 1111 (the bits have been set)

XOR (^)

Exclusive or is a toggler, it’s used to flip bits based on their current value. Example: I have a byte, and I need to toggle the upper 4-bits of it. The number is 1100 0101 = 0xC5. To toggle them I make a “bitmask” of 1111 0000 = 0xF0, the 1’s being the bits I want to toggle, the 0’s being the bits I want to keep the same.

0xC5 ^ 0xF0 = 0011 0101 = 0x35

NOT (!)

Not simply flips the bits, inverts them, toggles, compliments, whatever you want to call it.

!0x0F = 0xF0