Connecting a push button and an LED to the Arduino
Sketch source code
#define LED 13
#define BUTTON 1
#define INTERVAL 50 // milliseconds
void setup()
{
pinMode( LED, OUTPUT );
pinMode( BUTTON, INPUT );
}
void loop()
{
if ( digitalRead( BUTTON ) == HIGH )
digitalWrite( LED, HIGH );
else
digitalWrite( LED, LOW );
delay( INTERVAL ); // debouncing
}
Comments
The
digitalRead() function only returns 2 values,
HIGH when the push button is
pressed down or
LOW when the
push button is released.
Similarly, the
digitalWrite() function accepts 2 states,
HIGH to
turn the pin on or
LOW to
turn the pin off.
The
delay() function at line 18 is a rudimentary method of debouncing the the noise due to the mechanical switch in the button not making perfect contact.
