VandanRogheliya

Button Code - Vandan

Aug 27th, 2020
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.05 KB | None | 0 0
  1. /*
  2.  
  3.   State change detection (edge detection)
  4.  
  5.   Often, you don't need to know the state of a
  6.   digital input all the time,  but you just need
  7.   to know when the input changes from one state to
  8.   another.  For example, you want to know when a
  9.   button goes from OFF to ON.  This is called
  10.   state change detection, or edge detection.
  11.  
  12.   This example shows how to detect when a button
  13.   or button changes from off to on  and on to off.
  14.  
  15.  
  16.   The circuit:
  17.   * pushbutton attached to pin 2 from +5V
  18.   * 10K resistor attached to pin 2 from ground
  19.   * LED attached from pin 13 to ground (or use the
  20.   built-in LED on  most Arduino boards)
  21.  
  22.   This example code is in the public domain.
  23.   http://www.arduino.cc/en/Tutorial/ButtonStateChange
  24. */
  25.  
  26. int buttonState = 0;
  27.  
  28. int lastButtonState = 0;
  29.  
  30. int buttonPushCounter = 0;
  31.  
  32. void setup()
  33. {
  34.   pinMode(2, INPUT);
  35.   Serial.begin(9600);
  36.  
  37.   pinMode(13, OUTPUT);
  38. }
  39.  
  40. void loop()
  41. {
  42.   // read the pushbutton input pin
  43.   buttonState = digitalRead(2);
  44.   // compare the buttonState to its previous state
  45.   if (buttonState != lastButtonState) {
  46.     // if the state has changed, increment the counter
  47.     if (buttonState == HIGH) {
  48.       // if the current state is HIGH, then the button
  49.       // went from off to on
  50.       buttonPushCounter += 1;
  51.       Serial.println("on");
  52.       Serial.print("number of button pushes: ");
  53.       Serial.println(buttonPushCounter);
  54.     } else {
  55.       // if the current state is LOW, then the button
  56.       // went from on to off
  57.       Serial.println("off");
  58.     }
  59.     // delay a little bit to avoid debouncing
  60.     delay(5); // Wait for 5 millisecond(s)
  61.   }
  62.   // save the current state as the last state, for
  63.   // the next time through the loop
  64.   lastButtonState = buttonState;
  65.   // turns on the LED every four button pushes by
  66.   // checking the modulo of the button push counter.
  67.   // the modulo function gives you the remainder of
  68.   // the devision of two numbers
  69.   if (buttonPushCounter % 4 == 0) {
  70.     digitalWrite(13, HIGH);
  71.   } else {
  72.     digitalWrite(13, LOW);
  73.   }
  74. }
Add Comment
Please, Sign In to add comment