Archive for the ‘howtos’ Category.

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.

Software

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…

Hardware

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 www.kitsrus.com. 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 www.picallw.com, 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

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 #
7
6
5
4
3
2
1
0
104
0
1
1
0
1
0
0
0

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! :)

Hexadecimal

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

Logic

AND

 
0
1
0
0
0
1
0
1

 

OR

 
0
1
0
0
1
1
1
1

 

NOT

0
1
1
0
XOR

 
0
1
0
0
1
1
1
0

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

Introduction to PIC Microcontrollers

PIC 16F628

PIC 16F628

PICs are great little chips, useful in all kinds of projects. Here is a run-down of some of the features contained in the chips, as well as potential uses.

How to start… Well, first off, what is a microcontroller? Well, the difference between a microcontroller (heretoin referred to as MCU or μC) and, say, a computer CPU is pretty big… Here’s a little chart of some of the typical differences:

  CPU MCU
Onboard instruction memory   +
Complex math routines +  
Super-high speed +  
General purpose   +
All-in-one   +
Built-in I/O ports   +
Low power consumption   +

Microcontrollers are intended for small, specific purposes, they have their own I/O ports, own memory, nearly everything needed is built in. You’ll find them in your microwave, refrigerator, car, camera, tv, all kinds of things…

The microcontroller I’ll tend to use in the beginning at least, is the PIC 16F628. It has 2048 words of instruction memory, plenty of data RAM, lots of EEPROM storage, a serial module, PWM, Input Capture/Compare, Comparators, etc… Lots of features. These may seem complex but ignore it, we’ll start out with super simple stuff and not use any of it til later (if ever!)

This chip runs at 20MHz, which is PLENTY for the purposes we’ll be putting it to, heck it’s an insane amount faster than needed. You can get them for about $4 at Digi-Key.

Schematic

Each of the pins you see there have a specific purpose, which is explained on the following page. A quick look @ the datasheet reveals this:

Legend:

  • <–> denotes a bi-directional data line
  • –> going INTO the chip denotes input-only
  • <– going OUT of the chip denotes output-only
  • the pins may have various labels, depending on how you decide to use them in your design
  • if a label has a BAR above it’s name (i.e. MCLR) it is active LOW, meaning the pin is “enabled” @ 0V instead of @ +5V

The 16F628 has 2 – 8bit data ports. They are the RA0..7 and RB0..7 you see on the diagram. Vss = Ground, and Vdd = +5V typically, and in my examples, always. CMPx are comparators, TX/RX are serial guys, etc, they are all described in the datasheet. For the first few tutorials, I’ll only be using them as straight digital outputs, no funky stuff.

Making Home-Made PCBs

A PCB is much more desirable than just a mess of wires, or even the little breadboards you can get @ Radio Shack. They’re not always the best way to do it, might not be worth the effort, but when you have a fairly complex wiring project, a PCB is VERY HANDY.

So, what do we need to make a PCB? Well, it’s not TOO much stuff… This method is the Iron Transfer method of making a home made PCB or PC Board.

Supplies

El-cheapo glossy inkjet paper

  • Some way to draw the board. I use Eagle from CadSoft. It has a great free version available for download at their site.
  • Copper-clad board (we’re doing single-sided, 1oz.) these run around $5 @ Radio Shack or online for a single/double sided, 6″x6″ board
  • Glossy Ink Jet paper (I use JetPrint Photo, HP Glossy does ”’NOT”’ work)
  • Laser Printer or Photocopier (need the toner to transfer)
  • Iron (normal, household iron) & Ironing board
  • PCB Etchant Solution (there are several)
    • Ferric Chloride
    • Ammonium Persulphate
  • A ”’PLASTIC”’ tray (metal is a BAD IDEA)
  • A drill of some kind (Dremel Tools work great)
  • Some little tiny drill bits (hobby stores have ’em for like $5)

Process

Design and print the PCB Layout

An example layout

An example layout

2-up sample layouts

2-up sample layouts

First you draw your board, with whatever software you want. If you are using a PCB layout software package, then you already know what to do.  You can also just use any old drawing program, but I’d stick to 1 layer for that.  If simply drawing it, keep in mind you are drawing the BOTTOM of the PCB, so all pinouts, and arrangements are REVERSED (Unless you are making stuff for SMT parts, in which case, you probably don’t need this tutorial!). It’ll take practice and patience… Measure, draw, print on plain paper and see how your parts fit… Check, check, check, and check again to make sure all the lines you have drawn will mimic your wiring, you can’t change it without being sloppy once it’s etched…

