Tuesday, January 13, 2009

Common pitfall: digital pins aren't digital unless explicitely set as digital

If you've read some jallib samples, you may have often seen this line:

enable_digital_io() -- disable analog I/O (if any)

What does this mean and why ? This simply means you want to set all pins as digital pins. Because, by default, pins are configured as analog pins.

Where does this come from ? From the holy datasheet, of course ! Consider the 16f88 chip. PORTA provides the following functions:



Amongst them, some provide analog function, such Analog-to-Digital-Conversion (ADC). And it's explicitly said the PORTA pins are configured as analog inputs on Power-on Reset:


Datasheet is less explicit for PORTB. Two pins provide analog functions, for the last two ADC channels (pins RB6 and RB7):


Those pins are configured with ANSEL register, which is read as 1 on Power-on Reset, which means by default, pins are configured as analog:


Phew... Now why don't we, at jallib, set all pins as digital ? After all, most of the time, you need digital pins, and even if not, you could just set them as analog pins as needed. Yes, you could. But we decided to follow the holy datasheet. And this means if you read and know the datasheet, when you type this:

include 16f88

you expect to get analog pins, because the datasheet says so. To switch them to digital pins, just call
enable_digital_io(). This procedure is the same for every PIC: whatever the device file you're using, calling this procedure will configure and setup all registers so you have digital pins (and there are many differencies and inconsistencies between PICs, fortunately thanks to Rob's hard work, this is made easy for users).

So, one important point using jallib is: "be explicit". While this may need more typing from you, you'll get a better understanding of what's going on, and you'll finally get a cleaner and more maintainable code.

S├ębastien Lelong

No comments:

Post a Comment