I'm working on an embedded systems project, and am reading multiple switches, and then doing things depending on the result. I am trying to keep this modular and abstracted, so each of my functions don't see any of the low-level pin numbers or pin reading functions.
There may be multiple switches down at a time, so I am storing the numbers using bitwise or |
, then using bitwise to compare. I am currently just redundantly converting the pin that is read, into my switch values that can be compared with bitwise operators.
Is the a more efficient or better way to do this?
// physical pins on microcontroller
#define pin_sw_green 5
#define pin_sw_yellow 6
#define pin_sw_blue 7
#define pin_sw_red 8
// switch numbers, allowing bitwise operators to work
#define switch_green 0x01
#define switch_yellow 0x02
#define switch_blue 0x04
#define switch_red 0x08
// store switch press to val
uint8_t button_pressed()
{
uint8_t data;
if (pin_read(pin_sw_red))
data |= switch_red;
//...
if (pin_read(pin_sw_green))
data |= switch_green;
return data;
}
//...
uint8_t button_data = button_pressed();
if (button_data & switch_red)
{
// do things..