#include <16F84.h>
#fuses HS, NOWDT,NOPROTECT,PUT
#use Delay(Clock=8000000)
#use RS232(Baud=19200, Xmit=PIN_B1, Rcv=PIN_B0)

#define SCLK PIN_A0
#define CSN  PIN_A1
#define DOUT PIN_A2
#define DIN  PIN_A3

#define chan1 0b10001111
#define chan2 0b11001111
#define chan3 0b10011111
#define chan4 0b11011111
#define chan5 0b10101111
#define chan6 0b11101111
#define chan7 0b10111111
#define chan8 0b11111111

byte sclkDL = 1;
byte cnvDL = 2;

int idata[16];
int gdata[22];

void transmit2(int byte_number)
{
	putc(gdata[byte_number]);
}

void reada2d()
{
	int i;
	int shiftout;
	int shiftin;
	byte odata[1];
	int channel = 1;

	for(i = 0 ; i <6 ; i++) {
	    transmit2(i);
	}

	for(channel = 0 ; channel <= 7 ; channel++){
		if(channel == 0)
		*odata = chan1;
		if(channel == 1)
		*odata = chan2;
		if(channel == 2)
		*odata = chan3;
		if(channel == 3)
		*odata = chan4;
		if(channel == 4)
		*odata = chan5;
		if(channel == 5)
		*odata = chan6;
		if(channel == 6)
		*odata = chan7;
		if(channel == 7)
		*odata = chan8;

		OUTPUT_LOW(CSN);
		DELAY_US(sclkDL);
		for(shiftout = 1 ; shiftout <= 8 ; shiftout++){
			OUTPUT_LOW(SCLK);
			output_bit(DOUT, shift_left(odata,1,0));
			DELAY_US(sclkDL);

			OUTPUT_HIGH(SCLK);
			DELAY_US(sclkDL);
			DELAY_US(sclkDL);
			}

		OUTPUT_LOW(SCLK);
		OUTPUT_LOW(DOUT);

		transmit2(channel*2+6);

		for(shiftin = 1 ; shiftin <= 8 ; shiftin++){
			OUTPUT_HIGH(SCLK);
			shift_left(idata,16,input(DIN));
			DELAY_US(sclkDL);

			OUTPUT_LOW(SCLK);
			DELAY_US(sclkDL);
			DELAY_US(sclkDL);
			}

		for(shiftin = 1 ; shiftin <= 8 ; shiftin++){
			OUTPUT_HIGH(SCLK);
			shift_left(idata,16,input(DIN));
			DELAY_US(sclkDL);

			OUTPUT_LOW(SCLK);
			DELAY_US(sclkDL);
			DELAY_US(sclkDL);
			}
 
		OUTPUT_HIGH(CSN);
		transmit2(channel*2+7);
	}
}

void reorder()
{
	int i;
	int complement;

	gdata[0] = 0x69;
	gdata[1] = 0x69;
	gdata[2] = 0x69;
	gdata[3] = 0x69;
	gdata[4] = 0xFF;
	gdata[5] = 0xFF;
	
	for(i=0 ; i<=15 ; i+=2){
		complement=(((idata[i] * 2)  & 0xF0) ^ 0xFF) & 0xF0;
		gdata[6+i] = idata[i+1] * 2 + ((idata[i] / 128) & 0x01) ;
		gdata[7+i] = ((idata[i] / 8) & 0x0F) + complement;
	}

}


main()
{
    set_tris_a(0x08); 
    while(1) {
	reada2d();
	reorder();
	delay_ms(1);
    }
}