Tip: Make sure your components have holes for each pad, once etched, it’ll make drilling much easier.

After we have that done, we’re ready to print it on our glossy paper. One thing you must remember to do, is to print this image flipped. You will be printing it to the page, then ironing it on, so to get it the right way, you must mirror it.

My laser printer doesn’t like the glossy paper, so I print it on a plain sheet of paper, then run it through a photocopier… Same result. You just need a flipped image of your board in toner on the glossy paper. The glossy paper lets the toner come off easier when you iron it.

Transfer the Image

Pre-etch copper clad

Pre-etch copper clad

An iron!

An iron!

Cut the paper to size to make it easier to handle and position on the copper-clad. You may also want to cut the copper-clad if don’t plan on using all of it for this board.

Really quick we need to prep the copper-clad to take the transfer. You simply scratch it up a bit, not gouge, just scratch. I usually wet-sand it with super-uber-fine grit sandpaper, or an abrasive sponge pad. It should be nice and shiny and dry when you are done.

Now we break out the Iron.

Turn it up to a medium temperature. I only put mine up about 1/3 of the way, too hot and it’ll smear the toner and burn the paper, no need for that.

Place the image on the copper-clad and line it up. Rub the iron across it holding firmly down til it starts to stick, once you have good contact you don’t need to worry about it moving around.

I usually put a piece of paper or two in between the iron and the transfer paper, so I can run the iron over easier. It helps diffuse both the heat and the pressure more evenly, but will slow the process down a bit.  Check every so often to see if it is transferring. Some areas like the edges might need special attention with the tip of the iron. I usually push down real hard to ensure good contact, and leave it on, moving around for a few minutes. Whatever feels right. If you mess up you can just scrape it off (re-sand as per the prep instructions), so experiment and find what works for you.

Once you think you’re done, remove the iron. Take the board (using hot pads or something so you don’t singe your fingers) and put it in your sink. I use it to cover the drain hole, then turn on a light stream of water.  This will make the sink fill, and let the board soak.

Stuck on

Stuck on

Soakin' it...

Soakin' it...

Transferred

Transferred

After a while, the glossy material gets goopy and slimy and starts to come off, it can be a bit messy but it’s tolerable.

Once it’s pretty loose you can peel off a layer of paper… Some might stay on, it’s fine, just leave it in running water. Eventually it will lose it’s grip and just come right off, leaving (ideally) a perfect image of your PCB layout on the copper-clad.

Etch

Etchant and Tray

Etchant and Tray

Etching the PCB

Etching the PCB

Now that the image is transferred on, we can start to etch. The etchant solution eats away all the copper it can react with, but the toner on there stops it from getting our pattern, the result? An etched PCB.

You want to use a plastic tray of some kind, something you won’t be putting food in or anything. Rinse it out and dry it, then set the PCB in there. Pour in some solution and watch it work. 

Tip: The hotter the solution, the faster it works… Outside in the summer sun really makes it go fast.

Warning: Don’t do this in a closed area, breathing this is bad… Also try not to touch it, it stains quite effectively.

Agitate the solution as much as you can tolerate. :) It gets kinda boring so do it off and on. Just simply lift and set down one end to slosh the solution around so fresh solution can get at the board and continue the reaction.

Keep an eye on the board, I use plastic tongs to take it out every so often and check it, rubber gloves also work well.  Eventually you’ll be able to see how it’s eating away the copper and your board is appearing.

Once you feel it’s done, flood the tray with water, be careful not to spill it, you’ll be quite unhappy if you do. I usually fill it up w/water, then pour it into a bucket. This stuff is hazardous waste, so you might want to find out where to dispose of it with whatever local agency deals w/that in your area. Once you rinse a few times to dilute the solution, take the pcb out, and run that under water for a minute or so to make absolutely sure the  chemical reaction is neutralized.

Once you have that out of the way, you should have something that looks like this:

Etched PCB, bottom

Etched PCB, bottom

Etched PCB, top

Etched PCB, top

Drill

Itty Bitty Bits

Itty Bitty Bits

Completed PCB

Completed PCB

Ok lets drill. I have a little set of bits I found at Hobby Lobby. They’re for crafts or something, anyway they work really well and were cheap. You can also get a Dremel bit set from hardware stores.

Using these with a Dremel makes this process super easy, as the Dremel is easy to handle and nimble. But a normal hand drill should work fine too. Some people even go so far as to use a Dremel with a drill press, I’ve tried it, it’s neat, but no easier than by hand.

