Electronic – “Not enough RAM ” error in PIC16F877a

cpicpic16fpic16f877a

I have been trying to run the following code:

void reset();

int board[8][8];
int i,switcher,j,k;

void main() {
    TRISB = 0X00;
    TRISD = 0X00;
    TRISC = 0X00;
    reset();
    ADCON1 = 0X06;
    TRISA =0X11;
    while(1)
    {
        for( i=0;i<16;i++)
        {
            switcher = i;
            PORTB.F0  = switcher%2;
            switcher /= 2;
            PORTB.F1 = switcher%2;
            switcher /= 2;
            PORTB.F2 = switcher%2;
            switcher /= 2;
            PORTB.F3 = switcher%2 ;
            if (!PORTA.F0 == board[i/8][i%8])
                break;
            delay_ms(1000);
       }
       switcher = i;
       PORTC.F0   =  switcher%2;
       switcher /= 2;
       PORTC.F1 = switcher%2;
       switcher /= 2;
       PORTC.F2 = switcher%2;
       switcher /= 2;
       PORTC.F3 = switcher%2 ;
       switcher /= 2;
       PORTC.F4 = switcher%2;
       switcher /= 2;
       PORTC.F5 = switcher%2 ;
       break;
   }
}

void reset()
{
    PORTB = 0;
    PORTD = 0;
    PORTC= 0;
}

On running this code, it's showing

"Not enough RAM" error.

However on running this code :

void reset();

int board[80][80];

void main() {
    TRISB = 0X00;
    TRISD = 0X00;
    TRISC = 0X00;
    reset();
    ADCON1 = 0X06;
    TRISA =0X11;
}

void reset()
{
    PORTB = 0;
    PORTD = 0;
    PORTC= 0;
}

It runs successfully with no errors (Note that I am creating a multidimensional array of 80×80 whereas for the previous one it's only 8×8). Can someone help me in identifying the cause for the problem? And if possible then also the proper solution for the problem ?

Best Answer

The PIC16f877a only has 368 bytes of memory, meaning that the 8x8 array is already in danger of exhausting available memory (either 128 or 256 bytes depending on sizeof(int)) given a requirement for other structures (other symbols, stack, etc).

However, in the second program, your compiler recognizes that you do not access the 80x80 array in any way, and thus optimizes it out. As a result, the linker doesn't need to find space for a variable of size 80*80*sizeof(int) bytes and the program is successfully compiled and linked.

Presumably, you are only using each element of the array for a single boolean value--in that case you can reduce your space requirements to 64 bytes of space by packing the data more efficiently. This answer describes one way to do this, where bitwise operations are used to index into an array of uint8_t values. Alternatively, you could try using your existing technique (2D integer array) with a uint8_t[8][8] to avoid making larger code changes, but this remains wasteful of memory (8x waste).

Related Topic