Search code examples
cembeddedpicmicrochipmplab

Blinking 3 LEDs using PIC 18F4550


I'm trying to get myself started with the PIC 18F4550 using the C, MPLAB X (both IDE and IPE) and using the PICKit 3. I've managed to blink one LED without any problems, but as I try to blink more than one LED at simultaneously, it doesn't work.

Please note that I will post my full code at the end of the question. Until then, I'll be writing pseudocode in hope of making my question a little bit clearer.

Assume I want to blink 4 LEDs, each attached to an output pin of the chip, you'd obviously type something like

loop{
     output1 = 1;
     output2 = 1;
     output3 = 1;
     output4 = 1;
     delay();
     output1 = 0;
     output2 = 0;
     output3 = 0;
     output4 = 0;
     delay();
}

You would expect that all of the LEDs would turn on and off simultaneously. However, I noticed that only the LED connected to output4 would blink and the rest would remain turned off. So I tried flipping the order of the output pins as such

 loop{
         output1 = 1;
         output2 = 1;
         output4 = 1;
         output3 = 1;
         delay();
         output1 = 0;
         output2 = 0;
         output4 = 0;
         output3 = 0;
         delay();
    }

As a result, only the LED attached to output 3 would blink, and the rest would remain turned off.

So I figured, somehow, the code is not executing sequentially as I'd expected it to do so. Can anyone please provide me with an explanation and a possible solution for this?

Thanks a lot!

Here's the full code

#include <xc.h>
#include <p18f4450.h>
#pragma config FOSC = HS

#define outRed  PORTBbits.RB0
#define outBlue PORTBbits.RB1
#define outYellow PORTBbits.RB2
#define outGreen PORTBbits.RB3
#define _XTAL_FREQ 10000000

void delay(unsigned int);



void main(void) {
    TRISBbits.TRISB0 = 0;
    TRISBbits.TRISB1 = 0;
    TRISBbits.TRISB2 = 0;
    TRISBbits.TRISB3 = 0;

    while(1) {
        outRed = 1;
        outGreen = 1;
        outBlue = 1;
        outYellow = 1;
        delay(1000);   
        outRed = 0;
        outGreen = 0;
        outBlue = 0;
        outYellow = 0;
        delay(1000);
    }        

}

void delay(unsigned int delayInput) {
    unsigned int mul = delayInput/50;
    unsigned int count = 0;
    for (count = 0; count <= mul; count ++)
        __delay_ms(50);
}

Solution

  • This could be a LATCH issue. I have had this problem a few times when I started up. Try writing to the LATB (output latch) register instead of the PORTB register. I always use the LATx for output and the PORTx for input.