Arduino Read Switch and Display on LED.JPG

Code

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