How do I update data through serial port?

9 views (last 30 days)
I would like to get input data through serial communication instead of 'for' sentence to provide input variables.
For example,
I opened 2 serial port and communicated serial data through following code.
Computer 1.
s=serial('COM7')
fopen(s)
while(1)
fwrite(s,[0 90 180 270 360]) %pusai(i) input
end
computer 2.
s=serial('COM8')
fopen(s)
a=fread(s)
Like above, computer 2 gets the 'a' serial data having [0 90 180 270 360].
I would like to get the data [0 90 180 270 360] on real-time(continuously) through serial data communication.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 18 Oct 2013
You can use the 'BytesAvailable' property of the serial object to monitor incoming data and trigger read operations when a specified number of bytes are available. Thus reading in the data and use the data on the second computer, in an approximately real-time manner.
There are two ways to use this property:
1. Use the 'BytesAvailableFcn' callback function. This function automatically executes when a specified number of bytes are available. The code to read the data and can be put into this callback function.
Please refer to the small demo code that illustrates this method at the following.
function serialContinuousReader()
%open serial port
s = serial('COM1');
%set bytes-available-callback to execute after number of bytes available
set(s, 'BytesAvailableFcnMode', 'byte');
%set number of bytes to be ready
set(s, 'BytesAvailableFcnCount', 5);
%set function to execute when bytes are ready
set(s, 'BytesAvailableFcn', @(obj, e)obtainData(s))
fopen(s);
function obtainData(s)
%obtain number of bytes available
bytesAvailable = get(s, 'BytesAvailable');
%obtain latest data available
data = fread(s, bytesAvailable);
2. Run a continuous WHILE loop, and continuously check the 'BytesAvailable' property to see if it goes over a certain threshold. When it does, initiate read the data.

More Answers (0)

Tags

No tags entered yet.

Products


Release

R2012a

Community Treasure Hunt

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

Start Hunting!