Main Content

Why Does the dsp.AsyncBuffer Object Error When You Call read Before write?

In the dsp.AsyncBuffer System object™, you must initialize the buffer before the first call to the read method. To initialize the buffer, call either the write or setup method.

Consider the bufferWrapper function, which writes and reads data from an asynchronous buffer. When the input cmd is set to true, the object writes data to the buffer. When cmd is false, the object reads data from the buffer.

function [y,isData] = bufferWrapper(u,cmd) 

persistent asyncBuff 
if isempty(asyncBuff) 
   asyncBuff  = dsp.AsyncBuffer; 
end 

if cmd % write 
   write(asyncBuff,u); 
   y = zeros(128,1); 
   isData = false; 
else % read 
    isData = true; 
    y = read(asyncBuff,128,64); 
end 

Call the buffer with cmd set to false.

bufferWrapper(1,false);

The function errors with the following message:

Buffer not initialized. You must call write before read.

When you generate code from this function, the object throws an error that the buffer 'Cache' is undefined.

codegen bufferWrapper -args {1,false}
??? Property 'Cache' is undefined on some execution paths but is used inside the called function.

Both these error messages indicate that the buffer is not initialized at the first call to the read method in one of the execution paths.

To resolve these errors, call write or setup before the first call to read. If you are calling setup, call it only once at the beginning, during the buffer construction.

In this function, setup is called before read.

function [y,isData] = bufferWrapper_setup(u,cmd) 

persistent asyncBuff 
if isempty(asyncBuff) 
   asyncBuff = dsp.AsyncBuffer; 
   setup(asyncBuff,u);
end 

if cmd % write 
   write(asyncBuff,u); 
   y = zeros(128,1); 
   isData = false; 
else % read 
    isData = true; 
    y = read(asyncBuff,128,64); 
end 

You can now read the buffer without any errors.

bufferWrapper_setup(1,false);

Generating code from this function now successfully generates the MEX file, because the cache is defined on all execution paths.

codegen bufferWrapper_setup -args {1,false}

See Also

Objects

Related Examples

More About