% rtdx_echotext : writes new char and receives through rtdx

% Gets newest character from figure
newChar = get(Fig,'CurrentCharacter');

v=newChar;

% Opens rtdx write channel
status = invoke(h,'Open','ichan','W');

% Write ascii value of newest character to channel
status = invoke(h,'Write',int16(v));

% Close rtdx channel
status = invoke(h,'Close');

% Wait some time. Needed so that DSP has time to write back. 
% Without wait, there will be nothing for MATLAB to read in
for i=1:7000000
    i = i;
end

% Open rtdx read channel
status = invoke(h,'Open','ochan','R');

% Find how many messages available in read buffer
% RTDX seems to keep read values in the buffer, so 
% need to read just the latest one
[status,nummsgs] = invoke(h,'GetNumMsgs');

% Fast forward to latest message
status = invoke(h,'Seek',nummsgs);

% Read from read channel
[status, values] = invoke(h,'ReadI2');

% Close channel
status = invoke(h,'Close');


% Following is for formatting purposes. 
% MATLAB does not like spaces. So if a space was sent, MATLAB won't append
% it to the end of the string. The most important part is the 
% set(edit2,'String',newRString) command which sets the string of the 
% edit2 text box.
recvChar = char(values);
oldRString = get(edit2,'string');
if values == 32
    if spaceMode == 1
        spaces = spaces+1;
    else
        spaceMode = 1;
        spaces = 1;
    end
elseif values == 8
    stringL = length(oldRString);
    oldRString(stringL) = '' ;
    set(edit2,'String',oldRString);
else
    if spaceMode == 1
        newRString = [oldRString blanks(spaces) recvChar];
        
        set(edit2,'String',newRString);
        spaceMode = 0;
        spaces = 0;
    else
        newRString = [oldRString recvChar];
        set(edit2,'String',newRString);
    end
end


