Main Content

Generate Code for User-Defined System Objects

How To Create A User-Defined System object

To create a user-defined System object™ and generate code:

  1. Create a class that subclasses from matlab.System.

  2. Define one of the following sets of methods:

    • setupImpl and stepImpl

    • setupImpl, outputImpl, and updateImpl

  3. Optionally, if your System object has private state properties, define the resetImpl method to initialize them to zero.

  4. Write a top-level design function that creates an instance of your System object and calls the object, or calls the output and update methods.

    Note

    The resetImpl method runs automatically during System object initialization. For HDL code generation, you cannot call the public reset method.

  5. Write a test bench function that exercises the top-level design function.

  6. Generate HDL code.

User-Defined System object Example

This example shows how to generate HDL code for a user-defined System object that implements the setupImpl and stepImpl methods.

  1. In a writable folder, create a System object, CounterSysObj, which subclasses from matlab.System. Save the code as CounterSysObj.m.

    classdef CounterSysObj < matlab.System
    
        properties (Nontunable)
            Threshold = int32(1)
        end
        properties (Access=private)
            State
            Count
        end
        methods
            function obj = CounterSysObj(varargin)
                setProperties(obj,nargin,varargin{:});
            end
        end
        
        methods (Access=protected)
            function setupImpl(obj, ~)
                % Initialize states
                obj.Count = int32(0);
                obj.State = int32(0);
            end
            function y = stepImpl(obj, u)
                if obj.Threshold > u(1)
                    obj.Count(:) = obj.Count + int32(1); % Increment count
                end
                y = obj.State;          % Delay output
                obj.State = obj.Count;  % Put new value in state
            end
        end
    end
    
    The stepImpl method implements the System object functionality. The setupImpl method defines the initial values for the persistent variables in the System object.

  2. Write a function that uses this System object and save it as myDesign.m. This function is your DUT.

    function y = myDesign(u)
    
    persistent obj
    if isempty(obj)
        obj = CounterSysObj('Threshold',5);
    end
    
    y = obj(u);
    
    end

  3. Write a test bench that calls the DUT function and save it as myDesign_tb.m.

    clear myDesign
    for ii=1:10
        y = myDesign(int32(ii));
    end
    

  4. Generate HDL code for the DUT function as you would for any other MATLAB® code, but skip fixed-point conversion.

Related Topics