Main Content

Generate Hardware Instances For Local Functions

The following example shows how to use local functions in MATLAB®, so that each execution of a local function corresponds to a separate hardware module in the generated HDL code.

MATLAB Local Functions

This example demonstrates best practices for writing local functions in MATLAB code that is suitable for HDL code generation.

  • If your MATLAB code executes a local function multiple times, the generated HDL code does not necessarily instantiate multiple hardware modules. Rather than instantiating multiple hardware modules, multiple calls to a function typically update the state variable.

  • If you want the generated HDL code to contain multiple hardware modules corresponding to each execution of a local function, specify two different local functions with the same code but different function names. If you want to avoid code duplication, consider using System objects to implement the behavior in the function, and instantiate the System object™ multiple times.

  • If you want to specify a separate HDL file for each local function in the MATLAB code, in the Workflow Advisor, on the Advanced tab in the HDL Code Generation section, select Generate instantiable code for functions .

MATLAB Code for mlhdlc_two_counters.m

This function creates two counters and adds the output of these counters. To create two counters, there are two local functions with identical code, counter and counter2. The main method calls each of these local functions once. If the function were to call the counter function twice, separate hardware modules for the counters would not be generated in the HDL code.

%#codegen
function total_count = mlhdlc_two_counters(a,b)

%This function contains two different local functions with identical
%counters and calls each counter once.

total_count1=counter(a);

total_count2=counter2(b);

total_count=total_count1+total_count2;

function count = counter(enable_ctr)
%four bit synchronous up counter

%persistent variable for the state 
persistent count_val;
if isempty(count_val)
    count_val = 0;
end

%counting up
if enable_ctr
    count_val=count_val+1;
end

%limit from four bits
if count_val>15
    count_val=0;
end

count=count_val;



function count = counter2(enable_ctr)
%four bit synchronous up counter

%persistent variable for the state 
persistent count_val;
if isempty(count_val)
    count_val = 0;
end

%counting up
if enable_ctr
    count_val=count_val+1;
end

%limit from four bits
if count_val>15
    count_val=0;
end

count=count_val;

See Also

|

Related Topics