Question

I wrote a interrupt routine for 8051, using Keil C51, as follows:

void intrupt1(void) interrupt 2        // ext interrupt 1 vector
{   
    char i,j,prime;
    P2 = 0;
    for(i=2;i<128;i++)
    {
        prime = 1;
        for(j=2;j<i;j++)
        {
            if(i%j==0)
                prime = 0;
        }
        if(prime == 1)
        {
            P2 = i;
            delay2();
        }
    }
    P2 = 0;
}

When I tried to simulate it, it showed the correct prime numbers till 128 and after that it turned into a 8 bit counter and after that back to prime number showing, i.e. after 127 (the last expected prime number), the output was 128,129,130....255,prime numbers till 127,128,129....

I also wrote a routine for external interrupt 0, which is a 4 bit counter (it works correctly), but i guess that shouldn't affect the above.

Was it helpful?

Solution

Most likely char is signed in your compiler (the C standard allows char to be either signed or unsigned) and has a range of -128 to 127. Any value from this range is less than 128. So, the loop condition is always true and the loop is therefore infinite.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top