Arduino Sketch for sending sensor turn on/off to computer I'm having this Arduino Sketch:

#define maxDigitalPin 7 //musn't be greater than 127

boolean state[] = { false, false, false, false, false, false };
unsigned long nextTime[] = { 0, 0, 0, 0, 0, 0 };

void setup(){
  Serial.begin(9600);

  for(int i = 2; i &lt;= maxDigitalPin; i++){
    pinMode(i, INPUT_PULLUP);
  }
}

void loop(){
  for(int i = 2; i &lt;= maxDigitalPin; i++){
    int arrayIndex = i - 2;
    if(digitalRead(i) == LOW &amp;&amp; !state[arrayIndex] &amp;&amp; millis() &gt; nextTime[arrayIndex]){
      Serial.write(i ^ 128);
      state[arrayIndex] = true;
    }
    else if(state[arrayIndex] &amp;&amp; digitalRead(i) == HIGH){
      Serial.write(i);
      state[arrayIndex] = false;
      nextTime[arrayIndex] = millis() + 500;
    }
  }
}


It will send a byte to a computer when a sensor goes on and when it goes back off.

The byte looks like:

SPPP PPPP


S is 1 when the sensor has gone on and 0 when it has gone off. P is the pin.

This code prevents sending the on message for a pin for 500ms after it has gone off. This is intended and really necessary. 

My concerns:


Is it possible to reduce the code to only use one array?
I fear this sketch will be slow once it's using more than 7 pins because it's really important that the computer gets informed pretty instantly.


Of course if there is anything else to improve I would like to hear it too.
If I understand correctly, your goal is to report all state changes; a 500 ms blackout is undesirable. If I am correct, read on.

You don't need the nextTime array at all. Change the state array from false/true to LOW/HIGH:

level = digitalRead(i);
if (level != state[arrayIndex]) {
    state[arrayIndex] = level;
    serialWrite(i | (level &lt;&lt; 8));
}


(I am assuming that LOW == 0, and HIGH == 1).

Regarding performance: the code runs a busy loop, which is usually undesirable, especially in the embedded world. I seriously recommend to connect your pins to an interrupt, and rewrite the code into a reactive model.