Wednesday, June 27, 2012

A mapping to the keyboard tutorial

// not a full "lab" per se but it does have the possibility to be developed into one. This is based on my experience working with the KIns.

To get ChucK working with the keyboard, there are a few essential things to include in your code:

1.
// keyboard
HidIn kb;
// hid message
HidMsg msg;

In the above code, "Hid" stands for "Human Interface (possibly also input?) Device." AKA a device that you use to interact with your computer, like the keyboard. The first line defines the variable that will represent the HID, and the second defines the variable that will hold the information we receive from the HID.

2. 
// If the keyboard is not available, just exit the program right away
if( !kb.openKeyboard( 0 ) ) me.exit();
//Otherwise, assuming the program didn't exit on the last line, keep going
<<< "Ready?", "" >>>;

These lines are not critical, but helpful to include in a file, especially for debugging purposes. Obviously you can change them around to suit your tastes, such as only printing out a message if the keyboard *doesn't* open instead of if it does.

3.
// wait for event
    kb => now;

The above lines go inside the event loop, which is the (usually infinite) loop that makes the program run. They'll probably be the first thing inside the loop, unless your program has a reason for them not to be. Basically they pause the loop until the HID has a message to send.

4.
kb.recv( msg )

When this function returns true, a key is being held down. It's probably best used in a while loop or if statement, such as while( kb.recv( msg ) ){....} That will execute the body of the loop as long as a key is being held down.

5. msg.which

The value of this variable contains an int that corresponds to the key that's being held down. Operators like ==, >, <, != can be used to work with it to assign different actions to different keys.


These are the most important things to understand when working with keyboard input. Using them, you can construct an array of values of the keys on your keyboard that correspond to meaningful values. For example, to make a program that plays notes when the keyboard is pressed, you could make an array in which the index of the array is the frequency of the note, and the data that corresponds to any given index is the key mapping integer.

How can we find out the key mapping integers if we don't know them or have a reference though? An easy, if tedious, way to do it is to simply print out msg.which whenever a keypress event is received. You can then write your own table by going through each key on your keyboard.

No comments:

Post a Comment