MATLAB: Read bytes from putc CCS to matlab gui

matlab coderread bytes

Hello, i have this code :
s.BytesAvailableFcnMode = 'byte';
s.BytesAvailableFcnCount = 1;
s.BytesAvailableFcn = {@mycallback,handles};
function mycallback(obj,event,handles)
global s;
data1 = fread(s,1); //read 1 byte
end
The question's "when i use 2 times putc, how can i read 2 bytes at the same time, one for data1 and one for data2 ???"

Best Answer

function [queryfcn, removefcn] = buffer_bytes(s)
persistent byte_buffer
persistent buffer_count
if isempty(buffer_count)
byte_buffer = [];
buffer_count = 0;
end
s.BytesAvailableFcnMode = 'byte';
s.BytesAvailableFcnCount = 1;
s.BytesAvailableFcn = @mycallback;
queryfcn = @query_buffer;
removefcn = @query_remove;
function mycallback(obj,event,handles)
current_bytes = fread(s, s.BytesAvailable);
num_bytes = length(current_bytes);
byte_buffer(buffer_count+1:buffer_count+num_bytes) = current_bytes;
buffer_count = buffer_count + num_bytes;
end
function buffer = query_buffer(maxn)
if nargin < 1 || maxn > buffer_count
maxn = buffer_count;
end
buffer = bytes_buffer(1:maxn);
end
function query_remove(count)
if count >= buffer_count
byte_buffer = [];
buffer_count = 0;
else
byte_buffer(1:count) = [];
buffer_count = buffer_count - count;
end
end
end
You call buffer_bytes, passing in the serial object. You get back a pair of function handles, queryfcn and removefcn; and bytes start to be buffered in the background as they arrive.
At any time, you call the first handle that was returned, the query function. If you do not pass in any parameter, then the output of the query function is a copy of all of the bytes that are currently queued. If you pass in a parameter, then at most that many bytes will be returned, with fewer returned if that was all that was available.
At any time, you call the second handle that was returned the removefcn. You must pass in a parameter, which is a count of the number of bytes to remove from the internal buffer. Bytes are left in the buffer until they are removed -- so if you call the query function multiple times, then the same bytes will be returned until you tell the remove function to discard them.
Not that I would bother with any of this stuff myself. instead I would just query s.BytesAvailable to find out whether there were at least 2 bytes available, and fread(s, 2, 'uint8') when it was time to fetch them.