Page 1 of 1

Keyboard waiting for input

Posted: Sat Feb 06, 2010 9:34 am
by matio
I've added keyboard support to my simple os, but how would I implement a function like getch (in C) & raw_input (in Python)?

Re: Keyboard waiting for input

Posted: Sat Feb 06, 2010 10:23 am
by Creature
There are a couple of ways to about this, but an easy way would probably be this:

Code: Select all

volatile unsigned char GotKey = false;
volatile unsigned char Key = 0;

void MyKeyboardIrqHandler()
{
   // Previous key not processed yet?
   if(GotKey)
       return;

   // Handle key events, shifts and stuff like that.

   // At this point, the key is processed and you have the key as a character (I'm assuming you already have something like this).

   GotKey = true;
   Key = processed_key;
}

byte GetNextChar()
{
   GotKey = false;
   while(GotKey == false);

   return Key;
}
Of course this is a very simple implementation and you might want to add the ability to wait for a specific char and stuff, but it pretty much shows a simple implementation. Also take care with the "if(GotKey) return", so you don't let the keyboard buffer overflow by skipping too many reads (but I think IRQ's don't require you to necessarily accept the character by reading port 0x60).

Re: Keyboard waiting for input

Posted: Sat Feb 06, 2010 12:28 pm
by Selenic
Creature wrote:Also take care with the "if(GotKey) return", so you don't let the keyboard buffer overflow by skipping too many reads
The best thing to do would be to process each key as it is pressed. Here's a few reasons why:
- Some keys generate two or three individual bytes in the (very small) keyboard buffer, but only one in your (huge, resizeable) buffer
- Special keys and key sets are much easier and more reliable to handle (think Alt-SysRq on some Linux distros - it gets processed even if the entire userland has crashed and burnt)
- You can store them in per-terminal buffers, so that keys are always accepted by the right terminal

Re: Keyboard waiting for input

Posted: Sat Feb 06, 2010 12:43 pm
by matio
Could I use a buffer?

Re: Keyboard waiting for input

Posted: Sat Feb 06, 2010 12:46 pm
by Creature
matio wrote:Could I use a buffer?
I think the easiest way to store input would be to use a static buffer (possibly a Ring or circular buffer) so you can set a maximum amount of allowed characters. Using a vector or dynamic memory allocation doesn't seem like a good idea as you'd have to resize everytime a character gets pushed.