PHP code example of sanchescom / php-serial

1. Go to this page and download the library: Download sanchescom/php-serial library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sanchescom / php-serial example snippets




declare(strict_types=1);

// Talk to a modem or an ESP8266 with AT firmware:
//   php examples/at-command.php /dev/ttyUSB0 115200

TimeoutException;

$device = $argv[1] ?? (new SerialPortLocator())->candidates()[0] ?? null;
if ($device === null) {
    fwrite(STDERR, "No serial device found\n");
    exit(1);
}

try {
    $port = new SerialPort($device, (int) ($argv[2] ?? 115200));
    $port->write("AT\r\n");

    try {
        do {
            $line = $port->readLine(timeout: 2.0);
            echo "< {$line}\n";
        } while ($line !== 'OK' && $line !== 'ERROR');
    } catch (TimeoutException) {
        echo "No answer within 2 s\n";
    }

    $port->close();
} catch (SerialException $e) {
    fwrite(STDERR, $e->getMessage() . "\n");
    exit(1);
}

use Sanchescom\Serial\{FlowControl, Parity, StopBits};

$port = new SerialPort(
    '/dev/ttyUSB0',
    baudRate: 9600,
    dataBits: 7,
    parity: Parity::Even,
    stopBits: StopBits::Two,
    flowControl: FlowControl::XonXoff,
);

$devices = (new SerialPortLocator())->candidates();

$ php examples/loopback.php /dev/serial0 115200
Opened /dev/serial0 at 115200
readLine: 'ping'
loopback OK: 'ping' went out on TX and came back on RX
timeout: No "\n" received within 0.500 s
readAvailable: ''
[exit 0]

$ php examples/at-command.php /dev/serial0 115200
< AT
No answer within 2 s
[exit 0]
bash
composer