Thursday, September 6, 2018

Day3 Lab

const int LED=9; //The LED is connected to pin 9
const int BUTTON=2; //The Button is connected to pin 2
const int LED2=10; //The LED is connected to pin 10
const int BUTTON2=4; //The Button is connected to pin 3
boolean lastButton = LOW; //Variable containing the previous button state
boolean currentButton = LOW; //Variable containing the current button state
boolean ledOn = false; //The present state of the LED (on/off)
boolean lastButton2 = LOW; //Variable containing the previous button state
boolean currentButton2 = LOW; //Variable containing the current button state
boolean led2On = false; //The present state of the LED (on/off)
void setup()
{
 pinMode (LED, OUTPUT); //Set the LED pin as an output
 pinMode (BUTTON, INPUT); //Set button as input (not required)
  pinMode (LED2, OUTPUT); //Set the LED2 pin as an output
 pinMode (BUTTON2, INPUT); //Set button2 as input (not required)
}
/*
* Debouncing Function Pass it the previous button state,
* and get back the current debounced button state.
*/
boolean debounce(boolean last)
{
 boolean current = digitalRead(BUTTON);
 if (last != current) //if it's different…
 {
 delay(5); //wait 5ms
 current = digitalRead(BUTTON); //read it again
 return current; //return the current value
}
}
boolean deboucnce(boolean Last)
{
 boolean current2 = digitalRead(BUTTON2);//Read the button2 state
 if (Last != current2) //if it's different…
 {
  delay(5); // wait 5ms
  current2 = digitalRead(BUTTON2); //read it again
  return current2; //return the current value
}
}
void loop()
{
 currentButton = debounce(lastButton); //read debounced state
 if (lastButton == LOW && currentButton == HIGH) //if it was pressed...
 {
 ledOn = !ledOn; //toggle the LED value
 }
 lastButton = currentButton; //reset button value
 digitalWrite(LED, ledOn); //change the LED state
 {
 currentButton2 = debounce(lastButton2); //read debounced state
  if (lastButton2 == LOW && currentButton2 == HIGH) //if it was pressed...
{
  led2On =!led2On; // toggle the LED2 value
  }
 lastButton2 = currentButton2; //reset button value
  digitalWrite(LED2, led2On); //change the LED state
}
}

No comments:

Post a Comment