function base_speed = mcb_getBaseSpeed(pmsm,inverter)
% mcb_getBaseSpeed   Compute base speed for PMSM
% 
%   mcb_getBaseSpeed calculates the base speed for PMSM at rated voltage and
%   rated load. This is helpful in control algorithm development for the motor. 
% 
%   base_speed = mcb_getBaseSpeed(pmsm,inverter) returns the base speed for 
%   the given combination of PMSM and Inverter. The function accepts following inputs:
%   a pmsm object and an inverter object. 
%
%   See HELP for additional information for this utility.

% Function      :   mcb_getBaseSpeed
% Description   :   Compute PI Parameters for FOC of PMSM
% File name     :   mcb_getBaseSpeed.m
% Inputs        :   pmsm object & inverter object
% Authors       :   Darshan Pandit

% Copyright 2020 The MathWorks, Inc.

%% Get base speed

% pmsm        = obj1;
% inverter    = obj2;

% Update parameters
Rs          = pmsm.Rs + inverter.R_board;
Imax        = pmsm.I_rated;
Ld          = pmsm.Ld;
Lq          = pmsm.Lq;
Flux_PM     = pmsm.FluxPM;
Vph_max     = inverter.V_dc/sqrt(3);    %Vph peak for Space Vector PWM
% Vph_max     = inverter.V_dc/2;        %Uncomment if using Sine PWM
ConvRPM     = 60/(2*pi*pmsm.p);
      
% Compute MTPA 
if Ld < Lq 
    Id = (Flux_PM/(4*(Lq-Ld)))-sqrt((Flux_PM^2/(16*(Lq-Ld)^2))+(0.5*Imax^2));
else
    Id = 0;
end
        
Iq = sqrt(Imax^2 - Id^2);

% Get base speed
Vo_max = Vph_max - Rs*Imax;     
Vdo = -Lq*Iq;
Vqo = Ld*Id + Flux_PM;

omega_base = Vo_max/sqrt((Vdo)^2 + (Vqo)^2);
base_speed = double(uint32(ConvRPM*omega_base));

end