经过昨天一下午,终于写好了基于
只需要安装完毕,就可以调用函数了:<?php
/**
* Created by PhpStorm.
* User: tioncico
* Date: 19-7-6
* Time: 下午4:45
*/
define('PI_TRIG',0);
define('PI_ECHO',1);
if (wiringPiSetup()===false){
echo "初始化错误!";
die;
}
//初始化引脚
ultraInit();
while (1) {
//测距
$dis = disMeasure();
printf("distance = %0.2f cm\n", $dis);
piDelay(1000);
}
function ultraInit(){
pinMode(PI_ECHO, PI_INPUT);
pinMode(PI_TRIG, PI_OUTPUT);
}
function disMeasure(){
//先关闭脉冲,初始化
digitalWrite(PI_TRIG,PI_LOW);
//等待2微秒
piDelayMicroseconds(2);
//发出超声波脉冲
digitalWrite(PI_TRIG, PI_HIGH);
piDelayMicroseconds(10);
//等待10秒,关闭脉冲
digitalWrite(PI_TRIG, PI_LOW);
//关闭之后,马上开始判断获取声波
while (!(digitalRead(PI_ECHO) == 1));
$startTime = piMicros();
//如果获取不到了,说明已经接收完毕
while (!(digitalRead(PI_ECHO) == 0));
$endTime = piMicros();
//声音在空气中传播是34000cm/s, 1000000微秒是1秒,去掉来回的声波时间,求出距离
$dis = ($endTime - $startTime) / 1000000 * 34000 / 2; //求出距离
return $dis;
}
使用root权限运行:
本文为仙士可原创文章,转载无需和我联系,但请注明来自仙士可博客www.php20.cn