using fscanf command for distance sensor
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Robin Johannes Terstappen
el 28 de Nov. de 2017
Comentada: Robin Johannes Terstappen
el 30 de Nov. de 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 comentarios
Respuesta aceptada
Walter Roberson
el 28 de Nov. de 2017
Editada: Walter Roberson
el 28 de Nov. de 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 comentarios
Walter Roberson
el 29 de Nov. de 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
Más respuestas (0)
Ver también
Categorías
Más información sobre MATLAB Support Package for Arduino Hardware en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!