Advertisement
microrobotics

Waveshare AD Keypad 4 x 4

Apr 17th, 2023
799
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. This code reads the analog value from the keypad using the analogRead() function. The KEY_NONE constant represents the value of the analog pin when no key is pressed.
  3.  
  4. The key values are defined based on the voltage divider ratios of the keypad. The if statements in the loop() function determine which key was pressed based on the analog value
  5. */
  6.  
  7. // define the analog pin for the keypad
  8. const int KEYPAD_PIN = A0;
  9.  
  10. // define the key values
  11. const int KEY_NONE = 1023;
  12. const int KEY_1 = 0;
  13. const int KEY_2 = 75;
  14. const int KEY_3 = 150;
  15. const int KEY_A = 225;
  16. const int KEY_4 = 300;
  17. const int KEY_5 = 375;
  18. const int KEY_6 = 450;
  19. const int KEY_B = 525;
  20. const int KEY_7 = 600;
  21. const int KEY_8 = 675;
  22. const int KEY_9 = 750;
  23. const int KEY_C = 825;
  24. const int KEY_STAR = 900;
  25. const int KEY_0 = 930;
  26. const int KEY_POUND = 970;
  27.  
  28. void setup() {
  29.   // initialize the serial port for debugging
  30.   Serial.begin(9600);
  31.  
  32.   // print a message to the serial port
  33.   Serial.println("Waveshare AD Keypad 4 x 4 ready!");
  34. }
  35.  
  36. void loop() {
  37.   // read the analog value from the keypad
  38.   int analogValue = analogRead(KEYPAD_PIN);
  39.  
  40.   // determine which key was pressed based on the analog value
  41.   int key = KEY_NONE;
  42.   if (analogValue < KEY_1 + 5) {
  43.     key = KEY_1;
  44.   } else if (analogValue < KEY_2 + 5) {
  45.     key = KEY_2;
  46.   } else if (analogValue < KEY_3 + 5) {
  47.     key = KEY_3;
  48.   } else if (analogValue < KEY_A + 5) {
  49.     key = KEY_A;
  50.   } else if (analogValue < KEY_4 + 5) {
  51.     key = KEY_4;
  52.   } else if (analogValue < KEY_5 + 5) {
  53.     key = KEY_5;
  54.   } else if (analogValue < KEY_6 + 5) {
  55.     key = KEY_6;
  56.   } else if (analogValue < KEY_B + 5) {
  57.     key = KEY_B;
  58.   } else if (analogValue < KEY_7 + 5) {
  59.     key = KEY_7;
  60.   } else if (analogValue < KEY_8 + 5) {
  61.     key = KEY_8;
  62.   } else if (analogValue < KEY_9 + 5) {
  63.     key = KEY_9;
  64.   } else if (analogValue < KEY_C + 5) {
  65.     key = KEY_C;
  66.   } else if (analogValue < KEY_STAR + 5) {
  67.     key = KEY_STAR;
  68.   } else if (analogValue < KEY_0 + 5) {
  69.     key = KEY_0;
  70.   } else if (analogValue < KEY_POUND + 5) {
  71.     key = KEY_POUND;
  72.   }
  73.  
  74.   // print the key value to the serial port
  75.   if (key != KEY_NONE) {
  76.     Serial.print("Key pressed: ");
  77.     Serial.println(key);
  78.   }
  79.  
  80.   // wait for a short time
  81.   delay(100);
  82. }
  83.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement