% get9830.m 
%
% An example of how to get data from an instrument connected to a serial port.
% This was written specifically for an Interface 9830 Digital Indicator
% (connected to a load cell). Therefore some variables - espectially in the
% s = serial(....) line - may need to be adjusted for different systems.
% 
% pause(0.25) sets the frequency of data logging, units of seconds so 0.25
% is 4 Hz.
%
% finalized on 16 june 2008
% written by terry
% corresponding person: hsu.leslie at gmail.com
%
% open serial port on COM1
s=serial('COM1','BaudRate',9600,'DataBits',8,'Parity','none','StopBits',1,'Terminator','CR');

fopen(s);

s.Status

disp('get9830.m');
disp('ctrl-C to end');
input('press enter to begin');
i = 1;

while(i)
    % send transmit on
    %fprintf(s,'data');
    fwrite(s,17,'uint8');  %send an XON
    fwrite(s,13,'uint8');  %send a  CR


    % get first 8 bytes
    %data = fread(s, s.BytesAvailable, 'uint8');
    if(s.BytesAvailable >= 8)
        data = fread(s, 8, 'uint8');
    
        %convert data into decimal
        reading = bitshift(data(3),24) + bitshift(data(4),16) + bitshift(data(5),8) + data(6);  %combine data bytes
        

        %handle negatives
        if(data(3)>127)
            reading = bitcmp(reading,32); % complement the bits
            reading = -1*(reading+1);
        end;

        %place decimal point
        reading = reading*10^-(5-data(7));
        
        %save in array
        output(i) = reading;
        pause(0.25); % I think the indicator makes 4 measurements per second
        i=i+1;
        
        % press ctrl-c to end
        
    end;
end;

fclose(s);
delete(s);
clear s;