Instrcallback function and while loops
3 ビュー (過去 30 日間)
I am trying to make use of Matlab instrument call back function however I am slightly confused. If I set my object such that I have a callback function and set it to be triggered when 1 byte is available, for eg:
Then do I need to have anything else in the script? For example I am interested in recording the output from fread(s,s.BytesAvailable). So should I specify this inside the callback function or somewhere later in the script?
More specifically I am also interested in categorising the output from fread. In my fread I either get the output to be "67" or "86" and I want to so if the output is 67... Fwrite this or while the output is 86... Fwrite this. But I'm unsure if these if and while loops should be in the callback function or in the script later on? And if I am creating loops to read the port, does it defeat the purpose of a callback function?
I don't have much knowledge of callback functions and I couldn't understand this through documentation. Any advice will be appreciated!!
回答 (2 件)
Dave Behera 2016 年 4 月 6 日
It seems you will need to define a property called 'ReadAsyncMode'. See this link:
and go to section 'Defining an Asynchronous Read Callback' in it.
Also, to categorise the read data as you mentioned, you will need to add the corresponding logic to your callback function.
Ritesh Naik 2016 年 4 月 6 日
I understand that you have set the callback function to be triggered when bytes-available event is generated. In your case since you have set the 'BytesAvailableFcnCount' to 1, bytes-available event would be generated everytime a byte is available in the input buffer.
Use 'fprintf' or 'fwrite' after you open the serial object to send data/command to the device i.e if device has to receive some instruction/command to send the data back as a reply.
Once device starts sending data, input buffer receives bytes thus generating bytes-available event. that in turns calls a callback function.
At this moment, there are bytes available in the input buffer when the callback function is called and you can place the 'fread' to read the data from the input buffer and 'if' logic to compare the bytes and send the data accordingly to the device using 'fwrite' inside the callback function.
For example: Following callback function reads the data sent by the device which is available in the the input buffer.
function CallBack(serialObj, event)
if ~(isfield(event, 'Type') && isfield(event, 'Data'))
EventType = event.Type;
bytesToRead = get(serialObj, 'BytesAvailablefcnCount');
T = fread(serialObj, bytesToRead, 'uchar')';
You can also refer to the 'instrcallback' template by entering the following command in MATLAB command window and base your callback function accordingly