Controlling the brightness of an LED with a pushbutton.
We began by hooking up the Arduino and breadboard with an LED connected with PWM pin, as shown in Getting Started with Arduino, 2nd Edition.
After we successfully connected it, we then connected the pushbutton to the breadboard.
Having both the pushbutton and the LED both connected to the Arduino through the ground circuit provides power and ground where it is needed to make them work.
Clicking the pushbutton results in the fading of the brightness of the LED.
The picture does not do it justice, the LED would turn on when pressed and fade out.
Check out our code:
// Example 02: Turn on LED while the button is pressed
const int LED = 13; // the pin for the LED
const int BUTTON = 7; // the input pin where the
// pushbutton is connected
int val = 0; // val will be used to store the state
// of the input pin
void setup() {
pinMode(LED, OUTPUT); // tell Arduino LED is an output
pinMode(BUTTON, INPUT); // and BUTTON is an input
}
void loop(){
val = digitalRead(BUTTON); // read input value and store it
// check whether the input is HIGH (button pressed)
if (val == HIGH) {
digitalWrite(LED, HIGH); // turn LED ON
} else {
digitalWrite(LED, LOW);
}
}
No comments:
Post a Comment