There are several possible reasons random values are seen at micro controller inputs when connected to switches. Here are two:
- Missing pull up or pull down resistor when using a SPST switch.
Micro controller inputs should not be allowed to float. This can lead to unexpected input states. Instead, inputs should be connected to ground or the micro controller's positive voltage supply usually either directly or though a resistor. It is common to use a pull up resistor when using a SPST switch connected to ground. Or a pull down resistor when using a SPST switch connected to the micro controller's positive voltage supply. Not all micro controllers have pull up or pull down resistors built internally. Some only have one or the other. In these cases an external resistor may be required. Some thought should be given to using micro controllers that do have built in pull up or pull down resistors. The actual resistance value of these built in resistors does vary (may not be carefully controlled). This is fine for the majority of cases. However, if a specific value is needed, it may be best if external resistors were used instead.
- Long wires between the micro controller and the switch.
Longer wires are more likely to develop unexpected currents due external electrical noise. It is possible wires are long enough and the environment they are in electrically noisy enough to develop currents that will change the voltage across a pull up or pull down resistor. And, in turn, change the value of the micro controller's input. The higher the resistor value the more likely this will happen. However, the lower the resistor value chosen the more power needed when the SPST switch is closed. This is usually a concern when operating on batteries. There are many aspects to mitigating the effects of electrical noise. And will take us off subject. Instead, if long wires are necessary, consider using a "brake-before-make" SPDT switch which will connect the micro controller's input pin directly to ground or the micro controller's positive supply voltage. This will require running 3 rather than 2 wires to the switch.
Last words: Take care not to connect pull up resistors or switches to voltages higher than the micro controller's positive supply voltage! Some Arduino boards regulate higher voltages to lower voltage before supplying power to the micro controller. For instance, an Arduino board that runs from the 5 Volt USB power source may have a micro controller which actually runs at 3.3 Volt. In such a case, use the 3.3 Volts supplied to the micro controller when connecting a pull up resistor or switch.