Digital read problem: Toggles HIGH/LOW to LOW/HIGH on its own

I'm reading a digital input switch with the below program snip. The code shown is to toggle between upper and lowercase from a keyboard (actually a typewriter). It branches to one of two functions (basically lookup tables) to match an analog value to an ASCII value. It's stable and works just fine, except for the fact that at times after a reboot LOW and HIGH trade places. To be clear, the switch keeps working perfectly for the duration of the run, but backwards -- so it's not likely noise.

The physical switch is a Hall sensor that outputs 1/0. It's set to input pullup in setup, and no external resistor is used. It's driving me crazy. The program is otherwise complete and working well.

// UPPERCASE LOWERCASE TOGGLE______________________________________________

valb = digitalRead(sensorD8); //Read the sensor


if (valb == HIGH) {
Serial.println(valb); // observe value for testing
  readcounts(); //function call to lookup table
 

}
else if (valb == LOW) {
 Serial.println(valb);
  readcountsupper();
}

}
}

Welcome to the group.

Show us a good schematic of your proposed circuit.
Show us a good image of your ‘actual’ wiring.
Give links to components.

In the Arduino IDE, use Ctrl T or CMD T to format your code then copy the complete sketch.

Use the </> icon from the ‘reply menu’ to attach the copied sketch.

Please post your full sketch. Please indicate which board you're using.

Your topic has been moved to a more suitable location on the forum. Installation and Troubleshooting is not for problems with (nor for advise on) your project :wink: See About the Installation & Troubleshooting category.

Easier yet- CTRL-T to format the code, then right-click on the code and click on "Copy for Forum", then paste that into the forum.

Actually, you don't even need to right click, I just tried without that and it selects the entire sketch automatically.

Indeed it does. :sunglasses:

Do you have a logic probe or multimeter?

Can you use that or something else (LED switched by a transistor = poor man's logic probe) to see what's actually presented to the pin?

The problem may be in the code we can't see…

a7

in other words,
else {

Actually, here's the whole thing:

valb = digitalRead(sensorD8); //Read the sensor
Serial.println(valb);
if (valb == HIGH)
  readcounts(); //function call to lookup table
 else
  readcountsupper();