%% Timing Valve Analysis *With Slotted Connecting Rod*
% _Ryan Sweeney_

clear all; close all; clc
%% Position Analysis as a Function of Crank Angle
% The aim of this code is to analyze the sizes of the linkages that we need 
% to most closely approximate a square wave on a graph of the timing cylinder's 
% piston pin position as a function of crank angle.

a = .5; % crank length [in]
bshort = 3; % connecting rod length [in] at the beginning of the slot
blong = bshort+(.52); % connecting rod length [in] at the end of the slot
c = 0; % vertical offset [in] from crank origin to piston
n = 2; % number of cycles to plot

BDC = blong - a;
TDC = a + bshort;

% stroke  = TDC - BDC
% .48 = 2*a - slot_length (see blong)
Stroke = TDC - BDC % this is for checking purposes and important to be .48 [in]
StrokePP = .787402; % stroke of Power Piston [in] it's actually 20mm
BorePP = 1.5748; % bore of the Power Cylinder [in]
theta = zeros(1,360*n); % accounts for 90 degrees of analysis
theta2 = zeros(1,360*n); % accounts for 90 more degrees of analysis
dX = zeros(1,360*n); % position of the piston pin in the x direction
squareWave = zeros(1,360*n); % allocating space for a square wave
middle(1:1 + 360*n) = (TDC+BDC)/2; %visualizes the middle of the piston for easy 
% visual analysis
%% 
% To calculate the piston height as a function of theta relative to the 
% BDC position, we'll use the following equations:
% 
% $$\theta_2 = \sin^{-1}\left(\frac{c - a\cdot\sin(\Theta)}{b}\right)$$
% 
% $$dX = a\cdot\cos(\Theta) + b\cdot\cos(\Theta_2)$$
% 
% With the slotted connecting rod design, the crank only moves the piston 
% throughout certain domains of theta. The following is how the piston pin travels
% 
% * *[0 90)*         the piston remains at *TDC* 
% * *[90 180)*     the piston is acted on by the *long end* of the connecting 
% rod
% * *[180 270)*   the piston remains at *BDC*
% * *[270 360)*   the piston is acted on by the *short end* of the connecting 
% rod

for j = 1:n
    for i = 1 + (360*(j-1)):91 + (360*(j-1))
        theta(i) = (i-1)*pi/180;
        dX(i) = TDC;
    end
    for i = 91 + (360*(j-1)):181 + (360*(j-1))
        theta(i) = (i-1)*pi/180;
        theta2(i) = asin((c-a*sin(theta(i)))/blong);
        dX(i) = a*cos(theta(i)) + blong*cos(theta2(i));
    end
    for i = 181 + (360*(j-1)):271 + (360*(j-1))
        theta(i) = (i-1)*pi/180;
        dX(i) = BDC;
    end
    for i = 271 + (360*(j-1)):361 + (360*(j-1))
        theta(i) = (i-1)*pi/180;
        theta2(i) = asin((c-a*sin(theta(i)))/bshort);
        dX(i) = a*cos(theta(i)) + bshort*cos(theta2(i));
    end
    
    for i = 1:1 + 360*j
        if dX(i) < BDC
            dX(i) = BDC; % This corrects geometry where pin doesn't catch until 
            % slightly after 180 degrees
        else
            dX(i) = dX(i);
        end
    end
        
end
%% 
% Next, we'll analyze this data and compare it to having a square wave with 
% "lightswitch timing" where the position of the piston goes immediately to the 
% other side of the cylinder

for j = 1:n
    for i = 1 + (360*(j-1)):180 + (360*(j-1))
        squareWave(i) = BDC;
    end
    for i = 181 + (360*(j-1)):361 + (360*(j-1))
        squareWave(i) = TDC;
    end
end

SqWaveShift = -90; % square wave offset in degrees 

figure
hold on; axis([0 360*n BDC-.2 TDC+.2]); grid on; 
set(gca,'XTick',0:60*n:360*n)
plot(theta*180/pi, dX, theta*180/pi-SqWaveShift, squareWave, theta*180/pi, ... 
    middle, '--')
xlabel('Crank Angle [deg]'); ylabel('Position [in]')
title('Position of Piston Pin [in] vs. Crank Angle')
hold off;
%% Determining the Ports' Functions Depending on Crank Angle
% When looking at the timing cylinder's container, there are a few important 
% measurements that must be identified. The following are measurements from the 
% pin in the BDC position.
% 
%      
% 
%      

airOutLeft = zeros(1,360*n) ; airOutRight = zeros(1,360*n);
exhaustLeft = zeros(1,360*n); exhaustRight = zeros(1,360*n);

