Can't get variable out of Callback function. Already defined as global.

12 views (last 30 days)
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 svae this global variable in a local variable in my Mainscript.
processedData = data;
Problem is processedData is always empty. So when i want to make a 2D Matrice to save different data liek 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.
  10 Comments
Kaan Inal
Kaan Inal on 29 May 2022
Ok sorry maybe im too dumb to get it but it doesn't work. The callback works i get alle the data i need inside cbuff. But i can't check cbuffw inside my main skript and so cbuff doesn't contain the data. I feel really dumb.
In the main script.
cbuffw always 1.
cbuff always 1xpayloadBytes filled with zeros.
In the workspace
cbuff stores all values read.
cbuffw increases.
After stopping the mainscript i can see all the serialdata in cbuff.
Mainscript:
if cbuffr == cbuffw
disp("no new data");
elseif cbuffw > cbuffr
disp("w>r");
cbuffr = cbuffr+1;
data(frameCount,:) = cbuff(cbuffr,:) ;
frameCount= frameCount +1
if cbuffr == 16
cbuffr = 1;
end
end

Sign in to comment.

Answers (1)

Image Analyst
Image Analyst on 29 May 2022
Try assigning it like this
if isempty(data)
fprintf('Skipping frameCount = %d because data vector is empty!\n', frameCount);
elseif processedData <= 1 || isempty(processedData)
% The first time through just assign it so that processedData has the same number of columns as data
processedData = reshape(data, 1, []); % Make sure it's a row vector.
else
% Append on data into a new row for the second and subsequent times through.
processedData(frameCount,:) = data;
end
  9 Comments
Kaan Inal
Kaan Inal on 31 May 2022
I got the solution. I had to use drawnow(). With using drawnow() variable and its value was useable in the mainscript.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by