%  This script runs an example for EE462G of an analysis of a CMOS
%  invertor circuit.  The output voltage, drain current, and instantaneous power are
%  computed as a function of the input voltage (sweeping from 0 to VDD = 5 volts)
%  The functions nmos.m and pmos.m are needed to run this script
%
%   Written by Kevin D. Donohue (donohue@engr.uky.edu) October 2003
clear
%  Set Parameters
vton = 2.1;   %  Threshold voltage for NMOS
vtop = -2.1;  %  Threshold voltage for PMOS
K=1.1; W=1; L=1; KP=2*K;  VDD=5;  
vin = [0:.1:VDD];  % input voltages to sample at 
vdsn = [0:.01:VDD];  %  Create Vds value over of the NMOS transistor
vdsp = vdsn - VDD; %  Create vds values over the PMOS transistor (note vsdn-vdsp=VDD)

%  Loop to compute operating points
for vinx = 1:length(vin)
    
    idsp = pmos(vdsp,vin(vinx)-VDD,KP,W,L,vtop);  %  Generate Load Curve (gate voltage is vin-VDD)
	idsn = nmos(vdsn,vin(vinx),KP,W,L,vton);  % Compute characteristic curve

%  get effective intersection point
	[err, inderr] = min(abs(idsp - idsn));  %  Find closest point
    vout(vinx) = vdsn(inderr(1));  %  Store output voltage
    id(vinx) = idsp(inderr(1));       %  Store drain current
    
%   Comment out the next 6 lines (include the pause statement) to stop the while loop from being interupted
    plot(vdsn,idsp,'k:',vdsn,idsn,'r', [vout(vinx), vout(vinx)],[0 5], 'g--' )  %  Check plot along the way
    text(2.5, 2.5, ['VGSn = ' num2str(vin(vinx)) ' volts'])
    xlabel('Vdsn or Vdsp+VDD')
    ylabel('Idsn or -Idsp')
    disp(['Hit any key to continue'])
    pause
end

figure(1)
%  Plot transfer characteristic curve
plot(vin,vout)
xlabel('Voltage Input - Volts')
ylabel('Voltage Output - Volts')
title('Transfer Characteristics for CMOS Invertor')

figure(2)
%  Plot Drain current as a function of input voltage
plot(vin,id)
xlabel('Voltage Input - Volts')
ylabel('Drain current - Amps')
title('Drain Current CMOS Invertor')

figure(3)
%  Plot instantaneous power as a function of input voltage
plot(vin,id.*vout)
xlabel('Voltage Input - Volts')
ylabel('Watts')
title('Power consumed by NMOS Transistor in CMOS Invertor')
