经过昨天一下午,终于写好了基于wiringPi 的php扩展,源码地址:https://github.com/tioncico/phpPi
只需要安装完毕,就可以调用函数了:
<?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权限运行: