function interference
% Interactive simulation of a diffraction grating spectrum.
% A diffraction grating with N grooves is illuminated by monochromatic light. 
% When viewed at an angle, the reflections from each groove are slightly 
% phase shifted by small path length differences.  When these reflections
% are all added up, a diffraction pattern emerges that shows intensity maxima
% whenever the path length difference is an integral number of wavelengths 
% (called the "order"), thereby resulting in constructive interference. If
% the number of grooves is large anough, these maxima are very sharp and
% the intensity is nearly zero everywhere else.
% Sliders on the graph allow you to adjust the path length difference 
% between adjacent grooves (pld) and the number of grooves (N).
% Calls Interference1 and Interference2 as functions when sliders are
% adjusted.
% Tom O'Haver, toh@umd.edu, November 2011

global N pld  

N = 3;  % Number of grooves in the grating
pld = .1;  % Path Length Difference between reflections from adjacent grooves
maxpld=14; % Maximum value of pld  (you can change this if desired)
maxN=100;  % Maximum value of N   (you can change this if desired)

plotwaves(N,pld)
whitebg('k')

% Attaches KeyPress test function to the figure.
set(gcf,'KeyPressFcn',@ReadKey)
uicontrol('Style','text')
% end of outer function
% ----------------------------SUBFUNCTIONS--------------------------------
function ReadKey(obj,eventdata)
global N pld  
key=get(gcf,'CurrentCharacter');
if isscalar(key),
  switch double(key),
    case 28
        % pld down when right cursor arrow pressed.
          pld=pld-pld/20;
          plotwaves(N,pld);
    case 29
        % pld up when left cursor arrow pressed.    
        pld=pld+pld/20;
        plotwaves(N,pld);
    case {97,30}
        % When up cursor arrow pressed is pressed, INcreases number of 
        % grooves in the grating (N)
        if N==0,N=1;end
        if N>20,
            N=round(N+N./20);
        else
            N=N+1;
        end
        plotwaves(N,pld);
    case {122,31}
        % When down cursor arrow pressed is pressed, DEcreases number of
        % grooves in the grating (N)
        if N==0,N=1;end
        if N>20,
            N=round(N-N./20);
        else
            N=N-1;
        end
        plotangles(alphar,d);
    case 107
        % When 'K' key is pressed, prints out keyboard commands
        disp('Keyboard commands:')
        disp('Path Length Difference..............left and right cursor arrows')
        disp('Number of grooves in the grating....up and down cursor arrows')
    otherwise  
       UnassignedKey=double(key)
       disp('Press k to print out list of keyboard commands')
   end % switch
end % if

function plotwaves(N,pld)
x=[0:.1:pi];  % x-axis for plot
z=zeros(size(x));
a=0;
clear S
  for j=1:N, 
     y=sin(3.*x+a); % waveform of one reflection from grating groove.
     z=z+y;   % z is waveform resulting from superimposition of j reflections
     S(j,:)=y;
     a=a+pld;
  end
  plot(x,S,'k',x,z./N,'r') 
  intensity=sum(z.*z)./N^2;  % calculates mean amplitude
  title('Black lines: Electric vectors of the separate waves from each groove')
  xlabel('Red line: electric vector of light waveform reaching the detector')
    text(0,1.1,['    Grating has ' num2str(N) ' grooves.   Path length difference = ' num2str(pld./(2*pi)) ' wavelengths'])
  text(0,-1.1,['               Total intensity of sum of all waves:' num2str(intensity) ])
  axis([0 3 -1.2 1.2]);
