PHPでマイコンとのシリアル通信を行うクロスプラットフォームライブラリ。
PySerialやRuby serialportのような使い勝手を提供。 Windows、Mac、Linuxで動作し、Pure PHP実装。
- PHP 8.1以上
- Windows、Linux、macOS
Composerを使用してインストール:
composer require tomio2480/php-serial特定のバージョンを指定する場合:
composer require tomio2480/php-serial:^1.3<?php
require 'vendor/autoload.php';
use PhpSerial\Configuration;
use PhpSerial\SerialPort;
$config = new Configuration(
baudRate: 9600,
dataBits: 8,
parity: Configuration::PARITY_NONE,
stopBits: Configuration::STOP_BITS_1
);
$port = new SerialPort('/dev/ttyUSB0', $config);
$port->open();
// データ送信
$port->write("Hello, Arduino!\n");
// データ受信
$response = $port->readLine(timeout: 2000);
echo "Received: {$response}\n";
$port->close();対応: 110, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 115200, 230400
$config = new Configuration(baudRate: 115200);use PhpSerial\Configuration;
// パリティなし
$config = new Configuration(parity: Configuration::PARITY_NONE);
// 奇数パリティ
$config = new Configuration(parity: Configuration::PARITY_ODD);
// 偶数パリティ
$config = new Configuration(parity: Configuration::PARITY_EVEN);対応: 5, 6, 7, 8
$config = new Configuration(dataBits: 8);use PhpSerial\Configuration;
$config = new Configuration(stopBits: Configuration::STOP_BITS_1);
// または
$config = new Configuration(stopBits: Configuration::STOP_BITS_2);$config = new Configuration();
$config
->setBaudRate(115200)
->setDataBits(8)
->setParity(Configuration::PARITY_NONE)
->setStopBits(Configuration::STOP_BITS_1);$port = new SerialPort('COM3');重要: Windows環境ではPHP FFI拡張の有効化を強く推奨します
正確で安定したシリアル通信を実現するため、php.iniでFFIを有効にしてください:
extension=ffi
ffi.enable=trueFFI無効時はフォールバック実装が使用されますが、データ受信が動作せず送信のみ可能となります。 詳細はdocs/WINDOWS_FFI_SETUP.mdを参照してください。
$port = new SerialPort('/dev/ttyUSB0');
// または
$port = new SerialPort('/dev/ttyACM0');$port = new SerialPort('/dev/tty.usbserial');環境変数でテスト用デバイスを指定:
# .env.exampleを.envにコピー
cp .env.example .env
# .envファイルでTEST_SERIAL_PORTを設定
# TEST_SERIAL_PORT=COM3
# テスト実行
composer test基本的な使用例はexamples/basic.phpを参照。 複数コマンド送信の例はexamples/advanced.phpを参照。
すべての品質チェックを一度に実行:
composer qa個別チェック:
composer cs:check # PSR-12準拠チェック
composer cs:fixer # コードスタイルチェック
composer stan # PHPStan静的解析 (レベル8)
composer test # テスト実行詳細はCONTRIBUTING.mdを参照してください。
MIT