Diagnosing Unstable Digital Input Readings on Arduino: A Pin Configuration Guide
Unstable digital readings from an Arduino switch usually mean the input pin is 'floating.' Use INPUT_PULLUP in pinMode() or add external resistors to define a stable HIGH or LOW state.