Sunday, 29 July 2012 11:19

Control Serial via PHP

Written by
COM Port status COM Port status
It is simple to control serial via PHP.

<?php
exec("mode com4: BAUD=9600 PARITY=n DATA=8 STOP=1 to=off dtr=off rts=off");
$fp =fopen("com4", "w");
//$fp = fopen('/dev/ttyUSB0','r+'); //use this for Linux
fwrite($fp, "string to send"); //write string to serial
fclose($fp);
?>

 
The first function exec is similar to the DOS command, use to change the port settings.
You can run mode from Ms DOS command prompt. For example:
C:\> mode com4:/status
The above DOS command display the status of the COM port. 

Syntax of mode (display a list of mode commands & options)
C:\> mode/?

 

Open COM4 in write mode (for Microsoft Windows only)

$fp =fopen("com4", "w");

or your can use  $fp =fopen("com4", "r+"); for read & write

 

Open USB serial port for read and write (for Linux)

$fp =fopen('/dev/ttyUSB0',r+');

 

Open first serial port in read & write (for Linux)

$fp = fopen('/dev/ttyS0','r+');

 

To terminate string with Carriage Return

fwrite($fp, "string to send\r");

 

To terminate string with New Line & Carriage Return

fwrite($fp, "string to send\n\r");

 

 Close the serial port

 

fclose($fp);

 

Additional Information about PHP Serial
There are many people using php_serial.class. Unfortunately it is not working in my computer. Please let me know if some one can make the following code work.

<?php
require("php_serial.class.php");
$serial = new phpSerial();
$serial->deviceSet("COM4");
$serial->confBaudRate(9600); //Baud rate: 9600
$serial->confParity("none"); //Parity (this is the "N" in "8-N-1")
$serial->confCharacterLength(8); //Character length
$serial->confStopBits(1); //Stop bits (this is the "1" in "8-N-1")
$serial->confFlowControl("none");
$serial->deviceOpen();
$serial->sendMessage("string to send");
$serial->deviceClose();
?>

 
It is not important to me no matter the php_serial.class is working or not. I'm happy with the  $fp =fopen("com4", "w"); command since I do not need to include additional library file to my php source code.
Read 113461 times Last modified on Sunday, 12 June 2016 10:33
More in this category: HTML Onclick Button Image »
Back to Top