push_button_pull_up.ino 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /*
  2. Button
  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. Serial.begin(9600);
  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. Serial.print(buttonState);
  28. Serial.print("\n");
  29. // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  30. if (buttonState == LOW) {
  31. // turn LED on:
  32. digitalWrite(ledPin, HIGH);
  33. } else {
  34. // turn LED off:
  35. digitalWrite(ledPin, LOW);
  36. }
  37. }