用Matlab和Arduino+HC-SR04建图
今天突然想起买的HCSR04声纳传感器,拿出来在Arduino上试验了一下,现在想在用matlab实现数据的读取和图像的实时绘制。
硬件准备:Arduino Mega2560、 HC-SR04声纳传感器、线材若干
软件准备:
1、在matlab上安装对Arduino的Matlab和Simulink支持包
2、安装HC-SR04库文件(如何安装?)。
代码如下:
clc;
clear;
%设置端口和板类型
A=arduino('COM3','mega2560','Libraries',{'JRodrigoTech/HCSR04','Servo'});
%其中{'JRodrigoTech/HCSR04', 'Servo'}为需要的库函数
%% 添加HC-SR04传感器和舵机
sensor = addon(A, 'JRodrigoTech/HCSR04', 'D12', 'D13');
servo_motor = servo(A, 'D3');
%% Rotate the servo motor from 0 to 180 degrees.
% Every time the motor rotates, determine the distance of any obstacles
% via the bounceback time of the ultrasonic ping. Take two measurements
% and average them for accuracy. Record the angle and the distance (in cm)
i = 1;
table = zeros(180,2);
obstacle=[100;100];
for theta = 0 : 1/180 : 1
writePosition(servo_motor, theta);
dist1 = readTravelTime(sensor)*170;
pause(.04);
dist2 = readTravelTime(sensor)*170;
dist = (dist1+dist2)/2;
table(i,1) = (i-1);
table(i,2) = round(dist * 100,2);
i = i + 1;
obstacle(1)=dist*cos(theta*pi);
obstacle(2)=dist*sin(theta*pi);
figure(1)
axis equal
hold on
line([0,obstacle(1)],[0,obstacle(2)]);
%plot(obstacle(1),obstacle(2),'r.');
end
% Rotate the servo motor from 180 to 0 degrees. Replace the values in the
% table with the average of the clockwise and counterclockwise scans to
% improve the accuracy of the map.
j = 1;
for theta = 1 : -1/180 : 0
writePosition(servo_motor, theta);
dist1 = readTravelTime(sensor)*170;
pause(.04);
dist2 = readTravelTime(sensor)*170;
dist=(dist1+dist2)/2;
if dist<table(i-j,2)
table(i-j,2)=dist;
end
obstacle(1)=table(i-j,2)*cos(theta*pi);
obstacle(2)=table(i-j,2)*sin(theta*pi);
figure(1)
line([0,obstacle(1)],[0,obstacle(2)],'color','r');
% plot(obstacle(1),obstacle(2),'r.');
j = j + 1;
end
%% Make a polar plot of the distance data to display the map.
% Limit the theta values to be between 0 and 180 because the map is only
% for obstacles in front of the servo.
figure (2)
polarplot (table(:,1)*pi/180, table (:,2));
title('Map of the Environment');
thetalim([0 180]);
grid on;
我的结果运行结果:
参照官方教程:https://ww2.mathworks.cn/videos/mapping-your-surroundings-using-matlab-and-arduino-121311.html
|
请发表评论