get continuous data in while loop through serial

20 ビュー (過去 30 日間)
Sharah
Sharah 2019 年 1 月 18 日
編集済み: Sharah 2019 年 1 月 18 日
Hello,
I need help with reading data from serial. Basically I have arduino that sends data "0" or "1" randomly every 2-4 seconds. When I save this data i will get 0 or 1. However, what I want is a continuous data, i.e. even when the true or false does not change, i still can record that. in this case have an array of 0 or 1 instead of 01010101. how can i do this? my code:
s = serial('COM13', 'BaudRate', 115200);
fopen(s);
y=[];
t1 = tic;
while (t<10)
x = fscanf(s)
t = toc(t1);
y = [y; t, x] % right now it's only 010101, but i want eg 00000011111111111110001111...
%with time stamp
end

回答 (1 件)

Walter Roberson
Walter Roberson 2019 年 1 月 18 日
You can test the BytesAvailable property of the port. If it is 0 then repeat your most recent reading . You might want to configure a timer object to sample at appropriate frequency .
  3 件のコメント
Walter Roberson
Walter Roberson 2019 年 1 月 18 日
It would be 0 except when data has been received but not processed . Your current fgets is blocking waiting for a complete line so you would need to be using a timer to detect the situation as timers should be able to interrupt the wait.
You should reorganize . Don't use while . Use BytesAvailableFcn to trigger the fgets and store the result in a known place . use aa timer object set to repeat at your desired sampling frequency . The timer should retrieve the current value from the known location and leave the value there . If the timer fires again before the BytesAvailable callback has read in the next value then the same value as before will be read.
Sharah
Sharah 2019 年 1 月 18 日
編集済み: Sharah 2019 年 1 月 18 日
Actaully I made a mistake before and using the BytesAvailable works now. Many thanks for the suggested answer. DO you know any sample code that shows BytesAvailableFcn? I have never used it before. I need to read and store the data at 100Hz.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMATLAB Support Package for Arduino Hardware についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by