ADCP Currents MATLAB Implementation

function [u, v, cspd, cdir] = cadcp2currents ( cu_counts, cv_counts, magnetic_variation  )
% CADCP2CURRENTS:  calculate current parameters from Campbell buffer
%
% When the current observations are transferred from the Workhorse to the Campbell, they
% are reported as two-byte, two's compliment integers [-32768, 32767], least significant
% byte first.  We reverse this process.  Also, the observations are made in units of mm/s,
% which we convert to cm/s.
%
% USAGE:  [u, v, cspd, cdir] = cadcp2currents ( cu_counts, cv_counts, mag_var );
%
% PARAMETERS:
% Input:
%    cu_counts, cv_counts:
%        velocity sensor values as reported by Campbell
%    magnetic_variation:
%        correction factor for directions
% Output:
%    u, v:
%        East and north velocity components in cm/s
%    cspd, cdir:
%        speed and direction in cm/s, angular degrees
%
% Reference:
% Workhorse Accoustic Doppler Current Profiler Technical Manual, Appendix D, Table D-4



[r,c] = size(cu_counts);

%
% Two's compliment processing on current data.
x = dec2hex(cu_counts);
y = [x(:,3:4) x(:,1:2)];
z = hex2dec(y);

%
% find the negative velocities.
ind = find(z>32767);
z(ind) = (65536 - z(ind))*-1;
z = z/10;

%
% restore to original matrix size.
unew = reshape(z, r, c);


%
% Two's compliment processing on current data.
x = dec2hex(cv_counts);
y = [x(:,3:4) x(:,1:2)];
z = hex2dec(y);

%
% find the negative velocities.
ind = find(z>32767);
z(ind) = (65536 - z(ind))*-1;
z = z/10;

%
% restore to original matrix size.
vnew = reshape(z, r, c);

% now rotate to true north (add in magnetic variation).
% no longer need to do in the process_filtered_doppler.m
[u,v]=rot2d(unew,vnew,magnetic_variation);


cspd = sqrt ( u.^2 + v.^2 );
cdir = 90 - atan2(v,u)*180/pi;


return;