Search code examples
cpointersembeddedpicmplab

Passing a predefined variable as a pointer in C


I tried to write a PIC program with C and what it does is turn on a series of 8 LED's (like Knight Rider LED illumination :D ). I have created the circuit design and tested with a simple c program that sets the state of the lights and it works. Now I want to streamline my code.

So i have created 2 functions for delaying and getting the required HEX value of the LED. the 2 methods are like this.

#define MAX 8
#define LEFT 1
#define RIGHT 2
#define BOTH 0

void delay_ms(int ms) {
    while(ms > 0)
        ms--;
}

int getHex(int delay, int dir, int *pin) {
    int hex[] = {0x01, 0x02, 0x04, 0x10, 0x20, 0x40, 0x80};

    if (dir == RIGHT) {
        for (int i = 0; i < MAX; i++)
        {
            *pin = hex[i];
            delay_ms(delay);
        }
    } else if( dir == LEFT ) {
        for (int i = MAX - 1; i == 0; i--)
        {
            pin = hex[i];
            delay_ms(delay);
        }
    }
}

and i have this in the main() function

main() {
    TRISA = 1;
    TRISB = 0;

    while(1) {

        if(RA0 == 0)
            getHex(5000, RIGHT, PORTB);
    }
}

What im trying to do is pass the PORTB predefined variable as a pointer to the function so it is set with the proper hex value. But i get the following warnings when i compile with the MPLAB IDE,

Warning [357] D:\...\main.c; 24.13 illegal conversion of integer to pointer
Warning [357] D:\...\main.c; 37.22 illegal conversion of integer to pointer

and when the program hex is added and run in the Proteus 8 nothing happens and the following warning appears.

[PIC16 MEMORY]PC=0x03AF. Attempt to write unimplemented memory location 0x0087 with 0x01 ignored
[PIC16 MEMORY]PC=0x03AF. Attempt to write unimplemented memory location 0x0087 with 0x02 ignored
[PIC16 MEMORY]PC=0x03AF. Attempt to write unimplemented memory location 0x0087 with 0x04 ignored

the final Hex value in the error correspond with the hex value i am trying to set as the value of PORTB. What am i doing wrong.. Please help.


Solution

  • Changed the getHex Method definition to this.

    int getHex(int delay, int dir, int *pin) {
        int hex[] = {0x01, 0x02, 0x04, 0x10, 0x20, 0x40, 0x80};
    
        if (dir == RIGHT) {
            for (int i = 0; i < MAX; i++)
            {
                *pin = hex[i];
                delay_ms(delay);
            }
        } else if( dir == LEFT ) {
            for (int i = MAX - 1; i == 0; i--)
            {
                *pin = hex[i];
                delay_ms(delay);
            }
        }
    }
    

    and then called the function with the following..

    getHex(2000, RIGHT, &PORTB);