Extracting bits from PortIn without using bitwise shifts

22 Nov 2011

Hi,

We are trying to use the PortIn function to read from multiple digital ports in a single snapshot. The problem we encounter is we have to read PortIn, assign it to a series of integers, bitmask it and then bitshift down the bit we want to check its digital value. For example if we want to check if a certain pin which is the 3rd bit in PortIn we would have something similar to:

(PortInValue & 0x00000008) >> 3 == 1

Ideally we would like something where we can just get a single bit from PortIn like

multableObject = PortInValue[3]

We have considered writing a utility function that breaks PortIn data into an array which we can then read. However, we believe the performance hit due to the overhead required by the utility function will negate the speed merit of PortIn library (a motivation of its use) as opposed to the DigitalIn library.

Does anybody have ideas on how to accomplish what we want. Would using assembler help or is PortIn inherently always going to give out a 32bit number. Is PortIn the best thing to use in our case? Any suggestions?

Many Thanks, Thomas

22 Nov 2011

You don't need to do the shift just to check the bit value.

if ( PortInValue & 0x00000008 )
{
  // pin3 is on
}
else
{
  // pin3 is off
}

Or you can check several bits at once:

uint32_t mask = (1<<8)|(1<<3)|(1<<0); // we want to check bits 0, 3 and 8
if ( PortInValue & mask )
{
  // at least one of the bits is on
}
else
{
  // all bits are off
}