I am using HC-SR04 ultrasonic sensor with raspberry pi 3 interfaced with MATLAB 2017b. When I run my code to measure distance of an object from sensor my code goes in infinite loop detecting nothing. Code is as follows:
4 次查看(过去 30 天)
显示 更早的评论
trig=17;
echo=27;
configurePin(mypi,echo,'DigitalInput')
configurePin(mypi,trig,'DigitalOutput')
writeDigitalPin(mypi,trig,0)
pause(1)
writeDigitalPin(mypi,trig,1)
pause(0.00001)
writeDigitalPin(mypi,trig,0)
readDigitalPin(mypi,echo)
while readDigitalPin(mypi,echo)== 0
a = toc
while readDigitalPin(mypi,echo)== 1
b = toc;
end
end
pulseDuration = b-a;
distance = pulseDuration*17150;
distance= round(distance,2)
display(distance)
3 个评论
回答(1 个)
松繁
2023-2-18
% clear mypi
% mypi=raspi;
configurePin(mypi,4,'DigitalOutput'); % 5脚设置为输出脚 21 Trig发送引脚
configurePin(mypi,17,'DigitalInput'); % 13脚设置为输入脚23 Echo接收引脚
%disp(readDigitalPin(mypi,17));
while (1)
dis=0;
try
dis=distance(mypi);
catch error % 捕获到异常
pause(2);
% disp("超出量程(4米)");
continue; % 跳出本次循环
end
pause(2);
if (dis>4) % 异常数据
pause(2);
% disp("超出量程(4米)");
continue; % 跳出本次循环
end
disp(dis+"米");
end
%编写测距函数并调用
function distance=distance(mypi)
while(readDigitalPin(mypi,17)==0)% 假如13脚一直为低电平,则一直循环
writeDigitalPin(mypi,4,0);
pause(0.5);
writeDigitalPin(mypi, 4, 1); % trig输出正向脉冲
pause(0.00001); % 10US=1.0e-5# pause(0.0001); % 100微妙 原//pause(n秒)
% pause(0.000012)= pause(1.2e-5) 保持10us以上(选择12us)
writeDigitalPin(mypi, 4, 0); % trig低电平
%pause(2.0e-4);%8个40kHz的TTL
disp("Echo脚低电平"); % 调试控制台打印数据
end
tic; % Echo脚变高电平时开始本次计时
while(readDigitalPin(mypi,17)==1)% 假如13脚一直为高电平,则一直循环
%disp("Echo高电平"); % 可能为HCSR04模块内部短路
end
distance=toc*343/2; % Echo脚变高电平时结束本次计时
% 中间时段便是HCSR04模块一次超声波传播并返回的总时间
end % 距离=时间*声速/2
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Performance and Memory 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!