MATLAB Answers

Read Data from MATLAB Serial Port one by one byte and then process it ?

7 views (last 30 days)
Arun Sharma
Arun Sharma on 1 Dec 2015
Commented: Walter Roberson on 1 Dec 2015
Hello!! All
I have to develop a MATLAB GUI application, which will regularly communicate with my Hardware and share data from hardware and MATLAB. The communication interface is Serial Interface.
The problem is that, i can't add any terminator in my packet, i just have a Start of Packet and at last the byte of packet is check-sum of whole packet, so what i decided is to write a callback function, which is called whenever data is received on serial port.
% Create Serial Object at 9600 BaudRate
handles.serial = serial('COM1','BaudRate', 9600);
handles.serial.BytesAvailableFcnCount = 1;
handles.serial.BytesAvailableFcnMode = 'byte';
handles.serial.BytesAvailableFcn = @Serial_Receive;
And the callback function is as follow:
function Serial_Receive(sObject, eventdata)
global TransRxBuffer;
global TRANS_STATE_IDLE;
global TRANS_STATE_DEST;
global TRANS_STATE_SRC;
global TRANS_STATE_LEN;
global TRANS_STATE_DATA;
global TRANS_STATE_CS;
global trans_state;
global TRANS_HEADER;
global MY_ADDRESS;
global DEST_ADDRESS;
global true false;
true = 1;
false = 0;
ByteAvailable = sObject.BytesAvailable;
tmp_c = fread(sObject,1,'uint8'); % Reading only 1 byte
switch(trans_state)
case TRANS_STATE_IDLE
if tmp_c == TRANS_HEADER
trans_state = TRANS_STATE_DEST;
TransRxBufferCount = 0;
trans_length = 0;
data_ready = false;
TransRxBuffer(TransRxBufferCount) = tmp_c;
TransRxBufferCount = TransRxBufferCount + 1;
TransChecksum = 0;
TransChecksum = bitxor(TransChecksum,tmp_c);
end
case TRANS_STATE_DEST
AND SO ON....
  1 Comment
Walter Roberson
Walter Roberson on 1 Dec 2015
It is not clear what your question is?
Setting BytesAvailableFcnMode to byte and count of 1 should work.

Sign in to comment.

Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!