Advertisement
microrobotics

4-Key Membrane Switch Keypad

Apr 26th, 2023
1,026
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. To use a 4-Key Membrane Switch Keypad with an Arduino or an ESP32, you will need to connect each button to a digital input pin on the microcontroller. Here's an example of how to read the keypad input and print the key press to the Serial Monitor:
  3.  
  4. Hardware Requirements:
  5.  
  6. 4-Key Membrane Switch Keypad
  7. Arduino or ESP32 development board
  8. Jumper wires
  9. Connection:
  10.  
  11. Connect the 4 pins of the membrane keypad to 4 digital input pins on the Arduino or ESP32. In this example, we'll use pins 2, 3, 4, and 5.
  12.  
  13. This code sets up the digital input pins with internal pull-up resistors, reads the state of each button, and prints the button number to the Serial Monitor when a button is pressed. The code also includes a 200ms debounce delay to avoid false triggers or multiple triggers caused by mechanical vibrations in the switch.
  14.  
  15. You can customize the code to perform different actions depending on the button pressed. For example, you could control LEDs, motors, or other components in response to the button inputs.
  16. */
  17.  
  18. const int buttonPins[] = {2, 3, 4, 5};
  19. const int numButtons = sizeof(buttonPins) / sizeof(buttonPins[0]);
  20.  
  21. void setup() {
  22.   for (int i = 0; i < numButtons; i++) {
  23.     pinMode(buttonPins[i], INPUT_PULLUP);
  24.   }
  25.   Serial.begin(115200);
  26. }
  27.  
  28. void loop() {
  29.   for (int i = 0; i < numButtons; i++) {
  30.     int buttonState = digitalRead(buttonPins[i]);
  31.     if (buttonState == LOW) {
  32.       Serial.print("Button ");
  33.       Serial.print(i + 1);
  34.       Serial.println(" pressed");
  35.       delay(200); // Debounce delay
  36.     }
  37.   }
  38. }
  39.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement