//=============================================================================
// iR Hackpad Demo Firmware
// Compile for Arduino Leonardo
//=============================================================================

// The Arduino Keyboard library creates a HID keyboard interface to send keyboard scancodes to the host.
// For convenience, the class takes ASCII characters via Keyboard::write(), which are automatically
// converted to the corresponding keboard scan-codes according to the keyboard layout passed to
// Keyboard::begin(). On the host side, the scan-codes are again converted to characters by the OS.
#include "Keyboard.h"

//=============================================================================
// Our key matrix (see schematics)
const int N_rows = 5;
const int N_cols = 4;
const int gpio_rows[N_rows] = { 6, 7, 8, 9, 5 };
const int gpio_cols[N_cols] = { 15, 14, 16, 10 };

// Key function assignment: ASCII characters or special function codes (see Keyboard.h)
const int key_matrix[N_rows][N_cols] = {
  {'a', 'b', 'c', 'd'},  // 4x4 keypad
  {'e', 'f', 'g', 'h'},
  {'i', 'j', 'k', 'l'},
  {'m', 'n', 'o', 'p'},
  {'_', '_', '_', 'x'}   // rotery encoder button
};
int is_pressed[N_rows][N_cols] = { 0 };

const uint32_t KEY_SCAN_DELAY_US = 100;  // Delay between row scans

//=============================================================================

void setup()
{
  for (int col=0; col<N_cols; col++) {
    pinMode(gpio_cols[col], INPUT_PULLUP);  // Key matrix columns as inputs
  }
  for (int row=0; row<N_rows; row++) {
    digitalWrite(gpio_rows[row], HIGH);
    pinMode(gpio_rows[row], OUTPUT);  // Key matrix rows as outputs
  }
  Keyboard.begin(KeyboardLayout_de_DE);
  Serial.begin(9600);  // Open serial port to host, so the IDE can reset the device for reprogramming
}

//=============================================================================

void loop()
{
  for (int row=0; row<N_rows; row++) {
    digitalWrite(gpio_rows[row], LOW);
    for (int col=0; col<N_cols; col++) {
      if (digitalRead(gpio_cols[col]) == LOW){
        is_pressed[row][col] = true;
        Keyboard.press(key_matrix[row][col]);
        } else if (is_pressed[row][col]) {
          Keyboard.release(key_matrix[row][col]);
          is_pressed[row][col] = false;
        }
      delayMicroseconds(KEY_SCAN_DELAY_US);  // Give the column inputs time to reach HIGH state (slow recharge via weak pullups)
    }
    digitalWrite(gpio_rows[row], HIGH);
  }
}

//=============================================================================
