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];
if($bytesr[1] == 'ff') {
$read = 0;
}
}
return $c;
}
source
share