91 lines
1.8 KiB
PHP
Executable File
91 lines
1.8 KiB
PHP
Executable File
<?php
|
|
|
|
class Pin{
|
|
|
|
const GPIO_DIR = '/sys/class/gpio';
|
|
|
|
const GPIO_IN = 'in';
|
|
const GPIO_OUT = 'out';
|
|
|
|
const GPIO_HIGH = 1;
|
|
const GPIO_LOW = 0;
|
|
|
|
private $pin;
|
|
private $mode;
|
|
private $value;
|
|
|
|
public function __construct($pin){
|
|
if( !preg_match('@^\d+$@', $pin) )
|
|
throw new Exception("pin must be an integer");
|
|
|
|
|
|
/* (1) Make gpio pin available */
|
|
if( !file_exists(Pin::GPIO_DIR.'/gpio'.$pin) )
|
|
file_put_contents(Pin::GPIO_DIR.'/export', $pin);
|
|
|
|
/* (2) add attribute */
|
|
$this->pin = $pin;
|
|
}
|
|
|
|
|
|
public function __get($attr){
|
|
|
|
// if try to fetch value
|
|
if( $attr == 'value' ){
|
|
|
|
return ( file_get_contents(Pin::GPIO_DIR.'/gpio'.$this->pin.'/value') == '1' ) ? Pin::GPIO_HIGH : Pin::GPIO_LOW;
|
|
|
|
// if try to fetch mode
|
|
}else if( $attr == 'mode' ){
|
|
|
|
return ( file_get_contents(Pin::GPIO_DIR.'/gpio'.$this->pin.'/value') == 'in' ) ? Pin::GPIO_IN : Pin::GPIO_OUT;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
public function __set($attr, $value){
|
|
|
|
// if try to set value
|
|
if( $attr == 'value' ){
|
|
|
|
if( $value == Pin::GPIO_HIGH )
|
|
file_put_contents(Pin::GPIO_DIR.'/gpio'.$this->pin.'/value', 1);
|
|
else if( $value == Pin::GPIO_LOW )
|
|
file_put_contents(Pin::GPIO_DIR.'/gpio'.$this->pin.'/value', 0);
|
|
|
|
// if try to set mode
|
|
}else if( $attr == 'mode' ){
|
|
|
|
if( $value == Pin::GPIO_IN )
|
|
file_put_contents(Pin::GPIO_DIR.'/gpio'.$this->pin.'/direction', 'in');
|
|
else if( $value == Pin::GPIO_OUT )
|
|
file_put_contents(Pin::GPIO_DIR.'/gpio'.$this->pin.'/direction', 'out');
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
// USAGE
|
|
//
|
|
// $red = new GPIOPin(16);
|
|
// $green = new GPIOPin(20);
|
|
// $blue = new GPIOPin(21);
|
|
|
|
// $red->setMode(GPIO_OUT);
|
|
// $green->setMode(GPIO_OUT);
|
|
// $blue->setMode(GPIO_OUT);
|
|
|
|
// $red->set(GPIO_HIGH)
|
|
// $green->set(GPIO_LOW)
|
|
// $blue->set(GPIO_HIGH)
|
|
|
|
|
|
?>
|