Saving data of command window from callback function
8 次查看(过去 30 天)
显示 更早的评论
Hi guys,
I am using a callback function which reads a characteristic of a bluetooth module to achieve high sampling frequency. But since I am now using callback function I am not able to store the data as I wish. I can display it and see it in the command window but I want it as variables in the workspace. How can I achieve that?
Right know I just see my values in the command window and am not able to store it in workspace.
%% Setup connection
bt = ble("RN4871-BT_C719");
c = characteristic(bt,"59C88760-5364-11E7-B114-B2F933D5FE66","0F300FD5-78CD-4449-8865-A84136B8A286");
%% read values
tic;
c.DataAvailableFcn = @displayCharacteristicData;
%%
unsubscribe(c);
%% callback function
function displayCharacteristicData(src,~)
data = read(src,'oldest');
disp(data);
toc;
end
When I tried this I got the error message that there it could not find the variable "i"
%% Setup connection
bt = ble("RN4871-BT_C719");
c = characteristic(bt,"59C88760-5364-11E7-B114-B2F933D5FE66","0F300FD5-78CD-4449-8865-A84136B8A286");
%%
s = 1000;
i = 1;
t = zeros(1,s);
v1 = zeros(1,s);
v2 = zeros(1,s);
tic;
c.DataAvailableFcn = @displayCharacteristicData;
%%
unsubscribe(c);
%%
function displayCharacteristicData(src,~)
data = read(src,'oldest');
v1(i)=data(1);
v2(i)=data(2);
t(i)=toc;
i=i+1;
end
1 个评论
Mathieu NOE
2021-1-22
hello
is there any reason why data cannot be output of your function ?
function data = displayCharacteristicData(src,~)
回答(1 个)
Jan
2021-1-22
function data = displayCharacteristicData(src,~, Flush)
persistent Store
if isempty(Store)
Store = struct('v1', [], 'v2', [], 't', []);
end
if nargin == 3
data = Store;
Store = [];
end
data = read(src,'oldest');
i = numel(Store.v1) + 1;
Store.v1(i) = data(1);
Store.v2(i) = data(2);
Store.t(i) = toc;
end
Now the data are collected persistently inside the callback and flushed, of you call the callback with 3 inputs.
Note that this let the Struct grow iteratively, which consumes a lot of ressources. A smarter method would be to increase the size in steps and crop them finally:
function data = displayCharacteristicData(src,~, Flush)
persistent Store
if isempty(Store)
Store = struct('v1', zeros(1, 1000), 'v2', zeros(1, 1000), 't', zeros(1, 1000), 'count', 0);
end
if nargin == 3
data = Store;
Store = [];
end
data = read(src,'oldest');
count = Store.count + 1;
if count > numel(Store.v1)
Store.v1(count + 1000) = 0;
Store.v2(count + 1000) = 0;
Store.vt(count + 1000) = 0;
end
Store.v1(count) = data(1);
Store.v2(count) = data(2);
Store.t(count) = toc;
Store.count = count;
end
I'd use clock instead of tic/toc.
6 个评论
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!