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);
}
}
}