<html>
<head>
<title>PHP Testing: <?php echo phpversion(); ?></title>
<style type="text/css">
body {
font-family: Helvetica, Verdana, sans-serif;
font-size: 10pt;
width: 500px;
}
h1 {
font-size: 14pt;
}
.warning {
color: red;
}
</style>
</head>
<body>
<h1>Testing serial communication in PHP.</h1>
<p>
A simple serial port write test in a PHP form. The zone/level stuff is just
because the first serial device I found uses that format. In this example I
use /dev/ttyUSB0 as my serial port because I have a USB to RS-232 dongle on
a USB port since my laptop has no RS-232 ports.
</p>
<p class="warning">
Warning: This is pretty much guaranteed NOT to work in Windows.
</p>
<p class="warning">
Disclaimer: This is test code only. NEVER use code like this in production.
This code mixes logic and presentation and doesn't sanitize its inputs. It's
insecure and hard to maintain.
</p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Zone:
<select name="zone">
<?php
for ($i = 1; $i <= 16; $i++) {
$selected = ((@$_POST['zone'] == $i) ? ' selected="selected"' : '');
echo " <option value='$i'$selected>$i</option>\n";
}
?>
</select>
Level:
<select name="level">
<?php
for ($i = 0; $i <= 255; $i++) {
$selected = ((@$_POST['level'] == $i) ? ' selected="selected"' : '');
echo " <option value='$i'$selected>$i</option>\n";
}
?>
</select>
<input type="submit" value="Set level" />
</form>
<hr />
<pre>
<?php
/**
* The real work happens here.
*/
if (!empty($_POST['level'])) {
$port = '/dev/ttyUSB0';
// Set up for 9600 bps, 8-n-1, no flow control.
`stty -F $port`;
`stty -F $port 96`; // 9600 bps
`stty -F $port cs 8`; // character length 8
`stty -F $port -parenb`; // no parity
`stty -F $port -cstopb`; // no stop bit
`stty -F $port clocal -crtscts -ixon -ixoff`; // no flow control
$fp = fopen($port, 'w');
// The next line just encodes the form data as the hardware requires.
// This can easily be changed to support other command formats or textual
// communication.
$dsend = sprintf("%c%c%c%s\n", $_POST['zone'], $_POST['zone'], $_POST['zone'], $_POST['level']);
fwrite($fp, $dsend);
fclose($fp);
}
?>
</pre>
</body>
</html>