function SerialTest
% SerialTest
% 
% Exercise PsychSerial.mex.

% 9/18/98  dhb  Wrote it.
% 2/20/00  dgp  Enhanced to test both ports.
% 2/21/00  dgp  Report params.
% 2/22/00  dgp  Baud rates.
% 2/26/00  dgp  Use PsychSerial Ports to get actual port names.
% 4/24/02  awi  Exit on PC with message.
% 4/28/02	 awi	Changed name from "SerialTest.m" to "PsychSerialTest.m" Use "PsychSerial" now.    	

if strcmp('PCWIN',computer)
    error('Win: PsychSerialTest not yet supported.');
end


for p=PsychSerial('Ports')
	query=sprintf('Test the "%s" port %s %s? (Y or N)',p.name,p.inputDriverName,p.outputDriverName);
	reply=lower(input(query,'s'));
	if reply(1)=='y'
		fprintf('Open the serial port.\n');
		port=PsychSerial('Open',p.inputDriverName,p.outputDriverName,9600);
		params=PsychSerial('Params',port);
		fprintf('Params: %g baud, %g data bits, %g stop bits, parity-%s\n',params.baudRate,params.dataBits,params.stopBits,params.parity);
	
		% With nothing connected to my Mac, attempts to write hang up forever
		% unless I turn off CTS flow control.
		params.outCTSEnable=0;
		params=PsychSerial('Params',port,params);
		fprintf('Write "Hello world."\n');
		PsychSerial('Write',port,'Hello world.');
		
		fprintf('Read some characters, with default 20 ms timeout: ');
		readStr=PsychSerial('Read',port);
		fprintf('"%s"\n',readStr);
		
		fprintf('Read with 1 sec timeout: ');
		readStr=PsychSerial('Read',port,1);
		fprintf('"%s"\n',readStr);
		
		fprintf('Set and clear DTR line, using ''DTR''.\n');
		PsychSerial('DTR',port,1);
		PsychSerial('DTR',port,0);
		
		fprintf('Set and clear DTR line, using ''Params''.\n');
		clear params
		params.DTR=1;
		PsychSerial('Params',port,params);
		params.DTR=0;
		PsychSerial('Params',port,params);
		
		if 0
			% This always fails on the Macs I've tested. 
			% The error message indicates that the call isn't supported.
			fprintf('Set and clear RTS line, using ''Params''.\n');
			clear params
			params.RTS=1;
			PsychSerial('Params',port,params);
			params.RTS=0;
			PsychSerial('Params',port,params);
		end
		
		fprintf('Set baud rate, using ''Params'': ');
		clear params
		for baudRate=[300 1200 9600 57600 115000 230000]
			params.baudRate=baudRate;
			PsychSerial('Params',port,params);
			params=PsychSerial('Params',port);
			fprintf('%d ',params.baudRate);
		end
		fprintf('\n');
		
		fprintf('Close the port.\n');
		PsychSerial('Close',port);
		fprintf('\n');
	end
end
fprintf('Done!\n');
