Advertisement
baldengineer

Analog Buttons

Dec 29th, 2014
340
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.05 KB | None | 0 0
  1. // Provides a definition for each of the buttons
  2. #define btnRIGHT   1
  3. #define btnUP      2
  4. #define btnDOWN    3
  5. #define btnLEFT    4
  6. #define btnSELECT  5
  7. #define btnNONE    0
  8.  
  9.  
  10. int inPin = A0;         // the number of the input pin
  11. int outPin = 13;       // the number of the output pin
  12.  
  13. int state = HIGH;      // the current state of the output pin
  14. int reading;           // the current reading from the input pin
  15. int previous = LOW;    // the previous reading from the input pin
  16.  
  17. // the follow variables are long's because the time, measured in miliseconds,
  18. // will quickly become a bigger number than can be stored in an int.
  19. unsigned long time = 0;         // the last time the output pin was toggled
  20. unsigned long debounce = 200;   // the debounce time, increase if the output flickers
  21.  
  22. void setup()
  23. {
  24.   pinMode(outPin, OUTPUT);
  25. }
  26.  
  27. void loop()
  28. {
  29.   reading = read_LCD_buttons(inPin);  // checks to see which button is currently pressed, if any
  30.  
  31.   // if the input just went from LOW and HIGH and we've waited long enough
  32.   // to ignore any noise on the circuit, toggle the output pin and remember
  33.   // the time
  34.   if ( (reading > 0) && (previous == LOW) && ((millis() - time) > debounce) ) {
  35.     switch (reading) {
  36.     case btnRIGHT:
  37.       // the right button was pressed.
  38.       // toggles the state of the LED pin
  39.       state = !state;
  40.       break;
  41.  
  42.     case btnUP:
  43.       // Up button was pressed.
  44.       break;
  45.  
  46.     default:
  47.       // no button was pressed?
  48.       break;
  49.     }
  50.     time = millis();    
  51.   }
  52.  
  53.   // Constantly "writing" the state of the pin
  54.   digitalWrite(outPin, state);
  55.  
  56.   previous = reading;
  57. }
  58.  
  59. int read_LCD_buttons(int pinToRead)
  60. {
  61.   int adc_key_in = analogRead(pinToRead);      
  62.   delay(5);
  63.   if (5 < abs(adc_key_in)) return btnNONE;  
  64.  
  65.   if (adc_key_in > 1000) return btnNONE;
  66.   if (adc_key_in < 50)   return btnRIGHT;  
  67.   if (adc_key_in < 195)  return btnUP;
  68.   if (adc_key_in < 380)  return btnDOWN;
  69.   if (adc_key_in < 555)  return btnLEFT;
  70.   if (adc_key_in < 790)  return btnSELECT;  
  71.   return btnNONE;  
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement