Arduino Read Switch and Display on LED.JPG

Code

  1. /*
  2. Read Switch and Display on LED
  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. // set pin numbers:
  18. const int buttonPin = 2; // the number of the pushbutton pin
  19. const int ledPin = 13; // the number of the LED pin
  20. // variables will change:
  21. int buttonState = 0; // variable for reading the pushbutton status
  22. void setup() {
  23. // initialize the LED pin as an output:
  24. pinMode(ledPin, OUTPUT);
  25. // initialize the pushbutton pin as an input:
  26. pinMode(buttonPin, INPUT);
  27. }
  28. void loop(){
  29. // read the state of the pushbutton value:
  30. buttonState = digitalRead(buttonPin);
  31. // check if the pushbutton is pressed.
  32. // if it is, the buttonState is HIGH:
  33. if (buttonState == HIGH) {
  34. // turn LED on:
  35. digitalWrite(ledPin, HIGH);
  36. }
  37. else {
  38. // turn LED off:
  39. digitalWrite(ledPin, LOW);
  40. }
  41. }