noccylabs / raspio
Raspberry Pi GPIO/外围库
This package is auto-updated.
Last update: 2024-09-07 06:51:53 UTC
README
安装
使用 composer 安装
composer require "noccylabs/raspio:dev-master"
或者通过克隆 github 仓库
git clone git@github.com:noccylabs/php-raspio
注意,composer 会处理自动加载;如果你克隆了仓库,你必须自己处理自动加载。
入门指南
在 Raspberry Pi 上,只需调用 RaspberryPi::getInstance() 来获取板驱动程序的实例。
use RaspIo\RaspberryPi;
// Get an instance of the Pi
$pi = RaspberryPi::getInstance();
getInstance() 将找到第一个已注册且不抛出异常的板驱动程序,确保它是一个 RaspIo\RaspberryPi 的实例,然后使用它进行后续的 getInstance() 调用。
设备在板驱动程序的构造函数中或在设备驱动程序中通过调用 registerDevice($id,$device) 方法进行注册。这使得它们可以通过各自的属性以及 getDevice() 方法使用。
// Like this
$gpio = $pi->gpio;
// Or this
$gpio = $pi->getDevice("gpio");
设备也可以通过调用 registerAlias($alias,$id) 进行别名设置。这用于在板上可能存在多种设备类型时定义默认设备。
你可以通过调用 getVersion() 获取检测到的板的信息
printf("Board: %s\n", $pi->getVersion());
设备也可以通过迭代访问,或通过 getRegisteredDevices()(和 getRegisteredAliases())访问。
printf("Devices:\n");
foreach($pi as $device=>$obj) {
printf(" %s => %s\n", $device, get_class($obj));
}
printf("Aliases:\n");
foreach($pi->getRegisteredAliases() as $alias=>$device) {
printf(" %s -> %s\n", $alias, $device);
}
...在其他任何平台
如果你将在不支持的平台使用或测试 RaspIo,你可以启用模拟。
use RaspIo\RaspberryPi;
// Add the emulated rev2 board. This must be done before the first
// call to RaspberryPi::getInstance()
RaspberryPi::addBoardDriver("RaspIo\\Board\\EmulatedRev2Board");
// Get an instance of the Pi
$pi = RaspberryPi::getInstance();
使用设备
GPIO
GPIO 以设备 id gpio 可用,并且它应该是一个实现 RaspIo\Device\Gpio\IGpioMapper 接口的类。它通常是 RaspIo\Device\Gpio\GpioMapper 的一个实例。
// Get Pi instance
$pi = RaspberryPi::getInstance();
// Export and set direction
$pin = $pi->gpio->export(0)->setDirection("out");
// Write to the pin
$pin->setValue(1);
可用方法在 RaspIo\Device\Gpio\IGpioExport 中定义
setDirection($dir)和getDirection()用于将 gpio 方向设置为in或out之一。setValue($val)和getValue()用于将 gpio 值设置为1或0。
要取消导出引脚,请在 GpioMapper 上调用 unexport()
// Unexport the pin
$pi->gpio->unexport(0);
UART
UART 支持尚未实现。
虚拟设备
虚拟设备是用作尚未实现设备的占位符。