// Item Three—Mini Lamp
int buttonPin = 2; // button to be connected to digital pin No.2
int ledPin = 13; // LED to be connected to digital pin No.13
int ledState = HIGH; // ledState records the state of LED light
int buttonState; //buttonState records the stat of the button
// lastbuttonState records the previous status of the button
int lastButtonState = LOW;
long lastDebounceTime = 0;
long debounceDelay = 50; // eliminate the oscillation time
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, ledState);
}
void loop() {
//reading stores buttonPin’s data
int reading = digitalRead(buttonPin);
//record the time when data changes
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
// Wait for 50ms and check if it’s in line with the button’s current status
// If it’s not in line with the button’s current status, change the button’s
status
//Meanwhile, if the button is set to be in the mode of HIGH (meaning the
button has been pressed), led’s status shall be changed.
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;
if (buttonState == HIGH) {
ledState = !ledState;
}
}
}
digitalWrite(ledPin, ledState);
//Change the button’s previous state value
lastButtonState = reading;
}
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
int reading = digitalRead(buttonPin);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;
if (buttonState == HIGH) {
ledState = !ledState;
}
}
}