p03_MomentaryButtonControlLED.ino 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. /*
  2. Demo code for Project 3 - Momentary Button Control LED
  3. Turns on and off a light emitting diode(LED) connected to digital
  4. pin 9, when pressing a pushbutton attached to pin 2.
  5. The momentary button will keep the state untill you push it again.
  6. by Maker Studio
  7. http://makerstudio.cc
  8. */
  9. // constants won't change. They're used here to
  10. // set pin numbers:
  11. const int buttonPin = 2; // the number of the pushbutton pin
  12. const int ledPin = 9; // the number of the LED pin
  13. // variables will change:
  14. int buttonState = 0; // variable for reading the pushbutton status
  15. void setup() {
  16. // initialize the LED pin as an output:
  17. pinMode(ledPin, OUTPUT);
  18. // initialize the pushbutton pin as an input:
  19. pinMode(buttonPin, INPUT);
  20. }
  21. void loop(){
  22. // read the state of the pushbutton value:
  23. buttonState = digitalRead(buttonPin);
  24. // check if the pushbutton is pressed.
  25. // if it is, the buttonState is HIGH:
  26. if (buttonState == HIGH) {
  27. digitalWrite(ledPin, HIGH); // turn LED on:
  28. }
  29. else {
  30. digitalWrite(ledPin, LOW); // turn LED off:
  31. }
  32. }