classdef slexPWMSysObj < matlab.System
    %  System object that generates PWM (Pulse-width modulation) signals 
    %  based on the input period and duty cycle signals, by using a 
    %  controllable sample time and setNumTicksUntilNextHit.

%   Copyright 2017-2020 The MathWorks, Inc.
    
    % Public, tunable properties
    properties(Nontunable)
        Amplitude = 2;
        Resolution = 0.0001;
    end
    
    properties(Access = private)
        IsHit;
        RemainingSamples;
    end
    
    methods(Access = protected)
        function sts = getSampleTimeImpl(obj)
            sts = createSampleTime(obj, 'Type', 'Controllable', 'TickTime', obj.Resolution);
        end
        
        function yout = stepImpl(obj,duty, period)
            if (obj.IsHit)   
                numSamples = floor(period/obj.Resolution);
                numTicksToNextHit = floor(duty*numSamples); 
                
                if (numTicksToNextHit == 0)
                    numTicksToNextHit = (numSamples);
                    yout = 0;
                elseif (numTicksToNextHit == numSamples)
                    yout = obj.Amplitude;
                else
                    obj.IsHit = false;
                    obj.RemainingSamples = (numSamples - numTicksToNextHit);
                    yout = obj.Amplitude;
                end
                
            else
                obj.IsHit = true;
                numTicksToNextHit = (obj.RemainingSamples);
                yout = 0;
            end
            
            setNumTicksUntilNextHit(obj, numTicksToNextHit);
            
        end
        
        function setupImpl(obj)
            obj.IsHit = true;
            obj.RemainingSamples = 0;
            setNumTicksUntilNextHit(obj, 1);
        end
        
        function varargout = getOutputDataTypeImpl(~)
            % Return data type for each output port
            varargout{1} = 'double';
            
        end
        
        function varargout = getOutputSizeImpl(~)
        % Return size for each output port
            varargout{1} = [1 1];
            
        end
        
        function varargout = isOutputComplexImpl(~)
            % Return true for each output port with complex data
            varargout{1} = false;
            
        end
        
        function varargout = isOutputFixedSizeImpl(~)
            % Return true for each output port with fixed size
            varargout{1} = true;
        end
    end
end
