ikarus / raspberry-pinout
v0.8.0
2022-04-22 19:58 UTC
Requires
- php: >=7.2
- ext-pcntl: *
Suggests
- ext-pcntl: *
README
此包包含有关Raspberry Pi设备引脚排布的所有信息。
它帮助您分配和准备引脚,也可以清理它们。
安装
$ composer require ikarus/raspberry-pinout
用法
存在一个名为RaspberryPiDevice的单例类,该类包含有关引脚排布及其设备的所有信息。
<?php use Ikarus\Raspberry\RaspberryPiDevice; $dev = RaspberryPiDevice::getDevice(); echo $dev->getModelName();
设备创建后,您可以定义自定义引脚排布
<?php use Ikarus\Raspberry\Pinout\Revision_1\AbstractBoardPinout; use Ikarus\Raspberry\Pinout\Revision_2\AbstractBCMPinout; use Ikarus\Raspberry\Pinout\Revision_3\AbstractWpiPinout; // Take the abstract pinout class you need (device specific like rev 1-3) and you want to declare the pinout (bcm, wpi or board). class MyPinout extends AbstractWpiPinout { const MOTOR_A = 0; const MOTOR_B = 1; const CONTACT_A = 2; const CONTACT_B = 3; const ASPIRATION = 4; protected $inputPins = [ self::CONTACT_A => self::INPUT_RESISTOR_UP, self::CONTACT_B => self::INPUT_RESISTOR_DOWN ]; protected $outputPins = [ self::MOTOR_A => false, self::MOTOR_B => false, self::ASPIRATION => true // Use PWM ]; protected $activeLowPins = [ self::CONTACT_A // Inverts its value => if the pin is high, the value is 0. ]; }
现在您可以与pi一起工作
<?php require "vendor/autoload.php"; use Ikarus\Raspberry\RaspberryPiDevice; $dev = RaspberryPiDevice::getDevice(); $dev->requirePinout( new MyPinout() ); // Drive forward $dev->getOutputPin( MyPinout::MOTOR_A )->setValue(1); while ( $dev->getInputPin( MyPinout::CONTACT_A )->getValue() ) usleep(10000); // Motor stop $dev->getOutputPin( MyPinout::MOTOR_A )->setValue(0); sleep(2); // Drive backwards $dev->getOutputPin( MyPinout::MOTOR_B )->setValue(1); while ( $dev->getInputPin( MyPinout::CONTACT_B )->getValue() == 0 ) usleep(10000); // Motor stop $dev->getOutputPin( MyPinout::MOTOR_B )->setValue(0); // Releases all pins and brings them into a secure state (mode = input, value = 0 and resistor = none). $dev->cleanup();
或使用内置的安全循环方法
<?php $dev->loop(1/1000, function() { // Safe loop call });
安全意味着Ikarus确保在所有情况下调用方法 $dev->cleanup()
。
它注册中断处理程序,因此命令行中的^C也会进行清理。
边缘
Ikarus实现了一个边缘检测机制。
因此,为了改进上述示例,您可以监视边缘而不是轮询引脚
<?php use Ikarus\Raspberry\Edge\Edge; // Change /** @var \Ikarus\Raspberry\RaspberryPiDevice $dev */ while ( $dev->getInputPin( MyPinout::CONTACT_A )->getValue() ) usleep(10000); // Into $edge = new Edge($dev->getInputPin( MyPinout::CONTACT_A ), Edge::EDGE_FALLING); // Watch for 2.5 seconds for a falling edge // This method blocks until the requested edge (raising|falling|both) did occur or time is up. if($dev->watchEdge(2.5, $edge)) { echo "OK, Motor stopp\n"; } else { echo "Failed! Action took too long!\n"; } $dev->getOutputPin( MyPinout::MOTOR_A )->setValue(0); // You can also check the $edge like switch ($edge->getValue()) { case Edge::VALUE_DID_FALL: echo "did fall"; break; case Edge::VALUE_DID_RISE: echo "did rise"; break; default: echo "Nothing happen"; }
监视边缘比轮询引脚使用更少的CPU性能。
请注意,引脚状态可能会反弹。
因此,从 $edge->getValue() 获取引脚的值可以获取真实的触发边缘值。