Reading and writing to / from a serial device via USB on Linux using Perl or PHP

I have a problem reading from a serial device on Linux. The problem is rather strange, and I could not cover up the reasons.

I open the file / dev / ttyUSB 0 with PHP and start communicating with the device according to the device protocol. Many times I came across a situation where a PHP script is waiting for a device response. When I ran a Perl script in parallel, which was supposed to do the same thing, it sent a request to the same device and, presumably, left unanswered, but then saw that the PHP script received a response (only after the Perl script sent the request).

I came across a similar question when trying to read Arduino with PHP, PHP did not receive a response from the port, but the Arduino IDE Serial Monitor printed it.

I think I am missing important information about Linux files and USB ports here. What could be the problem? How can I determine which programs use a port / file?

    $usb = 'ttyUSB0';        
    `stty -F /dev/$usb 9600`;
    `stty -F /dev/$usb -parity`;
    `stty -F /dev/$usb cs8`;
    `stty -F /dev/$usb -cstopb`;
    $f = fopen("/dev/$usb", "r+");
    if(!$f) {
        echo "error opening file\n";
        exit;
    }

    statusRequest($f);
    sleep(1);
    $c = readPort($f);
    echo "$c\n";

function statusRequest($port) {
    $data = "request";
    fwrite($port, $data);
    fflush($port);
}

function readPort($port) {
    $read = 1;
    $c = '';
    while($read > 0) {
        $bytesr = unpack("h*", fread($port, 1));
        $c .= $bytesr[1];
        //echo $bytesr[1];
        if($bytesr[1] == 'ff') {
            $read = 0;
        }
    }    
    return $c;
}
+3
source share
1 answer

Check out these two articles on my wiki. The first article describes how to set useful permissions for the node device, the second article is an example that displays all the data that the remote sends to the PC. Although written for Arduino, it is easy to port for other uses.

lsof, , :

lsof | grep /dev/ttyUSB0 cat_ttyUS 19182 jhendrix 3u CHR 188,0 0t0 14519955 /dev/ttyUSB0

stty .

+1

Source: https://habr.com/ru/post/1792463/


All Articles