# Basic code to switch LED for PIC18f4550 XC8 not working!

I can't run this code on my PIC18F4550 with 20.00 MHz crystal oscillator. I use XC8 compiler. Where is the problem? How to write a configuration in XC8 compiler? By the way I am a beginner in the microcontroller world. Can someone tell me what is wrong with my configuration?

#pragma config OSC = HS,OSCS = OFF
#pragma config PWRT = OFF,BOR = ON,BOVR = 45
#pragma config WDT = OFF,LVP = OFF
#pragma config DEBUG = OFF,STVR = OFF
#include<p18f4550.h>

void msdelay(unsigned int ms)
{
unsingned int x;
unsigned char z;
for(x = 0; x < ms ; x++)
for(z = 0; z < 165;z++);
}

void main(void)
{
TRISB = 0;
while(1)
{
PORTB = 0x55;
msdelay(500);
PORTB = 0xAA;
msdelay(500);
}
}

• Where is the problem, does it look like the programmer is programming and verifying the chip OK? Jun 13 '13 at 6:14

If you are running your code at 20Mhz, and if I remember correctly, the Fcyc was a Fosc/4 which would mean that you are running your code at 5Mhz.

At 5Mhz thats 200ns per instruction.

Your delay function is ~ 500*165 = 82500 cycles = 16.5ms. It's 'not working' could be that it IS working, but its just not working the way you might have expected. It's probably just toggling too fast for you to see.

Try changing your msdelay(..) to the following

void msdelay(unsigned int ms)
{
unsingned int x;
unsigned int z;
for(x = 0; x < ms ; x++)
for(z = 0; z < 5000;z++);
}


How did I get 5000 ?

Each cycle takes 200ns. So to get a delay of 500ms, first you can find out how much it is for 1ms $\frac{1ms}{200ns} = 5000$

Now when you pass your parameter in ms, for each ms it will run 5000 times.

Hopefully that helps.

• The above is assuming the for loop is a single cycle. It'll depend on the compiler but I just checked a LST file I had floating around and it was 5 instructions plus a branch so 7 cycles for each loop iteration. Also your z < 5000 wouldn't work for an unsigned char. Jun 13 '13 at 7:35
• You are right, the delay wont be exact, but thats why I put a ~ for the number of cycles. It's an estimation and it would depend on the compiler, optimization etc.. And you are right, the char wouldnt work. It should be an int. I'll edit that. Thanks. Jun 13 '13 at 7:38