PHP code example of php-io-extensions / uart

1. Go to this page and download the library: Download php-io-extensions/uart 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/ */

    

php-io-extensions / uart example snippets


use Fd\FD;
use Uart\UARTConfig;
use Uart\UARTUse;

$fd = FD::open('/dev/ttyUSB0', 2); // O_RDWR = 2
// configure, then read/write ...
FD::close($fd);

use Fd\FD;
use Uart\UARTConfig;
use Uart\UARTUse;

$fd = FD::open('/dev/ttyUSB0', 2); // O_RDWR

UARTConfig::setRaw($fd);
UARTConfig::setBaudRate($fd, 115200);
UARTConfig::setDataBits($fd, 8);
UARTConfig::setStopBits($fd, 1);
UARTConfig::setParity($fd, 0);       // none
UARTConfig::setFlowControl($fd, 0);  // none

UARTUse::write($fd, "AT\r\n", 4);
UARTUse::drain($fd);

$response = UARTUse::read($fd, 64);

FD::close($fd);

$fd = FD::open('/dev/ttyS0', 2);

UARTConfig::setRaw($fd);
UARTConfig::setBaudRate($fd, 115200);
UARTConfig::setFlowControl($fd, 1); // hardware

UARTUse::write($fd, $payload, strlen($payload));
UARTUse::drain($fd);

FD::close($fd);

$fd = FD::open('/dev/ttyUSB0', 2);

UARTConfig::setRaw($fd);
UARTConfig::setBaudRate($fd, 9600);

UARTUse::flush($fd, 2); // TCIOFLUSH — clear both queues before use

$attrs = UARTConfig::getAttributes($fd);
printf("cflag=0x%08x  ispeed=%d  ospeed=%d\n",
    $attrs['cflag'], $attrs['ispeed'], $attrs['ospeed']);

FD::close($fd);

$fd = FD::open('/dev/ttyS0', 2);

UARTUse::setBits($fd, 0x002);    // TIOCM_DTR — raise DTR
$bits = UARTUse::getModemBits($fd);
$cts = ($bits & 0x020) !== 0;    // TIOCM_CTS
echo $cts ? "CTS asserted\n" : "CTS not asserted\n";

UARTUse::clearBits($fd, 0x002);  // lower DTR
FD::close($fd);