Using UART


Reading Data

Data received from UART is stored in receive buffer. pid_read function is required to read the data.

use uart 1

The following shows how to use the pid_read function.

pid_read($pid, $var[, $len]);

Argument $var is a variable for saving the read data and $len is size of read data.

example

This example checks and prints received data to UART every second.

<?php
$pid = pid_open("/mmap/uart0");                 // open UART 0
pid_ioctl($pid, "set baud 9600");               // baud rate: 9600bps
pid_ioctl($pid, "set parity 0");                // parity: none
pid_ioctl($pid, "set data 8");                  // data bit: 8
pid_ioctl($pid, "set stop 1");                  // stop bit: 1
$rxbuf = pid_ioctl($pid, "get rxbuf");          // get size of receive buffer
while(1)
{
    $rdata = "";
    $len_tot = pid_ioctl($pid, "get count rx"); // get total size of data received
    $rxlen = pid_ioctl($pid, "get rxlen");      // get size of data received 
    $rx_free = $rxbuf - $rxlen;                 // get remaining size
    echo "$rx_free / $rxbuf\r\n";               // print remaining size
    $len = pid_read($pid, $rdata, $rxlen);      // read data
    echo "len[total] = $len[$len_tot] / ";      // print size of read data
    echo "rdata = $rdata\r\n";                  // print read data
    sleep(1);
}
pid_close($pid);
?>

Sending Data

Data, written by pid_write function, is stored in send buffer and transferred to the outside via UART.

use uart 2

The following shows how to use pid_write function.

pid_write($pid, $var[, $wlen]);

Argument $var is a variable containing data to send and $wlen is a size of sending data.

example

This example prints the remaining size of send buffer and length of sent data every second.

<?php
$len_tot = 0;
$sdata = "0123456789";
$pid = pid_open("/mmap/uart0");                 // open UART 0
pid_ioctl($pid, "set baud 9600");               // baud rate: 9600bps
$txbuf = pid_ioctl($pid, "get txbuf");          // get size of send buffer
while(1)
{
    $len_tot = pid_ioctl($pid, "get count tx"); // get total size of transmitted data
    $txfree = pid_ioctl($pid, "get txfree");    // get remaining size
    echo "txfree = $txfree\r\n";                // print remaining size
    $len = pid_write($pid, $sdata, $txfree);    // write data
    echo "len[total] = $len[$len_tot]\r\n";     // print length of data sent
    sleep(1);
}
pid_close($pid);
?>

The third argument of pid_write function means the length of writing data. The length of writing data should be less than the remaining data size of send buffer to avoid data loss. It is highly recommended to check remaining size of send buffer before sending data.