0
\$\begingroup\$

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);
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ Where is the problem, does it look like the programmer is programming and verifying the chip OK? \$\endgroup\$
    – PeterJ
    Jun 13 '13 at 6:14
2
\$\begingroup\$

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.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – PeterJ
    Jun 13 '13 at 7:35
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – efox29
    Jun 13 '13 at 7:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.