how to convert the following code into one using direct port manipulation
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/