Search code examples
cassemblypiccarryflagstatus-register

Why carry bit is not 1 never? I looked in the program memory and never 1, just 0


I am writing a C program to generate Fibonacci numbers until 255 (as 8-bit values) using pic16f887. I try to check the carry bit from STATUS which is bit 0 (LSB) (I checked the datasheet), but all the time is 0.

#include <htc.h> 
#define N 20 
unsigned char i@0x20; 
unsigned char v[N]@0x30; 

void main(void)
{
    v[0] = 0;
    v[1] = 1;
    i = 2;
    while(1)    
    {
        v[i] = v[i-1] + v[i-2];

        if(STATUS &0b00000001) 
            goto end;
        i++;
    }
end:
    asm("NOP");
}

enter image description here


Solution

  • There's no ordering between the (presumably volatile) register read and the arithmetic and load/stores in the loop. You can't "read the carry flag" from C because there is no way of positioning the flag read relative to the underlying arithmetic operations, even if you assume a machine that has a carry flag. Instead you need to write the explicit logic for carry and hope the compiler can recognize it and make use of the carry flag if that's the most efficient way to do it.