Sunday, November 5, 2017

Lab 3 - Digital Inputs and Indexed Loops

CLASSWORK:
Blinking LED with For Loop (aka PWM)
const int LED=9; //define LED for Pin 9
void setup()
{
 pinMode (LED, OUTPUT); //Set the LED pin as an output
}
void loop()
{
 for (int i=100; i<=1000; i=i+100)
 {
 digitalWrite(LED, HIGH);
 delay(i);
 digitalWrite(LED, LOW);
 delay(i);
 }

}

LED with Changing Brightness
const int LED=9; //define LED for Pin 9
void setup()
{
 pinMode (LED, OUTPUT); //Set the LED pin as an output
}
void loop()
{
 for (int i=0; i<256; i++)
 {
 analogWrite(LED, i);
 delay(10);
}
 for (int i=255; i>=0; i--)
 {
 analogWrite(LED, i);
 delay(10);
 }

}

Basic Button Without Debounce
const int LED=9; //The LED is connected to pin 9
const int BUTTON=2; //The Button is connected to pin 2
void setup()
{
 pinMode (LED, OUTPUT); //Set the LED pin as an output
 pinMode (BUTTON, INPUT); //Set button as input (not required)
}
void loop()
{
 if (digitalRead(BUTTON) == LOW)
 {
 digitalWrite(LED, LOW);
 }
 else
 {
 digitalWrite(LED, HIGH);
 }

}

HOMEWORK:
Basic Button With Debounce
const int LED=9; //The LED is connected to pin 9
const int BUTTON=2; //The Button is connected to pin 2
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)
void setup()
{
 pinMode (LED, OUTPUT); //Set the LED pin as an output
 pinMode (BUTTON, INPUT); //Set button 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); //Read the button state
 if (last != current) //if it's different…
 {
 delay(5); //wait 5ms
 current = digitalRead(BUTTON); //read it again

 return current; //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

}



No comments:

Post a Comment