PHP serial port data return from Arduino

PHP serial port data return from Arduino

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Reading Serial Feedback from Arduino in PHP

You have successfully established a bidirectional communication channel between your web interface and an Arduino microcontroller, but you are currently stuck on one side: the response. You can send commands like r9 or g0b0 to toggle LEDs, but the feedback loop—the data the Arduino prints to its serial buffer—remains silent in your PHP script.

The core of the issue lies in how the phpSerial library handles data retrieval and how the Arduino code buffers its output. When you call $serial->readPort(), you are invoking a non-blocking read or attempting to grab available bytes without guaranteeing that the entire response string is ready. If your PHP script executes faster than the Arduino, or if the Arduino prints multiple lines before you read them, readPort() might return an empty string or only partial data.

The Timing Mismatch

The most immediate hurdle is the race condition between your web request and the serial buffer. When you send a command via exec("echo 'r9' > /dev/ttyACM0"), the Arduino receives the character immediately. However, the Arduino's Serial.print() calls happen inside a loop that checks for incoming data. If you process the PHP response on every page load without waiting, the Arduino might not have finished transmitting its status message yet.

To fix this, you need to ensure your PHP script waits until data is actually available before attempting to read it. The phpSerial class provides methods to check buffer status, but relying solely on a single readPort() call is fragile for interactive applications. Instead, you should poll the device or use a blocking read approach depending on your specific version of the library.

Handling Multi-Line Responses

Your Arduino sketch prints two lines of feedback:

Serial.print("Current Pin : ");
Serial.println(currentPin);
Serial.print("Brightness : ");
Serial.println(brightness);

If you send a command and immediately read, you might only capture the first line. Since readPort() typically reads until a newline character or an empty string is encountered (depending on configuration), you need to verify how many bytes are actually in the buffer before reading.

A robust approach involves checking the available byte count first. If the library exposes a method like available(), use it to determine if enough data has arrived. If the response is split across multiple reads, you must concatenate the results into a single string variable before processing or displaying it. This prevents your HTML output from appearing fragmented or incomplete.

Streamlining the PHP Implementation

In your current code, you are mixing shell commands (exec) with object-oriented calls to phpSerial. While using exec works for simple writes, it bypasses the library's internal state management and configuration (like baud rates). It is cleaner and safer to handle all serial interactions through the $serial object instance.

Here is a pattern that ensures you capture the full response:

<?php
require("php_serial.class.php");

$serial = new phpSerial();
$serial->deviceSet("/dev/ttyACM0");
$serial->confBaudRate(9600);
$serial->confParity("none");
$serial->confCharacterLength(8);
$serial->confStopBits(1);
$serial->confFlowControl("none");

if ($serial->deviceOpen()) {
    // Send command
    $serial->writePort("r9\n"); 
    
    // Wait a brief moment to ensure Arduino has processed and printed data.
    // You can sleep for 50ms or poll until available() > 0 based on library version.
    usleep(50000); 

    // Read all available data
    $response = $serial->readPort();

    echo "<pre>";
    print_r($response);
    echo "</pre>";

    if ($serial->deviceClose()) {
        echo "Device closed successfully.";
    }
} else {
    echo "Failed to open device.";
}
?>

Dealing with Buffer Flushing

Sometimes the Arduino prints data, but it sits in the UART buffer waiting for the next transmission or until a timeout occurs. If your PHP script reads too quickly after writing, it might get an empty string. The solution is often simply introducing a small delay (usleep or sleep) between writing and reading. This gives the Arduino's internal loop time to execute its Serial.print() statements before the next read attempt blocks on an empty buffer.

Additionally, ensure that your PHP script does not terminate immediately after sending data. The readPort() function requires the connection to remain open; closing the device via $serial->deviceClose() terminates the stream, which will result in an empty read string for subsequent calls within the same request lifecycle if not handled carefully.

By synchronizing the write and read operations and respecting the timing required by the microcontroller, you can successfully retrieve the feedback messages your Arduino sends back to the web interface.

Our network