Monday, May 8, 2017

Programming the MeinEnigma - Keyboard



I earlier talked about the HT16K33 chip which controls the LEDs. It also scans the keyboard keys which are across part of the same matrix of rows and columns. The chip scans the keyboard for key closures for a brief time when it is not driving the LEDs.

The code to handle keyboard events is implemented using the same library that we used in the LED examples. It provides several functions related to keyboard including keysPressed(), readKey(), and readKeyRaw().

For the example program we will just use readKey(). It returns zero if no key was pressed, a positive number containing a key code if a key was pressed, and a negative key code if a key was released.

I created a lookup table called keys that returns the ASCII character corresponding to a key code. The four buttons under the alphanumeric displays return characters "1" through "4".

The example is very simple. Initialization in the loop() method consists of setting up the serial port and HT16K33 object.

In the main loop we call readKey(). If a key event occured we display to the serial port the ASCII character for the key and whether if was a key press or release.

Here is some sample output:

Key H pressed
Key H released
Key E pressed
Key E released
Key L pressed
Key L released
Key L pressed
Key L released
Key O pressed
Key O released
Key 1 pressed
Key 1 released

More advanced functions, like detecting multiple keys pressed at the same time, can be done with the other functions provided in the ht16k33 library, but the example shows the most basic case of reading the keyboard.

Here is the listing, which can also be found here,

/*
  MeinEnigma Example

  Demonstrates reading the keyboard.
  Uses code from the MeinEnigma software.

  Jeff Tranter

*/

// External library for HT16K33 chip.
#include "ht16k33.h"

// Lookup table of key codes to characters.
const char keys[] = { 'Q','W','E','R','T','Z','U','I','O','A','S','D','F','P','Y','X','C','V','B','N','M','L','G','H','J','K','1','2','3','4' };

// Object instance for HT18K33 chip.
HT16K33 HT;

void setup() {
  Serial.begin(9600); // Initialize serial port for debug output.
  HT.begin(0x00);     // Need to initialize the chip in order for keyboard to work.
}

void loop() {
  int k;

  k = HT.readKey();
  if (k != 0) {
    Serial.print("Key ");
    Serial.print(keys[abs(k)-1]);
    Serial.print(" ");
    if (k > 0) {
      Serial.println("pressed");
    } else
      Serial.println("released");
  }

  delay(100);
}

No comments: