push_button_pull_up.ino 1.2 KB

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