Just find the bit that fits your parts, and drill away, using the holes you left in your PCB layout to guide the bit. The material making up most of the board is super soft and cuts like butter w/the drill bits. 

Warning: Hazardous Materials! Be careful not to breathe the dust, it’s fibreglass and some of its other nasty friends, not something you want in your lungs.  Use appropriate masks/ventilation.

After you’re done drilling, I like to wet-sand again with super-fine sandpaper… The toner is VERY hard to get off with a simple scotch pad or other abrasive… But wet-sanding takes it right off and you have nice shiny copper underneath… Acetone (the nail polish remover kind, no need to go industrial here) will also work to remove the toner but some PCB materials may not particularly care for Acetone.

That’s all!  An optional final step is tinning the PCB.  Tinning puts a very thin layer of tin over the remaining copper, reducing oxidization problems you’ll get with exposed copper, and it also helps soldering a bit. You can find tinning solution from electronics shops online or in reality.

Making Home-Made IDE and Floppy Cables

After having an electrical tape rounding job for a while, I decided it was time to have something nice looking if I was going to window my case. I don’t really care for any of the pre-made cable solutions available so I figured why not make my own. Turns out they’re super easy, look great, and can be totally customized to fit your case!

First off you need to find your cable… There’s 2 kinds (probably more, that’s all I bothered looking at) you got your gray ribbon and your rainbow ribbon. Depending on the purpose you need different conductor amounts, 34 for floppy, 40 for up to ATA33, and 80 for ATA66+. There are also different spacing, .050″ for Floppy and ATA33, and .025″ for ATA66+. Of course you have different widths for different flavors of SCSI, etc, pick what ya need…

I have yet to find a decent supplier for 80-conductor .025″ center ribbon. If anyone knows of any, let me know.

Jameco # Description
643655 34-conductor flat rainbow
644033 34-conductor flat gray
643697 40-conductor flat rainbow
644113 40-conductor flat gray

Next you need your IDC’s (insulation displacement connectors)… Pretty cut and dry, you need either 34, 40, or 80 contact ones to match the cable.

And again I’m still looking for the 80 contact ones. I’ve heard places like Fry’s have them, but we don’t have Fry’s out here, nor is that too useful since I usually mail order, so if someone finds them somewhere online, please let me know!

Jameco # Description
32768 IDC plug for 40-conductor
32644 IDC plug for 34-conductor

And finally you need some type of crimper… You *can* use a normal table vise for this, maybe even vise grips and maybe maybe maybe maybe pliers but I wouldn’t recommend it since you’ll get uneven pressure. The best thing to do is to use IDC crimpers.

Jameco # Description
73252 Insulation Displacement Crimper

Here are some pictures of the stuff I got…

Most of the stuff I used

Most of the stuff I used

IDC Connector (40-contact)

IDC Connector (40-contact)

IDC Crimpers

IDC Crimpers

For an IDE cable, we need not modify the cable to get it to work, but for a floppy cable we need to do a small tweak. If you want to have a 1 floppy drive cable, then you must put a twist in somewhere between the two connectors. The twist consists of wires 10-16 being swapped: 10 -> 16, 11 -> 15, 12 -> 14. These images will provide more detail:

Single floppy drive cable

Single floppy drive cable

Dual floppy drive cable

Dual floppy drive cable

Single floppy drive cable

Single floppy drive cable

Dual floppy drive cable

Dual floppy drive cable

Bare ribbon cable  

Bare ribbon cable

As far as the maximum length for an IDE cable goes, it would seem 18″ is the max IDE/ATA spec. although I’ve seen 36″ and higher work so it’s trial and error. Also it really doesn’t matter how close your two drive connectors are to each other, so just put them where you want them to be for your particular need.

I basically measured up the distances between my IDE connectors on my mobo and added a little for slack and to account for a bit of shortening due to rounding the cables later on. Here’s what I got for one of my IDE chains. It’s about 10″ or so (the perspective is skewed a bit).

Now we clamp on the IDC connectors, these little guys have 80 little teeth (2 for each wire) that penetrate the insulation (displace it as it were) and make contact with the wire inside, pretty slick if you ask me, just line them up and crunch ’em down.

Here are some pics of the cables as they were added into my case. You can even see the remnants of the electrical tape rounded cable that were being replaced.

Partially complete cable

Partially complete cable

 

Floppy done

 

Floppy (close)

Floppy (close)

 

Floppy + 1 IDE (Zip)

Floppy + 1 IDE (Zip)

 

Done, 1 Floppy, 3 IDE Cables

Done, 1 Floppy, 3 IDE