edipo99
edipo99

Reputation: 37

Timing delay on my PIC

Prepare for a nooby question.

I'm writing some ultra-simple code for this new PIC which I've just got. All I'm trying to do is to flash an LED. Below are two code samples - the first works but the second doesn't. Why?? I can't see any problem with the second one.

WORKS:

        while(1)
{
    i=99999;
    while(i--) {
        LATAbits.LATA0 = 0;  // set RA0 to logic 1
    }
    i=99999;
    while(i--) {
    LATAbits.LATA0 = 1;  // set RA0 to logic 0
    }
}    

DOESN'T WORK:

        while(1)
{
    LATAbits.LATA0 = 1;  // set RA0 to logic 1
    for(i=0;i<99999;i++) {}
    LATAbits.LATA0 = 0;  // set RA0 to logic 0
    for(i=0;i<99999;i++) {}
}

Thanks in advance for the help!

Upvotes: 1

Views: 309

Answers (2)

DrRobotNinja
DrRobotNinja

Reputation: 1421

  1. What's your definition of i? char i? int i? long i?
  2. What PIC are you using?

If you're using an int, the 8-bit PICs use a 16-bit int.

So what happens:

// Try to stuff 99999 into 16-bits, but it becomes 34463
i=99999;

// Count-down from 34463 to zero
while(i--) {}

// Successfully exit delay

As opposed to:

// Count up from zero
// Get to 65535 and then reset to zero
// Never reach 99999
for(i=0;i<99999;i++) {}
// Never exit delay

Try using unsigned long int for i, which tends to be 32-bit on PICs and see if it starts to work.

Upvotes: 0

Lucio Paiva
Lucio Paiva

Reputation: 20816

Try this:

while(1)
{
    for(i=0;i<99999;i++) 
    {
        LATAbits.LATA0 = 1;  // set RA0 to logic 1
    } 
    for(i=0;i<99999;i++) 
    {
        LATAbits.LATA0 = 0;  // set RA0 to logic 0
    }
}

Maybe your compiler is optimizing and ignoring the for statements as they have no code to execute inside. What I did was put the RA0 assignment inside these statements, forcing the compiler to keep the delay loops.

You can also pass the argument -S to your compiler to see the assembly code generated and confirm that the for statements were removed. The -S option generates an intermediate file with a ".S" extension.

Upvotes: 0

Related Questions