while loop conditions 50-50 resolved/unresolved? help?
1 view (last 30 days)
Show older comments
I am currently using a responsebox, which I connected with a serial to USB converter into a XP x32 system. I have gotten some help to write the code to read it (see below). However, when I do not press a button, everything is always fine, it checks for 5 seconds, and then stops. About half of the trials it works fine, it gives me my responsevariables (button 64 or 128, and the time) and stops. However, the other 50 percent I get the error that the operand to the operators and && must be reducible to a logical scalar value. As I understand it, that means either a 0 untrue or a 1 true. I cannot fathom why the conditions can be falsified half the time, but not the other half. IF it goes wrong once, all tries after that go wrong too. Is there anyone with an idea what might be going on here?
Code:
function RSbox s = serial('COM10',... 'BaudRate',57600,... 'DataTerminalReady','on',... 'RequestToSend','off',... 'DataBits',8,... 'StopBits',1,... 'Parity','none'); %'Terminator',10);
fclose(s);
fopen(s);
t0 = tic; data = -1; disp('Here we go again!')
while ~((data == 64)||(data == 128))||(toc(t0)>5) if s.BytesAvailable >0 data = fread(s,s.BytesAvailable); reactiontime = toc(t0) end; %pause(0.01); end
fprintf('Var. data goes into matrix %i \n',data);
fclose(s); delete(s); clear s; return
1 Comment
Jan
on 24 Mar 2011
Please use code formatting as described here: http://www.mathworks.com/matlabcentral/answers/help/markup . It is always a good idea to make the question as easy to read as possible.
Accepted Answer
Jan
on 24 Mar 2011
while ~(any(data == 64) || any(data == 128)) ...
|| (toc(t0) > 5)
if s.BytesAvailable > 0
data = fread(s, s.BytesAvailable);
reactiontime = toc(t0)
end;
pause(0.01);
end
I've inserted some ANY commands: If more than 1 byte is available, "data == 64" replies a vector, which cannot be process by the operator. Please check, if ANY does what you need.
More Answers (0)
See Also
Categories
Find more on Startup and Shutdown 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!