% General purpose Function for any command

% Inputs: two strings 'a' and 'b', indicating the IS command and the 
% port number respectively.
% For example: a = '@ndl 500','@gtv 10', etc.. 
% and b = 'COM2', 'COMM3', etc..;

function [out] = cavro(a,b)

p = serial(b); % creating a serial port object for input port 'b'

set(p,'BaudRate',9600)
set(p,'Terminator','CR')
set(p, 'Timeout', 180);


fopen (p)
fprintf(p,a)

out = uint8(fread(p,6,'char'));
%disp(['A ' num2str(double(out)')])
%[out(1), out(2), out(3), out(4), out(5), out(6)]

set(p, 'Timeout', 1);
warning off MATLAB:serial:fread:unsuccessfulRead
end_byte = uint8(fread(p,1,'char'));
%disp(['B' num2str(double(end_byte)')])
warning on MATLAB:serial:fread:unsuccessfulRead
set(p, 'Timeout', 180);

while (out(3) ~= 96)
    fprintf(p,'/1QR');
    out = double(fread(p,6,'char'));
%    disp(['C ' num2str(double(out)')])
    set(p, 'Timeout', 1);
    warning off MATLAB:serial:fread:unsuccessfulRead
    end_byte = uint8(fread(p,1,'char'));
%    disp(['D' num2str(double(end_byte)')])
    warning on MATLAB:serial:fread:unsuccessfulRead
    set(p, 'Timeout', 180);
    pause(1);
end

disp(['                                                  |->Cavro command completed with ** ' num2str(out(1)) '-' num2str(out(2)) '-' num2str(out(3)) '-' num2str(out(4)) '-' num2str(out(5)) '-' num2str(out(6)) ' ** returned.']);

fclose(p)
delete(p)
clear p