using fscanf command for distance sensor
2 ビュー (過去 30 日間)
古いコメントを表示
Robin Johannes Terstappen
2017 年 11 月 28 日
コメント済み: Robin Johannes Terstappen
2017 年 11 月 30 日
I am connecting an ultrasonic distance sensor to matlab with the 'serial' command, using the code below. When trying to get the distances as an output with a for loop I get an error in the line where I use the command 'fscanf'. Matlab tells me:
Error using fscanf
Invalid file identifier. Use fopen to generate a valid file identifier.
Error in subsonicsensor (line 12)
y(i)=fscanf('arduino','%cm');
Can anybody tell me how I can adjust my for loop, or rest of the code to get the right distances from the code?
I also tried using fprintf instead of fscanf. This gave me the value 7cm for al 100 measurements. Can anybody explain?
Here is my code:
clear all
clc
arduino=serial('COM3','BaudRate',9600);
x=linspace(1,100);
L = length(x);
for i=1:L
fopen('arduino');
y(i)=fscanf('arduino','%cm');
pause(0.05);
end
fclose(arduino);
disp('making plot..')
plot(x,y);
0 件のコメント
採用された回答
Walter Roberson
2017 年 11 月 28 日
編集済み: Walter Roberson
2017 年 11 月 28 日
Move the
fopen('arduino');
to before the loop, and change it to
fopen(arduino);
Change the
y(i)=fscanf('arduino','%cm');
to
y(i)=fscanf(arduino,'%fm');
6 件のコメント
Walter Roberson
2017 年 11 月 29 日
Change
y(i)=fscanf(arduino,'%fm');
to
thisline = fgetl(arduino);
if strcmpi(thisline, 'Out of Range')
fprintf('Out of Range reported at point #%d\n', i)
y(i) = nan;
else
thisdist = sscanf(thisline, '%f');
if isempty(thisdist)
fprintf('Unexpected response at point #%d; line was: "%s"\n', i, thisline);
y(i) = nan;
else
if length(thisdist) > 1
fprintf('Multiple distances reported for point #%d, using first; line was "%s"\n', i, thisline);
end
y(i) = thisdist(1);
end
end
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で MATLAB Support Package for Arduino Hardware についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!