Step 3: Touching The Serial Port in PHP
Step 3: Touching The Serial Port in PHP
The core of this technique is the fopen() command. This is normally used for opening a document to
edit within the code (like if you wrote a script to make a text file with some information in it and save
it). Instead, we're going to exploit how linux views files and use it on a port. Install Arduino from the
Ubuntu Software Manager. Plug in your Arduino and open the arduino window. You should see the
device name under the ports menu. It will probably be /dev/ttyUSB0 or something similar. Here's some
example code that will open that port as a file and write the numbers 1 to 6 based on what button is
pressed:
<?php
$verz="1.0";
$comPort = "/dev/ttyUSB0"; /*change to correct com port */
if (isset($_POST["rcmd"])) {
$rcmd = $_POST["rcmd"];
switch ($rcmd) {
case Stop:
$fp =fopen($comPort, "w");
fwrite($fp, 1); /* this is the number that it will write */
fclose($fp);
break;
case Slow:
$fp =fopen($comPort, "w");
fwrite($fp, 2); /* this is the number that it will write */
fclose($fp);
break;
case Medium:
$fp =fopen($comPort, "w");
fwrite($fp, 3); /* this is the number that it will write */
fclose($fp);
break;
case Fast:
$fp =fopen($comPort, "w");
fwrite($fp, 4); /* this is the number that it will write */
fclose($fp);
break;
case Right:
$fp =fopen($comPort, "w");
fwrite($fp, 5); /* this is the number that it will write */
fclose($fp);
break;
case Left:
$fp =fopen($comPort, "w");
fwrite($fp, 6); /* this is the number that it will write */
fclose($fp);
break;
default:
die('Crap, something went wrong. The page just puked.');
}
}
?>
<html>
<body>
<center><h1>Arduino from PHP Example</h1><b>Version <?php echo $verz; ?></b></center>
<form method="post" action="<?php echo $PHP_SELF;?>">
    
<input type="submit" value="Left" name="rcmd">
          
<input type="submit" value="Right" name="rcmd"><br/>
<br />
               
<input type="submit" value="Stop" name="rcmd"><br/>
<br />
   
<input type="submit" value="Slow" name="rcmd">
<input type="submit" value="Medium" name="rcmd">
<input type="submit" value="Fast" name="rcmd">
<br />
<br />
<br />
<br />
<br />
<br />
</form>
</body>
</html>