using fscanf command for distance sensor
2 views (last 30 days)
Show older comments
Robin Johannes Terstappen
on 28 Nov 2017
Commented: Robin Johannes Terstappen
on 30 Nov 2017
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 Comments
Accepted Answer
Walter Roberson
on 28 Nov 2017
Edited: Walter Roberson
on 28 Nov 2017
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 Comments
Walter Roberson
on 29 Nov 2017
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
More Answers (0)
See Also
Categories
Find more on MATLAB Support Package for Arduino Hardware in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!