for j = 1:n
    for i = 1 + (360*(j-1)):361 + (360*(j-1))
            % finding when HP air goes to left side
        if dX(i)+3.01 < BDC+3.24
            airOutLeft(i) = 1;
        else 
            airOutLeft(i) = 0;
        end
            % finding when HP air goes to right side
        if dX(i)+3.74 > BDC+3.99
            airOutRight(i) = -1;
        else
            airOutRight(i) = 0;
        end
            % finding exhaust going out the left side
        if dX(i)+2.75 > BDC+2.99
            exhaustLeft(i) = .5;
        else
            exhaustLeft(i) = 0;
        end
            % finding exhaust going out the right side
        if dX(i)+4.00 < BDC+4.24
            exhaustRight(i) = -.5;
        else 
            exhaustRight(i) = 0;
        end
    end
end

figure
hold on; axis([0 360*n -1.1 1.1]); 
set(gca,'XTick',0:60*n:360*n)
set(gca,'YTick',0:1.1)
plot(theta*180/pi,airOutLeft, theta*180/pi,airOutRight, theta*180/pi,exhaustLeft,...
    theta*180/pi,exhaustRight, 'LineWidth',2)
legend('HP Air to Left Side', 'HP Air to Right Side', 'Left Side Exhausting', ...
    'Right Side Exhausting', 'Location', 'southwest')
xlabel('Crank Angle [deg]'); ylabel('What is Acting')
title('Whats Happening at Each Crank Angle')
%% Determining the Phase Angle
% Here, we'll compare the differences between the crank angles when the different 
% ports open and close.

phase = [1:1+360*n; airOutRight; airOutLeft];
disp(phase(:,115:123)) % The switch between HP air going from ... 
    % the right to the left side
disp(phase(:,302:310)) % The switch between HP air going from ...
    % the left to the right side
%% 
% The right side's air cuts off at exactly 117 degrees while the left side 
% begins to recieve air at 121 degrees.
% 
% On the travel back the air to the left side cuts off at (304-180) = 124 
% degrees and then goes back to flowing to the right side at (308-180) = 128 degrees. 
% This difference is to be expected with this design due to the geometry behind 
% the lengths of the linkages. This length difference can be seen in the jump 
% on the Position vs Crank Angle graph as the small hiccup below BDC. 
% 
%  Knowing this, we've decided to make the admission angle be ~5 degrees. 
% Typically this value is between 5 and 10, however that's with continuous sinusoidal 
% motion. With the fast travel between top and bottom dead center, being able 
% to have a smaller admission angle becomes possible. We will, however, have an 
% adjustable crank to connect to the power cylinder. It will be centered at 125 
% degrees and have 4 positions, each offset 2 degrees to allow for an eight degree 
% adjustment in either direction. *This will allow our range to be from 117 - 
% 133 degrees.*
% 
% *Our final phase angle was experimentally found to work best at 131 degrees 
% therefore the admission angle is 11 degrees*
% 
% Next, to finish it, I'm going to plot the position of the timing piston 
% against the position of the power piston for a comparison to get to a PVT diagram

phase = 131; %[deg]
admission = 11; %[deg]
thetaPP = circshift(theta,phase);

for i = 1:1 + 360*j
    PPx(i) = 0 + StrokePP/2*sin(thetaPP(i));
end

figure
hold on; grid on; 
plot(theta*180/pi,airOutLeft, theta*180/pi,airOutRight, theta*180/pi, ... 
    exhaustLeft, theta*180/pi,exhaustRight, theta*180/pi, PPx)
xlabel('Crank Angle [deg]'); ylabel('Position [in]')
title('Valve Functions vs. Power Piston Position')
hold off;
VatBDC = 0;
VatBDCadmit = pi*(BorePP/2)^2*(.5*StrokePP-.5*StrokePP*cos((admission*pi/180)));
VatTDC = pi*(BorePP/2)^2*StrokePP;
VatTDCadmit = VatTDC - VatBDCadmit;

% Convert from in^3 to cm^3
VatBDC = VatBDC * 16.3871;
VatBDCadmit = VatBDCadmit * 16.3871;
VatTDC = VatTDC * 16.3871;
VatTDCadmit = VatTDCadmit * 16.3871;

Volume = [VatBDCadmit, VatBDC, VatBDC, VatBDCadmit, VatTDCadmit, VatTDC, ...
    VatTDC, VatTDCadmit, VatBDCadmit];
Pressure = [14, 25, 83, 94, 94, 83, 25, 14, 14];

figure
hold on; axis([-1 26 10 100]); grid on; 
plot(Volume, Pressure, '--o')
xlabel('Volume [cm^3]'); ylabel('Pressure [psia]')
title('PVT Diagram')
figure
hold on; grid on; 
plot(Volume, Pressure,'--o')
xlabel('Volume [cm^3]'); ylabel('Pressure [psia]')
title('PVT Diagram Zoomed In')
xlim([24 25.6])
ylim([78 96.0])
