So I am working on a big project and need help with one little roadblock I haven't had to do before. I am using an MCP23017 (i2c general I/O expander) with its interrupt function to grab button presses very efficiently. I have everything working with the chip. However when the MCP23017 returns what button was pressed in comes in as a byte (10000000) with whichever 1 standing for which button was pressed.
How do I break that byte to use individually. So I can then say "if button x was pressed do this". I can take care of all the if statements and such just need to know how to break it apart. Bit shifts???
orionsbelt0:
That case thing would work but I think it would miss presses if they happen at the same time.
The 'best' design depends how much similarity there is between the code to handle the different button presses. If they're completely different, I'd use a loop to shift and mask bits out of the byte, and for each bit that was set I'd call a handler which used a switch statement to select the case corresponding to the bit number of the set bit. If the handlers were very similar, I'd define a function which accepted the bit number as an argument and call that for each set bit.
Either way, to cope with multiple simultaneous button presses you need to test each bit individually, and I'd use a loop to do that.
If you can safely assume only one button is pressed at a time, you can just switch on the original byte value and avoid all that fiddling.
TexasStingray:
Then he still has to code for ever combination of all possible combinations. Doesn't he?
No; not for every combination.
If he knows that only one button will be pressed at a time, the simple solution is just to hard-code the eight possible one-bit values in a switch statement.
If they might possibly arrive in combinations, the simplest solution is to test each bit in turn and handle any bit that is set. This just needs a couple of extra lines over the previous case.