Ok, I'm sure it's something stupid but this is probably the 20th variant of this code and I can't get it figured out. I simply want a (debounced) switch to trigger an LED on the PIC18f4550. Should I be using a different port for the switch? Here's my code:
void main(void)
{
TRISBbits.TRISB0 = 1; //switch input
TRISBbits.TRISB3 = 0; // LED output
PORTBbits.RB3 = 0; // make LED low by default
TRISEbits.TRISE2 = 1; // alternate switch input
while (1) { // doesn't work for some reason
if (PORTEbits.RE2 == 1) {
LATBbits.LATB3 == 1;
}
else LATBbits.LATB3 == 0;
}
}
Tried to post the config code but it screwed up the formatting here.
EDIT: sorry for the ugly formatting, but here are the config settings. Had to change some things to keep the formatting from getting weird.
include stdio.h
include stdlib.h
include p18f4550.h
include delays.h
// chip config ////////////////////////////////////////////////////////////////////////////////////
pragma config PLLDIV = 5
pragma config CPUDIV = OSC1_PLL2
pragma config USBDIV = 2
// internal clock, pin #14 (RA6) as I/O pin, pin #13 unused,
pragma config FOSC = INTOSCIO_EC // if OSCCON is left as default clock speed will be 1Mhz
// now the other less confusing options . . .
pragma config FCMEN = OFF
pragma config IESO = OFF
pragma config PWRT = OFF
pragma config BOR = OFF
pragma config BORV = 3
pragma config VREGEN = OFF
pragma config WDT = OFF
pragma config WDTPS = 32768
pragma config CCP2MX = ON
pragma config PBADEN = OFF
pragma config LPT1OSC = OFF
pragma config MCLRE = ON
pragma config STVREN = ON
pragma config LVP = OFF
pragma config ICPRT = OFF
pragma config XINST = OFF
pragma config DEBUG = OFF
Best Answer
You didn't show the external circuit, but if you just have a switch connected between the input pin and ground (or power), then that's not enough. That will drive the pin one way when the switch is closed, but leave it floating when open. There is no guarantee what state it will be in when left floating. To fix this, tie a pullup or pulldown to the pin that pulls causes it to go to the opposite polarity when the switch is open.
For example, tie the switch between the pin and ground, and then the pullup between the pin and Vdd. use 1 - 10 kΩ for the pullup.
Some pins of that PIC can be configured for internal pullups. RB4-RB7 can but possibly others on that PIC (your job to check the datasheet). If you enable the internal pullup, then the only external part you need is the switch between the pin and ground.