%
% Example code for using an I-CubeX digitizer (USB-microDig or Wi-microDig) with Matlab
%
% The digitizer's sensor input 1 is sampled at 10 bit resolution in 10 ms intervals for 10 seconds 
% and the data is saved to file icubex.dat with timestamp  
%

fid = fopen('icubex.dat', 'w'); % open/create datafile for writing data from digitizer, change 'w' into 'a+' for appending

% uncomment the following two lines if the serial port is already opened
% newobjs = instrfind; % find all serial ports
% fclose(newobjs); % close all serial ports

% comment/uncomment lines below according to your operating system and digitizer type 
s = serial('COM10'); % Windows: create a serial port object for the applicable digitizer (USB-microDig or Wi-microDig), port number will vary
% s = serial('/dev/tty.SLAB_USBtoUART'); % MacOS: create a serial port object for the applicable USB-microDig, port name may vary
% s = serial('/dev/tty.I-CubeXWi-microDig0444-'); % MacOS: create a serial port object for the applicable Wi-microDig, port name will vary
fopen(s); % open the serial port for writing and reading

% setup the digitizer
fwrite(s,[240 125 0 90 0 247]); % send host mode message to digitizer
fwrite(s,[240 125 0 34 247]); % send reset message to digitizer
fwrite(s,[240 125 0 3 0 100 247]); % send interval message to digitizer to set sampling interval to 100 ms 
fwrite(s,[240 125 0 2 64 247]); % send resolution message to digitizer to set sampling resolution to 10-bit 
pause(3); % wait until the digitizer has sent host mode and reset confirmation messages
b = get(s, 'BytesAvailable'); % find out how many bytes are in the buffer
fread(s,b); % empty buffer

tstart = clock; % set start time as current time
t = clock; % current time
e = 0; % elapsed time
fwrite(s,[240 125 0 1 64 247]); % send stream message to digitizer to turn on continuous sampling for input 1
while get(s, 'BytesAvailable') < 6 % wait for digitizer to send confirmation message (6 bytes)
end
fread(s,6); % empty buffer of confirmation message bytes
while e < 10 % data acquisition loop for 10 seconds
  while get(s, 'BytesAvailable') < 7  % wait for digitizer to send hi-res data message (7 bytes) 
  end
  d = fread(s,7); % read data from buffer
  v = d(5)*8 + d(6); % calculate the sensor value from MSB and LSB
  dlmwrite('icubex.dat',[t v],'-append'); % write time stamp and sensor value to datafile
  t = clock; 
  e = etime(t, tstart); % calculate elapsed time
end

fclose(s); % close serial port
fclose(fid); % close datafile