/*
test485.c:

This program tests the 485 driver of the PK25xx. In order to test
the RS485 driver, the program samples\aasc\echo485.c must be compiled
and run on another controller (controller A). The 485 terminals of
controller A should then be connected to the 485 terminals of the
PK25xx (485+ to 485+, 485- to 485-). Be sure to configure both controllers
for 485 communication at channel 1.

After controller A is running echo485.c, compile and run this program on
the PK25xx. This program prints sequential numbers on the screen to verify
the operation of the 485 driver (both receive and transmit).

*/

#define N_WATCHDOG 0				//	no need for virtual watchdog
#define _VD_NOHITWD				//	no need to hit watchdog in the backgound

#use eziopk25.lib					//	specific definitions for the PK25xx
#use vdriver.lib					//	vdriver for timing
#use aascz1.lib					//	AASC driver for channel 1

main() {
	char rBuf[0x400];
	char wBuf[0x400];
	auto char transmit[16],receive[16];
	auto unsigned count;
	auto struct _Channel *chan;
	auto char *pCur;
	auto unsigned remaining;
	auto unsigned long timeMark;
	
	VdInit();

	chan = aascOpen(DEV_Z1,							//	open Z1 for 9600bps comm.
		0,
		ASCI_PARAM_8N1+ASCI_PARAM_1200*8,
		NULL);

	aascSetReadBuf(chan,rBuf,sizeof(rBuf));	//	set read buffer
	aascSetWriteBuf(chan,wBuf,sizeof(wBuf));	//	set write buffer
	aascTxSwitch(chan,1);							//	enable the channel
	aascRxSwitch(chan,1);
	off_485();											//	disable 485 transmit driver
	
	while (1) {
		hitwd();

		while (aascWriteBufFree(chan) < 5) {	//	wait for 5 empty slots
			hitwd();
		}
		aascFlushRdBuf(chan);						//	flush receive buf for echo
		sprintf(transmit,"%04x",count++);		//	this is the string to transmit
		on_485();										//	turn on 485 transmit driver
		aascWriteBlk(chan,transmit,5,1);			//	start transmit the string now
		while (aascReadBufLeft(chan) < 5) {		//	wait for entire string is echoed
			hitwd();
		}
		off_485();										//	then turn off the transmit driver
		aascFlushRdBuf(chan);						//	clear receive buffer
		while (aascReadBufLeft(chan) < 5) {		//	wait for echoer to echo
			hitwd();
		}
		aascReadBlk(chan,receive,5,1);			//	echo bytes are here, read them
		printf("received %s\n",receive);			//	print what is received
		if (strcmp(transmit,receive)) {			//	if not the same as transmitted
			printf("problem!\n");					//	we have a problem!
		}
		timeMark = MS_TIMER;							//	allow turn around time
		while (MS_TIMER - timeMark < 200) {		//	wait for 200ms
			hitwd();
		}
	}
}