using fscanf command for distance sensor
조회 수: 5 (최근 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!