EP1000

Interfacing switches

Here are some tips on using a switch with the Arduino system (or any microcontroller system for that matter)

Toggle switch

In this scenario, we will use a push button switch to change the state of an LED. However, we will TOGGLE the state of the LED by pressing the push button.

We will also ONLY change the state of the LED after each push. Hence, we will need to check the following states of the switch:

Pushbutton switch states

Circuit diagram

Code

lastSWState set to HIGH
Loop
	read switch
	if switch is pressed (LOW)
		debounce switch
		if switch is pressed (LOW)
			if lastSWState is HIGH
				process the switch
				toggle the LED
				lastSWState set to LOW to prevent further processing
			end-if
		else
			do-nothing
		end-if
	else
		lastSWState set to HIGH (gone back to original state)
	end-if
end-loop

We can implement the above logic using Arduino code:

const int SW = 7;
const int LED = 13;

int ledState = LOW;
int lastSWState = HIGH;

void setup(){
  pinMode(SW, INPUT);
  pinMode(LED, OUTPUT);
  digitalWrite(LED, ledState);
}


void loop() {
  int reading = digitalRead(SW);

  if (reading == LOW){
    // debounce SW
    delay(50);
    reading = digitalRead(SW);
    if (reading == LOW){
      // yes still low
      // check whether it went high yet
      if (lastSWState == HIGH){
      	  // toggle LED
          ledState = !ledState;
          digitalWrite(LED, ledState);
          // prevent any processing until SW returns to normal
          lastSWState = LOW;
      }
    }
  }
  else{
  	// SW returns to normal state
    lastSWState = HIGH;
  }
}

Updated: January 2021