• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

用Matlab和Arduino+HC-SR04建图

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

用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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap