%serial_line_echo.m
%Echo input lines received via COM1 port
%Incoming lines must be terminated with <CR><LF> characters
%
%    Connect COM1 of MATLAB computer to COM1 of another
%    computer using a NULL MODEM CABLE.  Then startup HYPERTERMINAL
%    on the remote computer via:
%      Start|All Programs|Accesories|Communications|HyperTerminal
%
%    Connect using: COM1
%    Port Setup:
%         Baud rate = 4800
%         Parity = EVEN
%         Number of stop bits = 2
%         Number of data bits = 7
%         Flow Control = NONE
%
%    File|Properties|Settings Tab|ASCII Setup... button
%       Check the following boxes:
%           Send line ends with line feeds
%           Echo typed characters locally
%           Append line feeds to incoming lines

clear all;

%640x480 windowed display mode
config_display(0);
%setup COM1 for access to Minolta Chroma meter
port=1;     %use COM1: port
baud=4800;
parity=2;   %0=no parity, 2=even parity
nstop=2;    %2 stop bits (0=1 stop bit)
ndata=7;    %7 data bits
config_serial(port,baud,parity,nstop,ndata);
start_cogent;

disp(' ');
disp('Start Serial Demo');
disp('Waiting for <LF> terminated line input on COM1');
disp('Automatically times-out in 60 seconds');
disp(' ');
wait(1000);

%send salutation to remote connection<CR><LF>]
%start with fresh biffer
clearserialbytes(port);
%construct text mesage with CR/LF termination
msg=['Start Serial Demo.',char(13),char(10)];
%convert text to numeric array
nmsg=abs(msg);
%send message via COM1:
sendserialbytes(port, nmsg);

%fetch <LF> terminated line of data
line_buffer = []; bytes = []; matches = [];
found = 0;
loop = 1;
ftime=time+60000;  %set 60 sec timeout
while( loop > 0 )
    %drain low-level serial input data buffer
    readserialbytes(port);
    %fetch buffered characters (if any)
    [bytes,times,n]=getserialbytes(port);
    %update line array if any data found
    if( n > 0 )
        %concatenate new chars to old
        line_buffer = [line_buffer; bytes];
        %search for <LF> terminator
        matches = find(bytes == 10);
        if(~isempty(matches))
            found = 1;
            loop = 0;  %exit if <LF> received
        end
    end
    %test for time-out condition
    if( time > ftime )
        loop = 0;  %exit if timed-out
    end
end

disp(['length of line_buffer = ',num2str(length(line_buffer))]);
if( length(line_buffer) > 0 )
    %convert numeric column-vector to string
    myString = char(line_buffer');
    %display line
    disp(['Line: ',myString]);
end
disp(' ');

%exit Cogent 2000 mode
stop_cogent;

