필터 지우기
필터 지우기

how to use while loop

조회 수: 1 (최근 30일)
Prashant Funde
Prashant Funde 2016년 6월 20일
답변: Walter Roberson 2016년 6월 20일
I am using 2 variables for getting(Receiving) data from serial port. I want to use while loop to operate these two variables. I am using following two variables : 1. Rcvd_1 & 2. Rcvd_2
I want to create a code in such a way that first i will check that Rcvd_1 is null and if so then i will start filling it, and as soon as it fills data storage will start in Rcvd_2.
While Rcvd_2 is filling i want to clear variable Rcvd_1.
So please suggest me what type of looping condition should be neede to do so.
Thanks in advance

답변 (1개)

Walter Roberson
Walter Roberson 2016년 6월 20일
chunk_size = 8192; %or as appropriate
while true
this_byte = fread(s, 1);
%check that Rcvd_1 is null and if so then i will start filling it
if ~exist('Rcvd_1', 'var')
Rcvd_1 = zeros(1, chunk_size, 'uint8');
idx1 = 0;
end
%fills data storage
if idx1 < chuck_size
idx1 = idx1 + 1;
Rcvd_1(idx1) = this_byte;
%as it fills data storage will start in Rcvd_2.
else
%check that Rcvd_2 is null and if so then i will start filling it
if ~exist('Rcvd_2', 'var')
Rcvd_2 = zeros(1, chunk_size, 'uint8');
idx2 = 0;
end
%fills data storage
if idx2 < chunk_size
idx2 = idx2 + 1;
Rcvd_2(idx2) = this_byte;
%as it fills data storage will start in Rcvd_1
else
%While Rcvd_2 is filling i want to clear variable Rcvd_1
Rcvd_1 = zeros(1, chunk_size, 'uint8');
idx1 = 0;
%as it fills data storage will start in Rcvd_1
idx1 = idx1 + 1;
Rcvd_1(idx1) = this_byte;
end
end
You will find that this method is not efficient. Reading one byte at a time has a lot of overhead, and making decisions on two sets of variables has more overhead than making decisions on one variable does. I posted more efficient code a few days ago; see http://www.mathworks.com/matlabcentral/answers/290111-problem-with-serial-port-communication#comment_373272

카테고리

Help CenterFile Exchange에서 Verification Mode에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by