How do I update data through serial port?

조회 수: 8 (최근 30일)
MathWorks Support Team
MathWorks Support Team 2013년 10월 18일
답변: MathWorks Support Team 2014년 7월 30일
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.

채택된 답변

MathWorks Support Team
MathWorks Support Team 2013년 10월 18일
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.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Low-Level File I/O에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

제품


릴리스

R2012a

Community Treasure Hunt

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

Start Hunting!

Translated by