% ADPCM Script function is for CONTEC AD12-8(PM)
%             Gerox(c) 1997,1998,1999 All Rights Reserved
% AD/DA PCMCIA card for MATLAB Version 5.3 
% by using inp/outp MEX function
% if cannot work, please check assigned io address for PCcard
% AD/DA PCMCIA card I/O default default I/O setting is 0x240
% only works under WIN95/98
% Usage: adpcm(interval,data_num,channel,'ioadr')
%   Example:  data = ADPCM(0.01,1000,2,'0x240')
%          :  data = ADPCM(0.01,100,2)
%  data matrix format
%        channel
%  ad0(0) ad1 ad2 ... adn     d
%  ad0(1) ad1 ad2 ... adn     a
%  ad0(2) ad1 ad2 ... adn     t
%  ad0(3) ad1 ad2 ... adn     a
%  ad0(4) ad1 ad2 ... adn     n
%  ad0(5) ad1 ad2 ... adn     u
%  ad0(6) ad1 ad2 ... adn     m
%  
%   interval range :0.1049 - 1.0000e-005 Sec
%   channel max data_num  min interval
%     1      16384          0.000001
%     2       8192          0.000002
%     3       5461          0.000003
%     4       4096          0.000004
%     5       3276          0.000005
%     6       2730          0.000006
%     7       2340          0.000007
%     8       2048          0.000008
function data = adpcm(interval,data_num,channel,ioadrstr)
%interval = 0.001;
%data_num=1024;
%channel=1
%ioadr=hex2dec('240');
if nargin == 4
  if ischar(ioadrstr)
    ioadr = hex2dec(ioadrstr(3:end));
  else 
    ioadr = ioadrstr;% BE CAREFUL!! THIS SHOULD DECIMAL number!!
  end
else
  ioadr = hex2dec('240');
end
if(interval > 1048576.0/1e7)
		interval = 1048576.0/1e7;
end
if(interval < 100.0/1e7)
		fprintf('Max sampling = %f [Sec]\n',100./1e7);
		interval = 100.0/1e7;
end
data = zeros(data_num,channel);
ModeData = 1;
if(channel == 1) ModeData = 0;end
ClockData = interval *1e7 - 1;
tmpClock = rem(floor(ClockData./[1 256 256*256]),256);
CountData = data_num;
tmpCount=rem(floor(CountData./[1 256]),256);
outp(ioadr+6, 0 );% initialize
outp(ioadr+6, 1 );%set sampling mode
outp(ioadr+7, ModeData );
outp(ioadr+6, 2 );% set sampling clock 
outp(ioadr+7, tmpClock(1));
outp(ioadr+7, tmpClock(2));
outp(ioadr+7, tmpClock(3));
outp(ioadr+6, 3 );% set sampling count 
outp(ioadr+7, tmpCount(1));
outp(ioadr+7, tmpCount(2));
if(channel == 1) outp(ioadr+2,0);
else outp(ioadr+2, channel-1);% sampling start 
end
for j = 1:data_num;
	while (~(bitand(inp(ioadr+2),2)));end
	for i = 1:channel
		AiDatal = inp(ioadr );% input data
		AiDatah = inp(ioadr+1);% input data
		data(j,i)= sum([AiDatah AiDatal].*[256 1]) * 20. / 4096. - 10.;
	end
	if(~bitand(inp(ioadr+2),3)) break;end
end
