Arduino Read Switch and Display on LED.JPG

Code

  1. /*
  2. Button
  3.  
  4. Turns on and off a light emitting diode(LED) connected to digital
  5. pin 13, when pressing a pushbutton attached to pin 2.
  6.  
  7.  
  8. The circuit:
  9. * LED attached from pin 13 to ground
  10. * pushbutton attached to pin 2 from +5V
  11. * 10K resistor attached to pin 2 from ground
  12.  
  13. * Note: on most Arduinos there is already an LED on the board
  14. attached to pin 13.
  15.  
  16.  
  17. // constants won't change. They're used here to
  18. // set pin numbers:
  19. const int buttonPin = 2; // the number of the pushbutton pin
  20. const int ledPin = 13; // the number of the LED pin
  21. // variables will change:
  22. int buttonState = 0; // variable for reading the pushbutton status
  23. void setup() {
  24. // initialize the LED pin as an output:
  25. pinMode(ledPin, OUTPUT);
  26. // initialize the pushbutton pin as an input:
  27. pinMode(buttonPin, INPUT);
  28. }
  29. void loop(){
  30. // read the state of the pushbutton value:
  31. buttonState = digitalRead(buttonPin);
  32. // check if the pushbutton is pressed.
  33. // if it is, the buttonState is HIGH:
  34. if (buttonState == HIGH) {
  35. // turn LED on:
  36. digitalWrite(ledPin, HIGH);
  37. }
  38. else {
  39. // turn LED off:
  40. digitalWrite(ledPin, LOW);
  41. }
  42. }