I'm making a midi controller and need to read lots of buttons... is there an easier way to write code to read multiple digital pins and return the number of which one goes HIGH...??
Yes.
I'm reading all 20 pins with the following code in and displaying them with only 30 lines of code. the actual reading only takes 3 lines.
Tested and works 100% on UNO
union PinsLink {
volatile uint32_t All;
volatile uint8_t Port[4];
} Pins;
uint8_t PinNumber[22] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, -1, -1, 14, 15, 16, 17, 18, 19}; // Key = Bit Val = Position List of pins that could be used as ping inputs:
uint8_t BitNumber[20] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 16, 17, 18, 19, 20, 21}; // Key = Pin Val = Position List of pins that could be used as ping inputs:
void setup() {
Serial.begin(115200);
for (int i = 2; i < 20; i++) { // pins 0 & 1 are for Serial communications
pinMode(i, INPUT_PULLUP);
}
}
void loop() {
// The following 3 lines gets the status of all the pins and stores them in a 32 bit interager using a union
Pins.Port[0] = PIND; // 0~7
Pins.Port[1] = PINB; // 8~13
Pins.Port[2] = PINC; // A0~A5
// Lets see what we have:
for (int Pin = 0; Pin < 20; Pin++) { // pins 14 ~ 19 are analog A0 ~ A5
Serial.print("Pin# ");
Serial.print(Pin);
Serial.print(" = ");
int Bit = BitNumber[Pin]; // the BitNumer array links the pin number to the bit representing the pin.
Serial.println(Pins.All >> Bit & 1); // Lets see if Just that bit is high and print the results.
}
delay(1000);