Model a Counter for HDL and High-Level Synthesis Code Generation

To write MATLAB® code that models hardware and is suitable for HDL and High-Level Synthesis (HLS) code generation, use this design pattern.

This design pattern demonstrates best practices for writing MATLAB code for HDL and HLS code generation:

• Initialize persistent variables to a specific value. In this example, an `if` statement and the `isempty ` function initialize the persistent variable. If you do not initialize the persistent variable, then you cannot generate HDL and HLS code.

• Inside a function, read persistent variables before they are modified so that the persistent variables are inferred as registers.

This Simulink® model illustrates the MATLAB counter modeled in this example.

To learn how to model the counter in Simulink, see Create HDL-Compatible Simulink Model.

MATLAB Code for the Counter

The function `mlhdlc_counter` is a behavioral model of a 4-bit synchronous up counter. The input signal, `enable_ctr`, triggers the value of the count register, `count_val`, to increase by one. The counter continues to increase by one each time the input is nonzero, until the count reaches a limit of 15. After the counter reaches this limit, the counter returns to zero. A persistent variable, which is initialized to zero, represents the current value of the count. Two `if` statements determine the value of the count based on the input.

To define the `mldhlc_counter` and `mldhlc_counter_tb`, use these codes:

MATLAB CodeMATLAB Testbench
```%#codegen function count = mlhdlc_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; % limit to four bits if count_val>15 count_val=0; end end count=count_val; end ```
```for i = 1:100 if mod(i,5) == 0 % do not increment the counter if mod(i,5) is zero. val = mlhdlc_counter(false); else val = mlhdlc_counter(true); end end ```