Read GPIO input

Tip / Sign in to post questions, reply, level up, and achieve exciting badges. Know more

cross mob
Anonymous
Not applicable

Hi,

   

I have a issue with reading GPIO input value with the code as below:

   

// set P0[2] drive mode = highZ

   

PRT0DM2&=~0x04;

   

PRT0DM1|=0x04;

   

PRT0DM0&=~0x04;

   

//read P0[2] input to temp 

   

                BYTE temp=0;

   

temp |= (PRT0DR&0x04)<<7;

   

 

   

P0[2] is set as StdCPU. While I give a 5V input to P0[2] port, and expect the variable temp will have a value of 80h after executing the above code. However, the temp value is always 0. I am wondering it is the correct way to read the input of port P0[2]?

   

appreciate any help and suggestion.

   

 

   

Thanks,

   

cc

0 Likes
2 Replies
Bob_Marlowe
Level 10
Level 10
First like given 50 questions asked 10 questions asked

Your shift by 7 (seven) is wrong. Easier (apart from shift) would be

   

temp = (PRT0DR & 0x04)  != 0; // giving a boolean result, 0 == FALSE, != 0 is TRUE

   

or

   

temp = (PRT0DR & 0x04) >> 2;

   

 

   

a macro (or two) could be helpful:

   

#define BitMask(BitNo)  (0x01 << (BitNo))

   

#define ReadPortBit(PortRegister,PortBit)  (((PortRegister) & BitMask(PortBit)) >> (PortBit))

   

The additional parentheses are only for the case that one of the parameters is an expression

   

 

   

Happy coding

   

Bob

0 Likes
ETRO_SSN583
Level 9
Level 9
250 likes received 100 sign-ins 5 likes given

If you are doing read modify writes on a port register shadow registers

   

are needed.

   

 

   

    

   

         

   

Shadow Registers

       

      http://www.planetpsoc.com/psoc1-articles-digital/13-basics-of-psoc-gpio.html?start=5

   

http://www.cypress.com/?rID=2900     AN2904

   

 

   

 

   

Regards, Dana.

0 Likes