Advertisement
belrey10

Lesson #3: Push Button

Nov 3rd, 2024 (edited)
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.   Button
  3.  
  4.   Turns on and off a light emitting diode(LED) connected to digital pin 8,
  5.   when pressing a pushbutton attached to pin 2.
  6.  
  7.   The circuit:
  8.   - LED attached from pin 8 to ground
  9.   - pushbutton attached to pin 2 from +5V
  10.   - 10K resistor attached to pin 2 from ground
  11.  
  12.   - Note: on most Arduinos there is already an LED on the board
  13.     attached to pin 13.
  14.  
  15.   created 2005
  16.   by DojoDave <http://www.0j0.org>
  17.   modified 30 Aug 2011
  18.   by Tom Igoe
  19.  
  20.   This example code is in the public domain.
  21.  
  22.   http://www.arduino.cc/en/Tutorial/Button
  23. */
  24.  
  25. // constants won't change. They're used here to set pin numbers:
  26. const int buttonPin = 2;     // the number of the pushbutton pin
  27. const int ledPin =  8;      // the number of the LED pin
  28.  
  29. // variables will change:
  30. int buttonState = 0;         // variable for reading the pushbutton status
  31.  
  32. void setup() {
  33.   // initialize the LED pin as an output:
  34.   pinMode(ledPin, OUTPUT);
  35.   // initialize the pushbutton pin as an input:
  36.   pinMode(buttonPin, INPUT);
  37. }
  38.  
  39. void loop() {
  40.   // read the state of the pushbutton value:
  41.   buttonState = digitalRead(buttonPin);
  42.  
  43.   // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  44.   if (buttonState == HIGH) {
  45.     // turn LED on:
  46.     digitalWrite(ledPin, HIGH);
  47.   } else {
  48.     // turn LED off:
  49.     digitalWrite(ledPin, LOW);
  50.   }
  51. }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement