Wednesday, February 3, 2010

serial port I/O and pause

i employed the help of yesdogs' friend to write this .m file to collect data from an instrument connected to my laptop's serial port:
http://seismo.berkeley.edu/~lhsu/help/get9830.m

instead of prostituting oneself for matlab code (figuratively, not literally), one could start here:

Serial Port I/O introduction
http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_external/f105659.html

okay i'll paste the .m below. there's a lot to talk about. i don't understand it all. i think i had a version 2 of this that collected data for a set time, but i can't find it.

i think my favorite part is pause(0.25)
pause halts execution temporarily. as written above, it halts things for 0.25 sec. so data is collected at 4 Hz.

note: i have not yet used this data, but i wrote an abstract for a conference in 2011 that requires it.


% 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
%
% 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;

No comments:

Post a Comment