Search code examples
c8051keil

C Programming for 8051: SFR directions as arguments


I'm currently making a very simple Tic-Tac-Toe game with an AT89C51RC2 and I am having issues getting the button input right.

Basically, the input is a 3x3 Button Matrix which I want to utilize by scanning through the rows with a pulse while checking the columns for a connection; pretty basic. However, the way I wanted to do this was by making a unique scroll method that received the row parameter and set it to HIGH accordingly.

I already have

sbit R1 = P1^0; 

all through the needed inputs, but I'm not sure if this is correct.

Then, on my main method, I run something like

while(TRUE)
{
    scroll(R1);
}

which is named scroll, I have this

void scroll (bit P)
{
   P = HIGH; //Sets the row being checked to HIGH (HIGH is already defined as a 1). Same goes with the aformentioned TRUE
   ...
}

So, this is not working. I know I'm not doing this right, but I had to start somewhere. Is what I am attempting to do possible? Sending a single Pin adress as an overload for a method? If so, what datatype should it be? I was juggling between char and bit but I can't settle.

I hope my question is understandable! If not, I will gladly elaborate and maybe post all the code (although it is quite messy). Thanks, everyone, in advance!


Solution

  • If I understand your question correctly, I could expand your code snippets to look like this:

    sbit R1 = P1^0;
    sbit R2 = P1^1;
    sbit R3 = P1^2; 
    
    while(TRUE)
    {
        scroll(R1);
        scroll(R2);
        scroll(R3);
    }
    

    (Your scroll function remains as is). You are trying to define one function that you can call multiple times, passing in a different pin to assert each time you call the function.

    Unfortunately, I am not aware of a way to do exactly what you want to do, because you may not define sbits in a function, either as locals or parameters. I'm sure there's a non-intuitive way to do it in inline assembly with the SETB and CLR instructions (maybe someone else can chime in), but with Keil the C compiler alone it is a no go.

    Instead, perhaps you could make a helper function to do the pin assignment. That would let you do something like this:

    void setRow(char whichRow, bit whatValue)
    {
        switch (whichRow)
        {
            case 1:
                R1 = whatValue;
                break;
            case 2:
                R2 = whatValue;
                break;
            case 3:
                R3 = whatValue;
                break;
            default:
                break;
        }
    }
    
    void scroll (char row)
    {
        setRow(row, HIGH); //Sets the row being checked to HIGH (HIGH is already defined as a 1). Same goes with the aformentioned TRUE    
        ...
    }
    

    And then in your main:

    while(TRUE)
    {
        scroll(1);
        scroll(2);
        scroll(3);
    }
    

    Good luck.