Implement RAM Using MATLAB Code - MATLAB & Simulink (original) (raw)
Main Content
You can write MATLAB® code that maps to RAM during HDL code generation by using:
- Persistent arrays or private properties in a user-defined System object™.
hdl.RAM
System objects.hdl.Delay
System objects.dsp.Delay
System objects.
The following examples model the same line delay in MATLAB. The line delay uses memory in a ring structure. Data is written to one location and read from another location in such a way that the data written is read after a delay of a specific number of cycles. The RAM read address is generated by a counter. The write address is generated by adding a constant value to the read address.
Implement RAM Using a Persistent Array or System object Properties
This example shows a line delay that implements the RAM behavior using a persistent array with the function mlhdlc_hdlram_persistent
. Changing a specific value in the persistent array is equivalent to writing to the RAM. Accessing a specific value in the array is equivalent to reading from the RAM.
You can implement RAM by using user-defined System object private properties in the same way.
%#codegen function data_out = mlhdlc_hdlram_persistent(data_in)
persistent hRam; if isempty(hRam) hRam = zeros(128,1); end
% read address counter persistent rdAddrCtr; if isempty(rdAddrCtr) rdAddrCtr = 1; end
% ring counter length ringCtrLength = 10; ramWriteAddr = rdAddrCtr + ringCtrLength;
ramWriteData = data_in; %ramWriteEnable = true;
ramReadAddr = rdAddrCtr;
% To write and read the memory, manipulate the values in the array
hRam(ramWriteAddr)=ramWriteData; ramRdDout=hRam(ramReadAddr);
rdAddrCtr = rdAddrCtr + 1;
data_out = ramRdDout;
Implement RAM Using hdl.RAM
This example shows a line delay that implements the RAM behavior using hdl.RAM
with the function, mlhdlc_hdlram_sysobj
. In this function, the step
method of the hdl.RAM
System object reads and writes to specific locations in hRam
. Code generation from hdl.RAM
has the same restrictions as code generation from other System objects. For details, see Limitations of HDL Code Generation for System Objects.
%#codegen function data_out = mlhdlc_hdlram_sysobj(data_in) persistent hRam; if isempty(hRam) hRam = hdl.RAM('RAMType', 'Dual port'); end
% read address counter persistent rdAddrCtr; if isempty(rdAddrCtr) rdAddrCtr = 0; end
% ring counter length ringCtrLength = 10; ramWriteAddr = rdAddrCtr + ringCtrLength;
ramWriteData = data_in; ramWriteEnable = true;
ramReadAddr = rdAddrCtr;
% To write and read the memory, call the RAM object [~,ramRdDout] = hRam(ramWriteData,ramWriteAddr, ... ramWriteEnable,ramReadAddr);
rdAddrCtr = rdAddrCtr + 1;
data_out = ramRdDout;