While loop stuck - matlab

I have written a callback function in Matlab. My laptop is communicating with another laptop that is sending it bytes every few seconds that are recorded in a text file. For e.g. the laptop sends "66" and my laptop writes to the file Event_Markers.txt "66" continuously until the other laptop sends something else. The code is below.
The problem that I am currently facing is that in my callback function (below) I use a while loop to continuously write the same "information" (e.g. "66") to the text file until the other laptop sends something else. But this while loop gets stuck. This part is of a larger script that is acquiring data from a spectrometer and adding it to my script and causes everything to become stuck and the rest of the script is not executed. I tried to use an if loop instead of while and it only writes "66" twice instead of writing it continuously. It is, however, writing to the text file as I want it to.
Does anybody know if I need to add some other line of code to stop it becoming stuck?
Thanks!
appenderFile=fopen('Event_Markers.txt','a+t');
s=serial('COM3');
set(s,'BytesAvailable',{#myCallback,appenderFile});
set(s,'BytesAvailableFcnCount',1);
set(s,'BytesAvailableFcnMode','byte');
fopen(s);
function myCallback(s,~,appenderFile)
bytes=(s,'BytesAvailable')
if(bytes==1)
[data count msg] = fread(s,bytes);
end
fprintf(appenderFile,'%d \n',data);
bytes=(s,'BytesAvailable');
while bytes==0
fprintf(appenderFile,'%d \n',data);
bytes=get(s,'BytesAvailable');
end
end

You need to break out of the loop when "something else is sent", something like:
while bytes==0
fprintf(appenderFile,'%d \n',data);
bytes=get(s,'BytesAvailable');
if s ~= 66
break
end
end

Related

Openpanel and symbol communication not working

I am trying to make a patch that plays audio when a bang is pressed. I have put a symbol so that I don't need to keep reimporting the file. However it works sometimes but not all the time.
A warning in the Pd console reads: Start requested with no prior open
However I have imported an audio file
Is there something that I have done wrong?
Use [trigger] to get the order-of-execution correct.
One problem is, that whenever you send a [1( to [readsf~] you must have sent an [open ...( message directly beforehand.
Even if you have just successfully opened a file, but then stopped it (with [0() or played it through (so it has been closed automatically), you have to send the filename again.
The real problem is, that your messages are out of order: you should never have a fan-out (that is: connecting a message outlet to multiple inlets), as this will create undefined behavior.
Use [trigger] to get the order-of-execution correct.
(Mastering [trigger] is probably the single most important step in learning to program Pd)

ram keeps on filling when program is abruptly closed in matlab

MAT-lab keeps on acquiring images form video object when program is closed abruptly,is there any way to know whether my program has been stopped abruptly?
it only stops when i type stop(vid), condition: the vid object must be there in work space
if you have cleared vid object by clear all , then MAT-LAB keeps on acquiring image from the camera
I think what you mean is this: You have some matlab code that acquires data from a camera. If your code exits before getting to the point at which you order the camera to stop acquiring data, then the camera keeps going until your RAM is full Please correct me if I'm wrong. If I'm right, I'd advise you use try/catch statements as follows:
start(vid);
try
%some code to use the video data
stop(vid);
catch
stop(vid);
end
Everything inside 'try' will run, and when it has finished, the video capture will be terminated. If something goes wrong and throws an error before it has got as far as the stop(vid); command, then rather than stalling the program it will display the error in the matlab prompt, and then jump to execute any code inside 'catch'. This means that if your code ends suddenly, the stop(vid); command is still run, and you don't run out of RAM.

How can I save output from Simulink?

I'm a student learning to use MATLAB. For an assignment, I have to create a simple state machine and collect some results. I'm used to using Verilog/Modelsim, and I'd like to collect data only when the state machine's output changes, which is not necessarily every time/sample period.
Right now I have a model that looks like this:
RequestChart ----> ResponseChart ----> Unit Delay Block --> (Back to RequestChart)
| |
------------------------> Mux --> "To Workspace" Sink Block
I've tried setting the sink block to save as "Array" format, but it only saves 51 values. I've tried setting it to "Timeseries", but it saves tons of zero values.
Can someone give me some suggestions? Like I said, MATLAB is new to me, please let me know if I need to clarify my question or provide more information.
Edit: Here's a screen capture of my model:
Generally Simulink will output a sample at every integration step. If you want to only output data when a particular event occurs -- in this case only when some data changes -- then do the following,
run the output of the state machine into a Detect Change block (from the Logic and Bit Operations library)
run that signal into the trigger port of a Triggered Subsystem.
run the output of the state machine into the data port of the Triggered Subsystem.
inside the triggered subsystem, run the data signal into a To Workspace block.
Data will only be saved at time point that the trigger occurs, i.e. when your data changes.
In your Simulink window, make sure the Relative Tolerance is small so that you can generate many more points in between your start and ending time. Click on the Simulation option at the top of the window, then click on Model Configuration Parameters.
From there, change the Relative Tolerance to something small... like 1e-10. After that, try running your simulation again. You should have a lot more points in your output array that you can now save.

Stopping cURL transfer in Matlab

I wrote a Matlab GUI that's used to automate the transfer of data to and from an ftp server, which is done using cURL, e.g.
str = sprintf(' "%s" -O "ftp://%s:%s#%s" -Q "CWD %s%s/" ', ...
handles.curl, username, password, ...
strcat(ftpname, d{1}), '/users/', username);
% Try to transfer file until successful (s=0)
s = 1;
while s ~= 0
s = dos(str);
end
Typically this GUI will be ran on a slow network, so transferring a 50 MB file could take up to 30 minutes or longer.
What I'd like to know is that if a "Stop" button is pressed on the GUI while it's in the middle of a data transfer, is there a way in cURL to cancel that transfer, or do I need to let it complete?
You could setup a timer object with a callback to check if the user hit the cancel button and then try to kill the process via a different dos command. The only thing I don't like is the whole external process cURL, it may be difficult to know you for sure got the right process. Is there a reason you didn't try any of the Matlab transfer commands?

socket receive loop never returns

I have a loop that reads from a socket in Lua:
socket = nmap.new_socket()
socket:connect(host, port)
socket:set_timeout(15000)
socket:send(command)
repeat
response,data = socket:receive_buf("\n", true)
output = output..data
until data == nil
Basically, the last line of the data does not contain a "\n" character, so is never read from the socket. But this loop just hangs and never completes. I basically need it to return whenever the "\n" delimeter is not recognised. Does anyone know a way to do this?
Cheers
Updated
to include socket code
Update2
OK I have got around the initial problem of waiting for a "\n" character by using the "receive_bytes" method.
New code:
--socket set as above
repeat
data = nil
response,data = socket:receive_bytes(5000)
output = output..data
until data == nil
return output
This works and I get the large complete block of data back. But I need to reduce the buffer size from 5000 bytes, as this is used in a recursive function and memory usage could get very high. I'm still having problems with my "until" condition however, and if I reduce the buffer size to a size that will require the method to loop, it just hangs after one iteration.
Update3
I have gotten around this problem using string.match and receive_bytes. I take in at least 80 bytes at a time. Then string.match checks to see if the data variable conatins a certain pattern. If so it exits. Its not the cleanest solution, but it works for what I need it to do. Here is the code:
repeat
response,data = socket:receive_bytes(80)
output = output..data
until string.match(data, "pattern")
return output
I believe the only way to deal with this situation in a socket is to set a timeout.
The following link has a little bit of info, but it's on http socket: lua http socket timeout
There is also this one (9.4 - Non-Preemptive Multithreading): http://www.lua.org/pil/9.4.html
And this question: http://lua-list.2524044.n2.nabble.com/luasocket-howto-read-write-Non-blocking-TPC-socket-td5792021.html
A good discussion on Socket can be found on this link:
http://nitoprograms.blogspot.com/2009/04/tcpip-net-sockets-faq.html
It's .NET but the concepts are general.
See update 3. Because the last part of the data is always the same pattern, I can read in a block of bytes and each time check if that block has the pattern. If it has the pattern it will mean that it is the end of the data, append to the output variable and exit.