1
#include <Keypad.h>
#include <Joystick.h>

const byte ROWS = 2;
const byte COLS = 5; 

char keys[ROWS][COLS] = {
  {'1', '2', '3', '4', '5'},
  {'6', '7', '8', '9', '10'},
};

byte rowPins[ROWS] = {8, 9};
byte colPins[COLS] = {3,4,5,6,7};

#define NUM_BUTTONS (ROWS * COLS)

Keypad customKeypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS);

// ----------------------------------------------------
// 2. CONFIGURACIÓN DEL DISPOSITIVO JOYSTICK
// ----------------------------------------------------

// Modificado para 4 botones y sin ejes/otros
Joystick_ Joystick(JOYSTICK_DEFAULT_REPORT_ID,
                   JOYSTICK_TYPE_GAMEPAD, NUM_BUTTONS, 0, 
                   false, false, false,  
                   false, false, false,  
                   false, false);        

// ----------------------------------------------------
// 3. SETUP Y LOOP
// ----------------------------------------------------

void setup() {
  Serial.begin(115200); 
  //Serial.println("Iniciando Matriz 2x2 y Joystick...");
  
  // Inicia el dispositivo Joystick
  Joystick.begin();
}

void loop() {
  // Escanea la matriz y actualiza el estado interno de todas las teclas
  customKeypad.getKeys();

  // Recorre todas las 4 teclas para verificar su estado
  for (int i = 0; i < ROWS * COLS; i++) {
    
    // Accede directamente al estado de la tecla actual en el array .key[]
    switch (customKeypad.key[i].kstate) {
      case PRESSED:
      {
        char pressedKey = customKeypad.key[i].kchar;
        int buttonNumber = pressedKey - '1'; 

        //Serial.print("Boton PRESSED: ");
        //Serial.println(pressedKey);

        // Presiona el boton virtual en el dispositivo Joystick
        Joystick.setButton(buttonNumber, 1);
        break;
      }
      
      case RELEASED:
      {
        char releasedKey = customKeypad.key[i].kchar;
        int buttonNumber = releasedKey - '1';

        //Serial.print("Boton RELEASED: ");
        //Serial.println(releasedKey);
        
        // Suelta el boton virtual en el dispositivo Joystick
        Joystick.setButton(buttonNumber, 0);
        break;
      }
      
      // Para las teclas HOLD y IDLE no hacemos nada en este caso
      case HOLD:
      case IDLE:
        break;
    }
  }
}

For immediate assistance, please email our customer support: [email protected]

Download RAW File