how to convert the following code into one using direct port manipulation Following is the program for scanning a keyboard for MIDI transfer.
At present the code works fine, but it could be faster.
I need to know how to use direct port manipulation inside the for loop.
boolean keypressed[6][6]; //for storing key states
int midinote[6][6] ={ 60 ,61 ,62 ,63 ,64 ,65
                 ,66 ,67 ,68 ,69 ,70 ,71
                 ,72 ,73 ,74 ,75 ,76 ,77
                 ,78 ,79 ,80 ,81 ,82 ,83
                 ,84 ,85 ,86 ,87 ,88 ,89
                 ,90 ,91 ,92 ,93 ,94 ,95  }; //code for various midi notes C3 to C6


void setup() {

   Serial.begin(38400);
   for(int i=0; i&lt;6; i++){
      pinMode(i+2,OUTPUT);
      digitalWrite(i+8,HIGH);
   }
   for(int i=0; i&lt;6; i++){
      pinMode(i+8,INPUT);
      digitalWrite(i+8,HIGH);
   }
   for(int i=0; i&lt;6; i++){
      for(int j=0; j&lt;6; j++){
          keypressed[i][j] = false;
          }
      }
   }
void loop() {

   for(int i=0; i&lt;6; i++){
      digitalWrite(i+2, LOW);
      for(int j =0; j&lt;6; j++){
         if ((digitalRead(j+8) == LOW) &amp;&amp; !keypressed[i][j]){
            Serial.write(0x91);
            Serial.write(midinote[i][j]);
            Serial.write(127);
            keypressed[i][j] = true;
           }
         if ((digitalRead(j+8) == HIGH) &amp;&amp; keypressed[i][j]){
            Serial.write(0x91);
            Serial.write(midinote[i][j]);
            Serial.write(0);
            keypressed[i][j] =false;
         } 
      }
digitalWrite(i+2, HIGH);
   }

 }
It is better to use interrupts instead of pooling pins.
but this is related to your arduino controller.
what is you arduino core controller?
if you can select I prefer &quot;Nano 33 IoT &quot; which has 9 pins (2, 3, 9, 10, 11, 13, 15, A5, A7) available for interrupt.
this page may be usable:
https://playground.arduino.cc/Main/PinChangeInterrupt/