%
%   Matlab driver for the for open loop model of a simple wheel
%
% 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
close all
clear all
%
%  Model Parameters
%
  MAX_DELTA_U = 100000;
  MAX_DUTY = 2*7300;
  AD_scale = 1.00;
  scale = MAX_DUTY/1023.0;
%
%  read the parameters from the file
%       
   data = load('Step_Response_50');
   t = data(:,1);
   u = data(:,2);
   u_max = data(:,3)*AD_scale/scale;
   ut = [t u];
   y = data(:,4);
   Ts = t(3)-t(2);
   Tf = t(end);
%
%  Compute the limiting parameters
%   
  Relay_On = 0;   % minimum positive control effort to make the motor start spinning in rad/sec
  Relay_Off = 0;  % motor stops at control efforts below this in rad/sec
  Max_Speed = 1000.0;  % maximum motor speed in rad/sec
  Control_Effort_Saturation = MAX_DUTY*AD_scale/scale; % maximum allowable control effort
  
  Rising_Slew = MAX_DELTA_U*AD_scale/(Ts*scale);  % maximum positive slope for control effort
  Falling_Slew = -MAX_DELTA_U*AD_scale/(Ts*scale);  % maximum negative slope for control effort
 
%
%  enter the discrete-time model parameters
%
  B = 0.015;
  b = 0.985;
%
%  enter the transfer function
% 
  D = tf(1,[1 0 0],Ts);  % enter the delay here as a transfer function
  %D = tf(1,1, Ts);
  Gp = tf(B*[1],[1 -b], Ts)*D
  [num_Gp, den_Gp] = tfdata(Gp,'v');
%
%  now simulate the system
%
  sim('DT_Openloop');
%
%  plot the results
%
  figure
  orient landscape
  subplot(2,1,1); 
  [mts, yts] = stairs(m_time,m_y); 
  [ts, ys] = stairs(t, y);
  plot(ts,ys,'r',mts,yts,'b','Linewidth',1.5); legend('Measured','Model'); grid; xlabel('Time (sec)'); ylabel('Speed (rad/sec)');
  subplot(2,1,2); 
  [mts, mtu] = stairs(m_time,m_u); 
  [ts, us] = stairs(t, u_max);
  plot(ts,us,'r',mts,mtu,'b','Linewidth',1.5); legend('Measured','Model'); grid; xlabel('Time (sec)'); ylabel('Control Effort (rad/sec)');
  axis([0 Tf 0 Control_Effort_Saturation]);
