PHP 点亮 Raspberry Zero Pi W 上 LED 的脚本

PHP script to lights up LED on Raspberry Zero Pi W

我不太了解PHP,但我想问一下我应该如何改进这个脚本。

添加我现有代码的截图,我简单描述一下。

当第一次按下网络按钮时,该程序会导致 LED 亮起。

必须满足条件,即文件大小必须等于 2 个字节。当执行第一个条件时,一个更大的 4 字节数字被写入 txt 文件。

再次按同一个按钮,应该满足第二个条件,但出现文件被覆盖的错误,但条件不能满足,不知为何。

你不会问别人哪里可能有问题或者你怎么可能解决这个问题吗?

这是部分代码:

    if(!file_get_contents("soubor.txt", 0)) {
            $soubor = fopen("soubor.txt","w+");
            $funkceled1 = 10;
            fwrite ($soubor, $funkceled1);
            fclose ($soubor);
        }

     if (isset($_GET['on1']) && file_get_contents("soubor.txt", 2)) {
                shell_exec("/usr/local/bin/gpio -g write 14 1");
                $soubor = fopen("soubor.txt","w+");
                $funkceled1 = 1000;
                fwrite ($soubor, $funkceled1);
                fclose ($soubor);
            }
     else if (isset($_GET['on1']) && file_get_contents("soubor.txt", 4)) {
                shell_exec("/usr/local/bin/gpio -g write 14 0");
                $soubor = fopen("soubor.txt","w+");
                $funkceled1 = 10;
                fwrite ($soubor, $funkceled1);
                fclose ($soubor);

您的代码可以这样重写:

$fileName = __DIR__.'/soubor.txt';
// if the file does not exist or does not contain '10' nor '1000', create it with default value '10'
if (!file_exists($fileName) || (file_get_contents($fileName) !== '10' && file_get_contents($fileName) !== '1000')) {
    file_put_contents($fileName, '10');
}
if (isset($_GET['on1']) && file_get_contents($fileName) === '10') {
    shell_exec("/usr/local/bin/gpio -g write 14 1");
    file_put_contents($fileName, '1000');
} else if (isset($_GET['on1']) && file_get_contents($fileName) === '1000') {
    shell_exec("/usr/local/bin/gpio -g write 14 0");
    file_put_contents($fileName, '10');
}

我不知道你的 gpio 二进制文件是如何工作的,但也许你除了写一个值外,还可以读取一个值?那么你可以让这个变得超级简单:

// read the current state from gpio (if 'read' is an option )
$current_state = shell_exec('/usr/local/bin/gpio -g read 14');

if (isset($_GET['on1']))  {
    // if it's off, turn it on, otherwise off.
    $new_state = (($current_state == '0') ? 1 : 0);
    shell_exec('/usr/local/bin/gpio -g write 14 '.$new_state);
}