while loop conditions 50-50 resolved/unresolved? help?

1 view (last 30 days)
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
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.

Sign in to comment.

Accepted Answer

Jan
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.
  2 Comments
Sirius
Sirius on 28 Mar 2011
Thank you very much! Unfortunately I haven't been able to test it until now. It indeed solves my problem, but also creates another one. Like you said, sometimes you get multiple signals: so either 64 or 128, or one of these and a second variable containing zero, or even a third containing either 64 or 128 again, but always the same as the first one. I suppose this is dependent on the duration of the button press. My task now is to somehow retain only the first, containing 64 or 128, without it being overwritten. I'm going to attempt this now, if I solve it myself I'll post again, but if you have any nice ideas on how to do this in the mean time, I would be very greatful.
Sirius
Sirius on 28 Mar 2011
Fixxed it! Thanks so much again, now I can get on!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!