Froggy Chair
Froggy Chair

Reputation: 43

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).

Upvotes: 1

Views: 833

Answers (2)

TheRealBeaky
TheRealBeaky

Reputation: 51

Well I would change the Pin-Mode itself to prevent some bad behavior of the PIC18F4550. So if you want to read some Pins: change the TRISx-Register on these Bits where you would like to have the Input to a 1. If you want to write from some Pins: change the TRISx-Register on these Bits back to a 0.

The TRISx-Register is to select the Pin-Mode (Input = 1 / Output = 0).

If you don't change this register, it could get faulty results or could possibly destroy your PIC.

Well, what I tried to tell you is: You can't / shouldn't read and write data at the same time. You always have to switch the Pin-Mode with the TRISx-Register. To write Data: Use the LATx-Register; to read Data: Use the PORTx-Register; to change the Pin-Mode: Use the TRISx-Register.

Upvotes: 0

theCreator
theCreator

Reputation: 164

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;
}

Upvotes: 1

Related Questions