I'm using a raspberry pi to control lightning in my apartment, and currently I'm writing a class to control RGB Leds. However, I'm having some troubles with it, and this particular problem is going to drive me crazy.
Whenever I call a function, setRed() for example, I get a notice that says Notice: Undefined variable: GPIORed in M:\wamp\www\LedControl\class.rgbcontrol.php on line 16
Shortened version of my class looks like this:
class RGBControl {
var $GPIORed;
var $GPIOGreen;
var $GPIOBlue;
public function __construct($red,$green,$blue) {
$this->GPIORed = $red;
$this->GPIOGreen = $green;
$this->GPIOBlue = $blue;
}
public function setRed($power){
shell_exec("echo \"$GPIORed=$power\" > /dev/pi-blaster");
}
public function setGreen($power){
shell_exec("echo \"$GPIOGreen=$power\" > /dev/pi-blaster");
}
public function setBlue($power){
shell_exec("echo \"$GPIOBlue=$power\" > /dev/pi-blaster");
}
}
So here's basic usage, I'm defining the class with arguments 24,23,18 (the GPIO pins on the Raspberry Pi that my leds are connected to).
$LED = new RGBControl (24,23,18);
$LED->setRed($color[0] / 255);
$LED->setGreen($color[1] / 255);
$LED->setBlue($color[2] / 255);
But what am I doing wrong?
The lines like this:
shell_exec("echo \"$GPIOBlue=$power\" > /dev/pi-blaster");
are trying to resolve variables named $GPIOBlue
and $power
, but $GPIOBlue
doesn't exist. You need to use $this
to access instance member variables. For example,
shell_exec("echo \"{$this->GPIOBlue}=$power\" > /dev/pi-blaster");
public function setRed($power){
shell_exec("echo \"$GPIORed=$power\" > /dev/pi-blaster");
}
You are trying to access the $GPIORed variable in the scope of the shell interpreter. It is only accessible through php. Like Dan mentioned, it's a scope reference issue. My bad.
I would recommend using a file operation instead of using shell_exec, partly because of security and partly because of readability.
file_put_contents("/dev/pi-blaster", "{$this->GPIORed}=$power
");