Read & Write to COM Port using PHP

PHP code : 

Below code is used to send data from strng to hx value to a com port & fetch the data from the com port.

file: send2com.php

<?php
if (!$_POST["inputvalue"])
        {
        die("You need to provide some message to sent.");
        }
else {
$value = $_POST["inputvalue"];
//echo "Value : ". $value;
 $device = "COM4";
 exec("mode $device BAUD=9600 PARITY=n DATA=8 STOP=1 xon=off octs=off rts=on");
 $comport = fopen($device, "w");
 if ($comport === false){
 die("Failed opening com port<br/>");
 }else{
 //echo "Com Port Open<br/>";
 }
 $valuee = strToHex($value);

 $valueee = $valuee."\r";
 fputs($comport, $valueee);
 fclose($comport);
 echo "Sent";
 Header("Location: comport.php", true, 302);
}


function strToHex($string){
    $hex='';
    for ($i=0; $i < strlen($string); $i++){
        $hex .= dechex(ord($string[$i]));
    }
    return $hex;
}


function hexToStr($hex){
    $string='';
    for ($i=0; $i < strlen($hex)-1; $i+=2){
        $string .= chr(hexdec($hex[$i].$hex[$i+1]));
    }
    return $string;
}
?>

file : comport2.php

<html>
<head>
<title>Com Port Access
</title>
</head>
<body><center>
<form id="comsend" action="send2com.php" method="post">
<table border="5" cellspacing="3">
<tr>
<td align="center"><b>Com Port Interface</b>
</tr>
<tr>
<td>
<textarea id="inputvalue" name="inputvalue" rows="25" cols="50">
<?php
$device = "COM4";
 exec("mode $device BAUD=9600 PARITY=n DATA=8 STOP=1 xon=off octs=off rts=on");
 $comport = fopen($device, "r+w");
 if ($comport === false){
 die("Failed opening com port<br/>");
 }else{
 //echo "connected";
  while (!feof($comport)) { 
sleep(3);
  echo fgets($comport); 
sleep(3);
// $value = hexToStr($val);
// echo $value;

}
}
 fclose($comport);
 ?>
</textarea>
</tr>
<tr>
<td align="center">
<input type="submit" value="Send" onclick="send2com();" style="width:300px; height:50px;">
</form>
</tr>
<tr>
<td align="center">
<form id="form2" action="comport2.php" method="get">
<input type="submit" value="Fetch" style="width:300px; height:50px;">
</form>
</tr>
</table>
</body>
</html>

Comments

piyush said…
sir is it really working...
Ritika said…
thank you sir its really very helpful... sir i wanna ask how can i store data coming on COM port in database (mysql). my data on COM port is something like this
3F009256758E AT 02:45:17 ON 17:02:16. Thanks for help.
Praneeth Damera said…
hi,

you have said u want to store in Database, this is not so complicated just use JDBC.

for this make a table in mysql with the required fields

with data as one column and date and time of arrival as another two columns.

when ever data is received add it to string and send it for parsing and parse it into 3 parts data, date and time

now send these three values to mysql by making query.

if you are seeing for code i will not make it for you.

do it for yourself.

sorry for my late reply, as im not using my blog regularly.