Search code examples
microcontrollerpic

How can I use a port of PIC18F4550 as both input and output?


So what I need to do is a three-state logic application using a PIC18F4550 a 74LS244 and a HCT573. The problem here is that I need to use a single port of the PIC as both inputs and outputs. I need to use 7 pins of the port because I need to connect a 7-segment-display and four of those pins have to work as inputs at the same. Those inputs are connected to the 74LS244 and from there to four push buttons so when I introduce the numbers from 0 to 15 in binary with them in the display must be shown that number or letter for the cases from 10 to 15. The display is connected to the HCT573 and from there to the PIC. The main problem here is that I don't really know how to use the port as inputs and outputs at the same time. The software that I'm using for write the code is CCS Compiler (PIC C Compiler).


Solution

  • you can run an infinite while loop. During that loop you can do two methods one for polling and one for display. some pseudo code could be as follows

    int pollState()
    {
        //return the output as an int
        
        int output = 0;
        //set 4 pins state to input - 0b00001111
        TRISC = 0x0f;
        
        //do some checking on the pins 
        if(PORTCbits.RC0 = 1)
        {
            output |= 1 <<0;
        }
        
        if(PORTCbits.RC1 = 1)
        {
            output |= 1<<1;
        }
        
        if(PORTCbits.RC2 = 1)
        {
            output |= 1 <<2;
        }
        
        if(PORTCbits.RC3 = 1)
        {
            output |= 1 <<3;
        }
        
        
        
        return output;
        
        
    }
    
    
    
    int setState(int number)
    {
        //set the portC as output
        
        TRISC = 0;
        
        //the binary was tranfered in the poll state
        //shift out the data here
        
        shiftOut(number);
        
        
        return 0;
        
    }
    
    int main(int argc, char **argv)
    {
        int state=0;
        
        while(1)
        {
            
            state=pollState();
            setState(state);
        }
        
        
        return 0;
    }