For the next PCOMP lab, I made a combination lock that would “open” (light a green LED) after the button was pressed four times. This was not that hard to set up on the bread board as much as getting the programming right. The logic and syntax was pretty new to me, but Jeff was kind enough to offer just enough advice to let me figure it out. The big revelation was using currentButtonState and previousButtonState as a way to track the state of the button, mainly if the state had changed at any moment since the loop restarted ( previousButtonState = currentButtonState; ). This gave the loop a sense of incremental time so that the number of button presses (or state changes) could be counted by incrementing the pressCount variable inside of an IF statement.
Here is the code:
// a combination lock which opens after 4 button presses //three LEDs, one switch int switchPatch = 2; int yellowLED = 3; int redLED = 4; int greenLED = 5; int currentButtonState; int previousButtonState; int pressCount = 0; void setup() { pinMode(switchPatch, INPUT); pinMode(yellowLED, OUTPUT); pinMode(redLED, OUTPUT); pinMode(greenLED, OUTPUT); Serial.begin(9600); } void loop() { //read the button at dig pin 2 currentButtonState = digitalRead(switchPatch); //if the state of the button changes if (currentButtonState != previousButtonState) { // and if the currentButtonState is not equal to the previous state // the button has either been pressed or released (something has changed) // so if the button stage has changed AND that state reads HIGH, then // the button has been pressed if (currentButtonState == HIGH) { // so turn on the yellowLED digitalWrite(yellowLED, HIGH); // and turn off the redLED digitalWrite(redLED, LOW); // and increase pressCount to track how many times this will happen pressCount++; } else { //otherwise the button has not been pressed // so keep the red LED on and yellow off digitalWrite(redLED, HIGH); digitalWrite(yellowLED, LOW); } } // if we press the button 4 times then... if (pressCount == 4) { //turn the green led ON digitalWrite(greenLED, HIGH); // and reset the counter pressCount = 0; } else { // otherwise keep the green LED off digitalWrite(greenLED, LOW); } // make the currentButtonState = to the previousButtonState just before // the loop starts over previousButtonState = currentButtonState; // print the pressCount value in the Serial Monitor Serial.print(pressCount); }