Home > OS >  Can't get variable out of Callback function. Already defined as global. Matlab
Can't get variable out of Callback function. Already defined as global. Matlab

Time:06-01

I have a serialport bytesavailable callback function.

function readFrame(src,~)
global data
global payloadBytes
message = read(src,payloadBytes,"uint8");
src.UserData = message;
data = message;
return

I read the buffer into the variable message and then save it as global variable data. i get the variable in my workspace. Then something happens that I can't explain. I try to save this global variable in a local variable in my Mainscript. Notice: global data is defined in mainscript.

global data;
global payloadBytes;
msg=[];
frameCount = 1;
numFrames = 10;
messageByte = zeros(numFrames,payloadBytes)

while(app)
        
       %wait till callback triggered and serial data read 
       while isempty(msg)
           %save global variable data in local variable msg
           msg = data;
           disp("wait for data")
       end
      
       %save msg in an expanding 2D Variable messagebyte 
       messageByte(frameCount,:) = msg;
        %empty msg variable 
        msg =[]
        frameCount = frameCount  1
  
        %stop when 10 frames are caught
        if frameCount == 11

        app = 0;
        end
    
end

Problem is processedData is always empty. So when i want to make a 2D Matrice to save different data like this:

processedData(frameCount,:) = data;

I get an exception: indices doesn't match. Thats no wonder.

Can somebody tell me what I am doing wrong. Thank you.

CodePudding user response:

MATLAB is single-threaded. Stuff doesn’t run in parallel unless you explicitly use the Parallel Processing Toolbox. So for your callback to write to data, your main loop must give the callback a chance to execute. Add a pause to your loop, this will allow callbacks to execute, as well as timer objects.

       while isempty(msg)
           pause(0.1) % find a suitable pause length here
           %save global variable data in local variable msg
           msg = data;
           disp("wait for data")
       end

The pause doesn’t need to be long, but make it as long as you can tolerate, since that will make your wait less processor intensive.

  • Related