Electronics > Microcontrollers

PIC16F877A Input problems


Hello all,
I am having difficulty interfacing my PIC16F877A microcontroller with 8 momentary buttons.
It only seems to be reading properly from RB0, 1 and 7. The other pins seem to be low even though I have 10K external pull up resistors to +6V. The circuit is pretty simple: 8 MHZ crystal to CLK with 22pF caps to groud, entire PORTD with apropriate resistors to LED's and entire PORTB with 10K pull up resistors to switches directly to ground. MCLR is tied high.

Here is the code written in Hi Tech PICC:

--- Code: ---/******************************************************
 * Pelle Jansen
 * 5 - 2 - 2012
 * PIC16F877A button IO test
 * X1: 8 MHZ, 2 22 pF capacitors to ground
 * ****************************************************

#include <htc.h> // main PIC header file
#include "delay.h" // for DelayUs()
#include "delay.c" // for some reason necessary for DelayMs()

/* External high speed 8 MHZ crystal oscillator, Watchdog timer disabled
 * brown out reset enabled, EEPROM protection disabled
 * write protect disabled, code protect disable, Low voltage programming disabled
 * power on timer enabled.

#define XTAL_FREQ 8 MHZ

/*main function*/
void main (void)
    TRISD=0; // PORTD as output
    TRISB=1; // PORTB as input

    while (1) // infinite loop
--- End code ---

The LED's are fine as I can light every individual one of them with success but when I try to read digital status from PORTB RD0, 1 and 7 works fine but others almost always return 0  >:( . When trying to use single ports in an if statement (RB2 in this case) it sometimes decides to work but than it fails again  :o . I feel like I'm overlooking something simple and stupid like an configuration bit. I am still pretty new to uCs so if you can help me out it would be greatly appreciated.
Oh and by the way, I am using MPLAB X on OS X 10.6.8 and am using a PICKIT 3. If you need any more info just ask :)

Thanks  ;)

Your really need this for all the pins to be inputs.

TRISB = 0xff

What Geoff said.

Your statement TRISB = 1 is equivalent to TRISB = 0x00000001.  See why it isn't setting the necessary pins as inputs?


--- Quote from: MikeK on February 06, 2012, 07:52:12 pm ---What Geoff said.

Your statement TRISB = 1 is equivalent to TRISB = 0x00000001.  See why it isn't setting the necessary pins as inputs?

--- End quote ---

That was quick, didn't even have time to type!
Now I get it. Thanks. According to the datasheet power on defaults are 1 so if I would completely remove that line it should solve it!

That means that the output port setting also is wrong. But why did it work?
Well I get it now. Thanks for the input  ;D


[0] Message Index

There was an error while thanking
Go to full version
Powered by SMFPacks Advanced Attachments Uploader Mod