USB callback "terminator" fails to trigger a read when messages are close together
Show older comments
My App Designer program uses USB communication to an Arduino
It usually works but every once in a while Matlab fails to read.
configureCallback(app.PicoCom,"terminator",@app.PicoInput);
...
function PicoInput(app,src,~)
% check if there is more than 1 line. For some reason I don't get another callback!!!
while (app.PicoCom.NumBytesAvailable>0)
raw = readline(src);
I've already added the while loop which mostly fixed it except if the messages are 20msec apart.
The only time it fails (and not very often) is between 2 messages that are known to be 20 ms apart.
When it fails (App Designer says "Run" ... no action), I can go into the debugger (with a special pause I put in to read app properties) and check with
K>> app.PicoCom
ans =
Serialport with properties:
Port: "COM6"
BaudRate: 57600
NumBytesAvailable: 11
K>> read(app.PicoCom,11,"char")
ans =
'z73851718
'
And there it sits, not being read.
Sure, there are probably work arounds (I'm open to suggestions to manage it now) but isn't this a bug!
My next attempt to handle this is to add a pause(0.03); at the end of the while loop but this is very unsatisfying and how do I know it will NEVER fail?
Accepted Answer
More Answers (1)
Matlab Pro
on 15 Sep 2024
Hi @Gavin
Here I am sednig to pieces of code:
1): simple example where you just wait for NumBytesAvailable to get some posistive value, read the data and thats all..
2): reading expected # of bytes:
Are you handling some kind of protocol with the Arduino?
I believe that the answer is 'yes', so the protocol should have some bytes pointing to the expected data length.
In the example below: the expected dataLength given in bytes #3 and #4
After caculateding the expeced dataLength - the code cotiues reading (with a minimal delay) till goal is achieved
% 1) Reading while NumBytesAvailable = 0
switch class(portObj)
case 'internal.Serialport'
write(portObj,data_write,"uint8");
while (portObj.NumBytesAvailable == 0)
pause(0.01);
end
out = read(portObj,portObj.NumBytesAvailable,"uint8");
end
% 2) Reading expected # of bytes (BY PROTOCOL)
switch class(portObj)
case 'internal.Serialport'
write(portObj,data_write,"uint8");
while (portObj.NumBytesAvailable == 0)
pause(0.01);
end
out = read(portObj,portObj.NumBytesAvailable,"uint8");
% If you expect that some of the data still can not be read
% (delayed data)
dataLength = out(3)*256+data(4);
% Some data is still delayed on channel...
while length(out) < dataLength
while (portObj.NumBytesAvailable == 0)
pause(0.01);
end
tmp = read(portObj,portObj.NumBytesAvailable,"uint8");
out = [out,tmp];
end
end
Categories
Find more on Whos in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!