dheera.net
Language:

PS/2 driver for PIC's

This is a driver (tested with Hi-Tech PICC on PIC16F630) to use a standard PS/2 keyboard with a PIC.
// PS/2 Keyboard driver for PIC's. tested on PIC16F630 with a Dell
// QuietKey.
// By Dheera Venkatraman (dheera at dheera dot net).
// 1. Change PIN_CLK and PIN_DATA as needed.
// 2. Execute kinit() at the _beginning_ of your code.
// 3. Use kgetb() to get the next byte received (char),
//        kgetn() to get the next digit typed on the keypad (int),
//      or
//        kgets() to get the scancode of the next key that is
//        released (char).
//          (does not support extended scancodes)
// This driver does not support buffering and has indefinite waits,
// but should be easily modifiable.

#ifndef PIN_CLK
#define PIN_CLK PIN_C3
#endif

#ifndef PIN_DATA
#define PIN_DATA PIN_C4
#endif

void kinit() {
  input(PIN_CLK);
  input(PIN_DATA);
}

char kgetb() {
  int lastclk=0,clk;
  int b,count,bit;
  while(input(PIN_CLK)==0) restart_wdt();
  while(input(PIN_DATA)==1) restart_wdt();
  while(input(PIN_CLK)==1) restart_wdt();

  b=0;count=0;
  while(count<10) {
    clk=input(PIN_CLK);
    if(clk==0 && lastclk==1) {
      bit=input(PIN_DATA);
      count++;
      if(count>0&&count<9) { b=(b>>1)|(bit<<7);}
    }
    lastclk=clk;
  }
  delay_us(200);
  return b;
}

char kgets() {
  char c=0;
  while(c!=0xF0) { c=kgetb(); }
  c=kgetb();
  return c;
}

char kgetn() {
  char c=0;
  while(c!=0xF0) { c=kgetb(); }
  c=kgetb();
  if(c==0x70) return 0;
  if(c==0x69) return 1;
  if(c==0x72) return 2;
  if(c==0x7A) return 3;
  if(c==0x6B) return 4;
  if(c==0x73) return 5;
  if(c==0x74) return 6;
  if(c==0x6C) return 7;
  if(c==0x75) return 8;
  if(c==0x7D) return 9;
  return 255;
}