Any switch is made of two conductive mechanical contacts that are either touching each other (closed circuit) or not (open circuit). When they make contact, the contact is not always perfect. For the fraction of s second before the contact is complete, the circuit may make contact and be broken several times. When you read this input on a microcontroller, you’ll see a rapid switching from 0 to 1 over a few milliseconds until the contact is final.
To avoid this, you can debounce the switch. This just means that if contact is made, you wait a few milliseconds, then check it again before taking action. Here’s an example:
switchClosedVar var byte
Input portd.1
main:
if portd.1 = 1 then
pause 10 ‘ change the time if your switch still bounces
if portd.1 = 1 then
switchClosedVar = 1
else
switchClosedVar = 0
endif
endif
goto main
Here it is in Arduino/Wiring syntax:
int switchPin = 2;
int switchState = 0;
int switchClosedVar = 0;
void setup() {
pinMode(switchPin, INPUT);
}
void loop() {
switchState = digitalRead(switchPin);
if (switchState == 1) {
delay(10); // change the time if your switch still bounces
switchState = digitalRead(switchPin);
if (switchState == 1) {
switchClosedVar = 1;
} else {
switchClosedVar = 0;
}
}
}