%
%  Matlab driver for the basic 1-dof state variable model
%
%  set up the matrices for constructing the states
%  this is for the ECP Simulink program
%
  get_positions = [1 0 0 0 0; 
                   0 1 0 0 0; 
                   0 0 1 0 0];
  get_angles = [0 0 0 1 0];
  get_error_bit = [0 0 0 0 1];
  get_all_states = [1 0 0 0 0 0 0 0; 
                    0 0 0 1 0 0 0 0; 
                    0 1 0 0 0 0 0 0; 
                    0 0 0 0 1 0 0 0; 
                    0 0 1 0 0 0 0 0; 
                    0 0 0 0 0 1 0 0; 
                    0 0 0 0 0 0 1 0; 
                    0 0 0 0 0 0 0 1];
 %
 % this is the only part you should ever have to change
 %
 get_desired_states = [1 0 0 0 0 0 0 0; 
                       0 1 0 0 0 0 0 0;
                       0 0 0 0 0 0 1 0;
                       0 0 0 0 0 0 0 1];
% 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  set the saturation levels
%
  saturation_level = 1000/2196;   % model 210
%  saturation_level = 1000/2546;   % model 205
%
%  set the input amplitude (in cm or radians)
%
  Amp = 0;
%  Amp = 15*pi/180;
%
%  set the final time
%
  Tf = 2.0;
%
%  load the A, B, C, and D matrices
%
%  load state_model_1dof_210
% load state_model_1dof_205
  load regular_model;
%  load inverted_model
  C = [0 0 1 0];
%
%  Now find the state feedback vector
%
%  [n,m] = size(A);
  K = lqr(A,B,diag([0.1 0.1 0.1 0.1]),1000)
  
  p = [-2 -3 -4 -5];
  K = place(A,B,p);
  disp('Feedback gains are:' ); K
  disp('Closed loop poles at :'); eig(A-B*K)
%
%  set the initial conditions
%
  ic_x1 = 0;
  ic_x1_dot = 0;
  ic_theta = 0.05;
  ic_theta_dot = 0;
%
%  determine the prefilter gain
%
%  Gpf = -1/(C*inv(A-B*K)*B)
  Gpf = 1;
%
%  run the simulation
%
  sim('Basic_2dof_State_Variable_Model');
%
%  Now plot the data
%
  ubound = saturation_level*ones(1,length(m_time));
  orient landscape
  subplot(3,2,1); plot(m_time,m_x1); grid; title('Cart Position (cm)');
  subplot(3,2,3); plot(m_time,m_x1_dot); grid; title('Cart Velocity (cm/sec)'); 
  subplot(3,2,2); plot(m_time,m_theta); grid; title('Pendulum Position (rad)');
  subplot(3,2,4); plot(m_time,m_theta_dot); grid; title('Pendulum Velocity (rad/sec)');
  subplot(3,2,5); plot(m_time,m_y,'-',m_time,m_r,':'); grid; legend('Output','Input',4); title('Input/Output');
  subplot(3,2,6); plot(m_time,m_u,'-',m_time,ubound,':',m_time,-ubound,':'); grid; title('Control Effort');
  axis([0 0.2 -saturation_level saturation_level]);
  %disp([' k_1 = ' num2str(K(1)) ', k_2 = ' num2str(K(2)) ', G_{pf} = ' num2str(Gpf) ', Closed Loop poles at ' num2str(eig(A-B*K)')]);