I have a debounce issue, but I think it's my code.

I have a relatively simple sketch with 8 of those 1990s style door reed switches.

If I put a delay of 5000 at the top of the loop. Everything works as expected. It only serial prints if the state of a switch changed (so I can send an mqtt message). However, if I take away that delay, when I pull the magnet away, that switch constantly alternates between 0 and 1. Not randomly. It actually bit flips. 0101010. What’s weird is that I can put a full 1000ms delay after updating the state and it still bit flips.

I don’t think it’s a pull up/pull down issue because I’m getting the expected results with the delay. The internal pullup resistor is enough to keep the switch high whether the magnet is there or not, so I’m thinking it has to be something with my code.

Is there something wrong with my logic for how I’m saving the state?

int read = 0;
int switches = 8;
int sw[] = {23,25,27,29,31,33,35,37};
int swstate[] = {0,0,0,0,0,0,0,0};

void setup() {
Serial.begin(9600);
for (int i = 0; i < switches; i++) {
  pinMode(sw[i],INPUT);
  Serial.println(swstate[i]);
}
}

void loop() {
  for (int i = 0; i < switches; i++) {
    Serial.println(swstate[i]);
  }
    for (int i = 0; i < switches; i++) {
    read = digitalRead(sw[i]);
    if(read != swstate[i]){
      swstate[i] = read;
      Serial.print("Switch ");
      Serial.print(i);
      Serial.print(" is now ");
      Serial.println(read);
    }
  }
}

I think after all that, it is a floating pin when there's no magnet. INPUT_PULLUP pulls it high all the time.

Should I use a smaller pullup resistor or should I do a pull down?

The internal pullup resistor is enough to keep the switch high whether the magnet is there or not, so I'm thinking it has to be something with my code.

But the code you posted is not using the internal pullup resistor.

A schematic, and the actual code you are running, would be useful.

Do you really need to be able to change pin numbers at run time? If not, sw should be const. Do you REALLY need to be able to handle negative pin numbers? Or pin numbers over 255? If not, then int is not the appropriate type.

Do you really expect to read more than two states for each pin? It is either HIGH or LOW or floating between those two states. If two states is reasonable, then int as the array type is not.

Get in the habit of using the smallest possible type for all variables.