Reading and writing to/from serial device via USB on Linux with perl or PHP

17,460

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

Using lsof you can find out which program is currently using the port:

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

With the stty commands you don't lock the port for exclusive use.

Share:
17,460
MeLight
Author by

MeLight

I code (surprise!) for living and for fun. The tools I [currently] enjoy: Python, Google App Engine, Git, BigQuery, memcached. I also do non-geek stuff, mostly boarding of all sorts (except for water-boarding, I'm not into that stuff). "If there's a saddle to it, I can ride it. If there's rhythm to it I can dance it." -Pepper Lewis "If there're variables to it, I can code it." -Me ;)

Updated on June 05, 2022

Comments

  • MeLight
    MeLight almost 2 years

    I'm having a problem reading from a serial device on Linux. The problem is rather weird, and I wasn't able to nail down the causes.

    I'm opening the /dev/ttyUSB0 file with PHP and beginning to communicate with the device according to the device's protocol. Many times I encountered a situation where the PHP script waits for the device to respond. When I ran a Perl script in parallel which supposed to do the same it sent a request to the same device, and quit supposedly without getting a response. Then I saw that the PHP script got the response (only after the Perl script sent a request).

    I encountered a similar matter when trying to read Arduino with PHP. The PHP got no response from the port, but Arduino IDE's Serial Monitor printed it.

    I think I'm missing a crucial thing about Linux files and USB ports here. What might be the problem? How can I tell which programs use the 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;
    }