/* In order to correctly write to the Pokey chip you must put
   your address on the address bus first.  Then your data on
   the data bus.  Then strobe the pokey chip.  Below you will
   see some routines that do this for you */

#define PORTADD 0x378
#define PPORTDATA    (PORTADD + 0)
#define PPORTSTATUS  (PORTADD + 1)
#define PPORTCONTROL (PORTADD + 2)

#define ACTIVE 0
#define INACTIVE 1
#define STROBE 2

/* The below function is the main function you would call when
   wanting to write to the Pokey Chip.  The add parameter is the
   address (0-f) of the pokey chip to write to.  byte is the
   value you want written to that register.  0-255 */

void WritePokey(int add,char byte) {
  PLatchAddress(add);
  PLatchData(byte);
  PChipSelect(STROBE);
}


/* This function controls the chip select to the Pokey Chip.
   It basically when going through the STROBE case, takes
   the chip select signal (pin 1 on the printer, inverse
   logic) low and then high.  This clocks the data on U2
   to the adress selected by U3. */

void PChipSelect(int mode) {
  if(mode == INACTIVE) outportb(PPORTCONTROL,0);
  if(mode == ACTIVE) outportb(PPORTCONTROL,1);
  if(mode == STROBE) {
    outportb(PPORTCONTROL,1);
    outportb(PPORTCONTROL,0);
  }
}

/* This function writes the specified address (0-f) to U3
   and puts a low on pin 17 on the printer port (inverse
   logic).  This places the address on U3 until a new
   address is latched out */

void PLatchAddress(int add) {
  outportb(PPORTCONTROL,0);
  outportb(PPORTDATA,add);
  outportb(PPORTCONTROL,8);
  outportb(PPORTCONTROL,0);
}

/* This function writes the specified value (0-ff) to U2
   and puts a low on pin 14 on the printer port (inverse
   logic).  This places the value on U2 until a new
   address is latched out */

void PLatchData(int val) {
  outportb(PPORTCONTROL,0);
  outportb(PPORTDATA,val);
  outportb(PPORTCONTROL,2);
  outportb(PPORTCONTROL,0);
}

