function gainControl(G_TX_target, G_PA_dB, Nd, mu) % Constants N=length(G_TX_target); % number of points Ts = 1.0 % sample period in sec. atten_res_dB = 0.010; % attenuator resolution %mu = 0.1; % Averaging of measurement knoise = 0.04; % measurement noise f_theta = 0.001; % Hz Temperature drift frequency a_theta = 5; % dB Temperature drift level dB atten_dB=40; % initial value: Controller atten_ output state = zeros(1, Nd-1); % filter state for delay error = 0; enabled = 1; LATENCY = 3; latency_count = LATENCY; for i=1:N, G_TX = G_PA_dB(i) - atten_dB + knoise*randn(); [G_TX_est, state] = filter([zeros(1,Nd-1) 1], 1, G_TX, state); error_last = error; error = G_TX_est - G_TX_target(i); derror = abs(error) - abs(error_last); atten_dB = atten_dB + mu*error; atten_dB = getAtten(atten_dB, atten_res_dB); if enabled == 0 G_TX = -120; end error_v(i) = error; derror_v(i) = derror; gain_dB_v(i) = G_TX; atten_v(i) = atten_dB; if enabled == 1 if derror > -0.1 && abs(error) > 3 if latency_count == 0 enabled = 0; else latency_count = latency_count - 1; end else latency_count = LATENCY; end end end subplot(4,1,1) plot((0:N-1)*Ts, G_TX_target, (0:N-1)*Ts, G_PA_dB); grid; legend('G_{TX_target}', 'G_{PA}'); xlabel('t/s'); ylabel('dB') subplot(4,1,2) plot((0:N-1)*Ts, error_v, (0:N-1)*Ts, derror_v); grid; legend('error', 'derror'); xlabel('t/s'); ylabel('dB') subplot(4,1,3) plot((0:N-1)*Ts, gain_dB_v); grid; title('Gain_{TX}'); xlabel('t/s'); ylabel('dB') subplot(4,1,4) plot((0:N-1)*Ts, atten_v); grid; title('atten'); xlabel('t/s'); ylabel('dB') function atten = getAtten(gain_dB, res_dB) atten = max(0, min(40, res_dB*fix(gain_dB/res_dB)));