Step 6Using buttons
This is just like the previous example but now the code runs only once after pushing a button. The push button uses a pull down resistor so when the button is pushed the input pin reads HIGH, otherwise it always reads LOW.
Copy and paste this sketch into your Arduino window-
/*
* Example 2
* LED Control using button input
* This example will blink two LEDs and fade another LED when a button is pressed and released
* Honus 2010
* Modified from Adafruit alternating switch code, http://www.adafruit.com
*/
int ledPin1 = 13; // control pin for LED
int ledPin2 = 12;
int ledPin3 = 11;
int buttonPin = 14; // button is connected to pin 14 (analog in pin 0)
int val; // variable for reading the pin status
int buttonState; // variable to hold the last button state
void setup() {
pinMode(buttonPin, INPUT); // set the button pin as input
Serial.begin(9600); // set up serial communication at 9600bps
buttonState = digitalRead(buttonPin); // read the initial state
pinMode(ledPin1, OUTPUT); // sets the LED pin as output
pinMode(ledPin2, OUTPUT);
}
void loop(){
val = digitalRead(buttonPin); // read input value and store it in val
if (val != buttonState) { // the button state has changed!
if (val == LOW) { // check if the button is pressed
Serial.println("button pressed");
digitalWrite(ledPin1, HIGH); // sets the LED pin HIGH (turns it on)
delay(500); // waits 500 milliseconds
digitalWrite(ledPin2, HIGH);
delay(500);
digitalWrite(ledPin1, LOW); // sets the LED pin LOW (turns it off)
delay(500);
digitalWrite(ledPin2, LOW);
delay(500);
// fade in from min to max in increments of 5 points:
for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin3, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(40);
}
// fade out from max to min in increments of 5 points:
for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin3, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(40);
}
} else { // the button is -not- pressed...
Serial.println("button released");
digitalWrite(ledPin1, LOW); // turn the LED off
digitalWrite(ledPin2, LOW);
}
}
buttonState = val; // save the new state in our variable
}
| « Previous Step | Download PDFView All Steps | Next Step » |
![]() |
Add Comment
|























































