/*
	MGPIOM1.C

	BL14xx/MicroG or BL15xx/MicroG2

	Read parallel data.
	
	PIOA is set to input mode 1. When inport(PIODA) is executed, ARDY1 goes
	high and a peripheral device is alerted that PIOA is ready to read data.
	When data is ready on the lines, a positive strobe from the peripheral
	device to ASTB1 will generate an interrupt for PIOA at which point the
	interrupt service routine can read in the valid data on PIOA.

	PIOB bit 7 is used to monitor ARDY1.
	PIOB bit 6 is used to strobe ASTB1.

	Jumper PB7 (H3-13) to ARDY1 (H3-11).
   Jumper PB6 (H3-14) to ASTB1 (H3-12).

   Use function readdata(char *buf, int count) to read count number of bytes
   to data array pointed to by buf.
*/

shared int datarcvcnt;
char datain;
char *piobuf;
int datacount;
char test[100];
void strobe();
void readdata(char *buf, int count);

main()
{
	resPIOCB(0x40);									// PIOB bit 6 is output
	setPIOCB(0x80);									// PIOB bit 7 is input
	resPIODB(0x04);									// PIOB bit 6 is low
	
	readdata(test, 20);								// start reading 20 bytes of data

   while (1)
   {
   	hitwd();
      runwatch();
      if( (inport(PIODB) & 0x80))				// mimic handshaking of peripheral here
      {
         strobe();
		  	if(datacount)
		  		printf("%d , datain >> %x \n",datarcvcnt, datain);
      }
   }
}

// Strobe the ASTB1 line to generate interrupt on PIOA.

void strobe()
{
   setPIODB(0x40);			// PIOB bit 6 high
   resPIODB(0x40);			// PIOB bit 6 low
}

// Prepare the PIODA interrupt service routine to read in count number
// of bytes from the PIOA port into buf.

void readdata(char *buf, int count)
{
   outport(PIOCA, 0x4f);         				// PIOA in mode1
   outport(PIOCA, PIOA_VEC);     				// set vector to PIOA
   outport(PIOCA,0x87);          				// interrupts on, d7 = 1, (0) off
	piobuf = buf;
   datacount = count;
	datarcvcnt = 0;
   outport(ITC, inport(ITC) | 0x01);         // enable INT0
	inport(PIODA);										// dummy first read to set ARDY1
}

#INT_VEC PIOA_VEC myint
interrupt reti myint()
{
   if(datacount--)			// check if more data to read
   {
   	datain = inport(PIODA);
      *(piobuf++) = datain;
		datarcvcnt++;
	}								// if no more disable the PIOA interrupt
	else
	{
		outport(PIOCA, 0x4f);					// mode1
		outport(PIOCA, 0x07);					// interrupt off
		outport(ITC, inport(ITC) & 0xfe);	// disable INT0
	}
}