iqb/gpio

GPIO 库和测试框架

dev-master 2015-10-26 12:46 UTC

This package is not auto-updated.

Last update: 2024-09-14 18:14:58 UTC


README

使用 Linux sysfs 接口进行 GPIO 抽象,主要适用于 Raspberry PI。

安装

只需将以下内容放入项目根目录下的 composer.json 文件中。目前尚无稳定版本。

"require": {
  "iqb/gpio": "*@dev"
}

特性

  • Pin 类:单个 GPIO 引脚的抽象
  • LCD 类:兼容 HD44780 的 16x2 显示屏的抽象
  • PinEmulator 类:用于 Pin 类的模拟替换
  • Emulator 类:使用 PinEmulator 使 GPIO 可通过软件测试!

GPIO 引脚抽象

Pin 类提供了一个简单的接口来操作 GPIO 引脚/端口。它使用 Linux 内核在 /sys/class/gpio 下提供的用户空间 GPIO 接口,因此显然在其它操作系统上无法工作。它是在 Raspbian Wheezy 上开发的。

Linux 内核通过数字来识别 GPIO 引脚。可以使用 gpio readall 命令的 BCM 值找到它们(需要 WiringPi 才能使用此命令)。

namespace iqb\gpio;

// Will open the GPIO pin with BCM number 17 = physical pin 11
$pin = new Pin(17);

// A pin must be enabled so it can be used.
// Pin-consumers like the LCD class enable pins themselves when they use them 
$pin->enable();

// Pin is in output mode
$pin->setDirection(Pin::DIRECTION_OUT);

// and the pin is now enabled (sending a 1)
$pin->setValue(true);

// Pin is in input mode now
$pin->setDirection(Pin::DIRECTION_IN);

// Enable edge detection.
// This feature is required to detect changes of the value.
$pin->setEdge(Pin::EDGE_BOTH);

// Read the current value
$value = $pin->getValue();

// We can wait for a change of the pin value using stream_select()
// We need to initialize the file handle sets we want to monitor.
// Changes to GPIO pins are "exceptional" (out of band) events
// so we need the third set of handles.
$read = [];
$write = [];
$except = [$pin->getValueHandle()];
while (true) {
  if (-1 === stream_select($read, $write, $except, 60)) { continue; }
  
  echo "Value changed: " . ($pin->getValue() ? '1' : '0') . "\n";  
}

兼容 HD44780 的 16x2 显示屏抽象

此显示屏通过 6 个 GPIO 引脚连接。

namespace iqb\gpio;

// Create the display, the pins are the actual used pins from my personal project
// You don't need to enable the pins or set the direction,
// that is done by the LCD class.
$lcd = new LCD(
  new Pin(7),
  new Pin(8),
  new Pin(25),
  new Pin(24),
  new Pin(23),
  new Pin(18)
);

// Enable the pins, set the direction, send some magic commands to the display ...
$lcd->initialize();

// Write something in the first line
$lcd->writeString('abcdefghijklmnop', 1);
// Write something in the second line
$lcd->writeString('0123456789012345', 2);