PHP - 直接I/O dio_tcsetattr() 函式



PHP 直接I/O dio_tcsetattr() 函式用於設定終端屬性。如果您想控制序列通訊終端的設定,這非常有用。

語法

以下是 PHP 直接I/O dio_tcsetattr() 函式的語法:

bool dio_tcsetattr ( resource $fd, array $options )

引數

以下是 dio_tcsetattr() 函式的引數:

  • $fd: 它是由 dio_open() 返回的,表示檔案描述符。

  • $options: 它是一個關聯陣列,指定終端選項。

常見的 $options 包括:

  • baud (整數): 波特率(例如,9600、115200)。
  • bits (整數): 資料位(例如,8)。
  • stop (整數): 停止位(例如,1)。
  • parity (整數): 奇偶校驗(例如,0 表示無奇偶校驗,1 表示奇校驗,2 表示偶校驗)。

返回值

dio_tcsetattr() 函式在成功時返回 TRUE,失敗時返回 FALSE。

PHP 版本

dio_tcsetattr() 函式首次在 PHP 4.3.0 的核心版本中引入,並在 PHP 5.1.0 中繼續正常工作。

示例 1

此示例演示瞭如何使用 PHP 直接I/O dio_tcsetattr() 函式設定基本的終端特性,例如波特率和資料位。

<?php
   // Open serial port
   $fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);
   
   // Set terminal attributes
   $options = array(
       'baud' => 9600,
       'bits' => 8,
       'stop' => 1,
       'parity' => 0
   );
   
   if (dio_tcsetattr($fd, $options)) {
       echo "Baud rate set to 9600 successfully.";
   } else {
       echo "Failed to set baud rate.";
   }
   
   dio_close($fd);
?>

輸出

以上程式碼將產生類似以下的結果:

Baud rate set to 9600 successfully.

示例 2

在下面的 PHP 程式碼中,我們將嘗試使用 dio_tcsetattr() 函式並設定更高的波特率 115200。

<?php
   // Open serial port
   $fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);
   
   // Set terminal attributes
   $options = array(
       'baud' => 115200,
       'bits' => 8,
       'stop' => 2,
       'parity' => 1 // Odd parity
   );
   
   if (dio_tcsetattr($fd, $options)) {
       echo "Baud rate set to 115200 with odd parity and 2 stop bits successfully.";
   } else {
       echo "Failed to set terminal attributes.";
   }
   
   dio_close($fd);
?> 

輸出

執行以上程式後,將生成以下輸出:

Baud rate set to 115200 with odd parity and 2 stop bits successfully.

示例 3

此示例演示瞭如何使用 dio_tcsetattr() 函式設定終端以使用偶校驗來檢查錯誤。

<?php
   // Open serial port
   $fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);
   
   // Set terminal attributes
   $options = array(
       'baud' => 19200,
       'bits' => 7,
       'stop' => 1,
       'parity' => 2 // Even parity
   );
   
   if (dio_tcsetattr($fd, $options)) {
       echo "Baud rate set to 19200 with even parity successfully.";
   } else {
       echo "Failed to set terminal attributes.";
   }
   
   dio_close($fd);
?> 

輸出

這將建立以下輸出:

Baud rate set to 19200 with even parity successfully.

示例 4

在以下示例中,我們使用 dio_tcsetattr() 函式設定 230400 的高波特率。

<?php
   // Open serial port
   $fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);
   
   // Set terminal attributes
   $options = array(
       'baud' => 230400,
       'bits' => 8,
       'stop' => 1,
       'parity' => 0 // No parity
   );
   
   if (dio_tcsetattr($fd, $options)) {
       echo "Baud rate set to 230400 successfully.";
   } else {
       echo "Failed to set baud rate.";
   }   
   dio_close($fd);
?> 

輸出

執行以上程式時,將生成以下輸出:

Baud rate set to 230400 successfully.
php_function_reference.htm
廣告