note 112243 deleted from function.fopen by cmb
| From: | cmb@php.net | Date: | Sun, 09 Feb 2020 08:12:00 +0000 |
| Subject: | note 112243 deleted from function.fopen by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-214041@lists.php.net to get a copy of this message | ||
Note Submitter: simon dot riget at gamil dot com
----
Writing and reading on a serial port.
If you are unable or unwilling to install the serial device library for PHP, its still possible to
communicate through a serial port or USB device.
There are two issues to note:
- you must use a system call to set the port control options
- you must use NON blocking stream mode for reading (not for writing unless you use flow control)
<?php
// Set timeout to 500 ms
$timeout=microtime(true)+0.5;
// Set device controle options (See man page for stty)
exec("/bin/stty -F /dev/ttyS0 19200 sane raw cs8 hupcl cread clocal -echo -onlcr ");
// Open serial port
$fp=fopen("/dev/ttyS0","c+");
if(!$fp) die("Can't open device");
// Set blocking mode for writing
stream_set_blocking($fp,1);
fwrite($fp,"foo\n");
// Set non blocking mode for reading
stream_set_blocking($fp,0);
do{
// Try to read one character from the device
$c=fgetc($fp);
// Wait for data to arive
if($c === false){
usleep(50000);
continue;
}
$line.=$c;
}while($c!="\n" && microtime(true)<$timeout);
echo "Responce: $line";
?>