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.

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

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




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.

$serial = new phpSerial();
$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->sendMessage("string to send");

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 82943 times Last modified on Sunday, 12 June 2016 10:33
More in this category: HTML Onclick Button Image »


  • Comment Link Smuncag Saturday, 12 October 2019 06:19 posted by Smuncag

    Наша фирма реализует малому и крупному бизнесу, а также частным лицам комплексное решение проблем - начиная от регистрации и закрытия фирмы до адвокатской помощи на всех стадиях её формирования. Наши сотрудники уважают любого потребителя, обратившегося к нам.

    Особенностью представленной работы является построение долговременных отношений со всеми нашими клиентами, основанных на принципах индивидуального подхода к всякому клиенту и сохранение секретности информационных материалов.

    Наши работники владеют высшим юридическим и финансовым образованием, хорошим практическим опытом в области предоставляемых нашими специалистами услуг. Главным положением в нашей команде несомненно считается то, что, работая с нынешней компанией, вы получите объективный итог, основанный на наших сведениях и более чем 5 летнем опыте. ликвидация предприятия
    Мы специализируемся на процедуре регистрации и закрытия юридических лиц и частных предпринимателей, бухгалтерских услугах для любого бизнеса, комплексном юридическом сопровождении юридических граждан. Дополнительно осуществляем провождение сделок,регистрация прав на нежилые помещения,заявление об отмене судебного приказа,отмена заочных решений,налоговое консультирование,получение налоговых вычетов и льгот,исковое заявление,сделка купли-продажи недвижимости,регистрация прав на интеллектуальную собственность,оспаривание отцовства,споры о детях,трудовые споры в Самаре.

  • Comment Link admin Thursday, 15 June 2017 13:15 posted by admin

    Seems like the baud does not match

  • Comment Link Edward Eborgu Monday, 12 June 2017 17:49 posted by Edward Eborgu

    I wrote my code this way to send price to a display pole

    function sendTodisplayPole($com, $baud, $msg)

    $com= "COM1";
    exec("mode $com: BAUD=9600 PARITY=n DATA=8 STOP=1 xon=off");
    $fp=fopen($com, 'w');
    fwrite($fp, "total:78578");


    it worked but the display pole was showing unrecognized characters please help to know how to let this show the exact character im sending to the display pole

  • Comment Link Edward Eborgu Monday, 12 June 2017 17:46 posted by Edward Eborgu

    Hello i wrote my code this was

    function sendTodisplayPole($com, $baud, $msg)

    $com= "COM1";
    exec("mode $com: BAUD=9600 PARITY=n DATA=8 STOP=1 xon=off");
    $fp=fopen($com, 'w');
    fwrite($fp, "total:78578");


  • Comment Link Johnny Churne Tuesday, 07 February 2017 20:40 posted by Johnny Churne

    Thanks for a great article. I want to ask it is possible to send byte as hex from php to serial port?

  • Comment Link admin Tuesday, 07 June 2016 15:54 posted by admin

    Can you describe in more detail?

  • Comment Link Mehedi Hasan Polin Tuesday, 07 June 2016 15:03 posted by Mehedi Hasan Polin

    Hi i am from bangladesh. i try to develop bridge scale software with Apache/php

    i want to read data from com1 port to pc. please help

  • Comment Link admin Friday, 22 January 2016 18:47 posted by admin

    Have you tried on other computer?
    I'm using WAMP & EasyPHP without any problem.

  • Comment Link Elza Friday, 22 January 2016 03:38 posted by Elza

    Hello, I want to read data from Arduino, windows 7, 32 bit, Port COM4. I have the following code:
    PHP Code

    And I have the problem: fopen(COM4): failed to open stream: Permission denied in C:\xampp\htdocs\project\index.php on line 3

    Does anyone knows what's the solution?

    Thanks in advance..

  • Comment Link Admin Wednesday, 15 May 2013 19:56 posted by Admin

    Please refer this article in order to read & write to serial port

  • Comment Link smching Wednesday, 15 May 2013 19:47 posted by smching

    You can check your com port from device manager too.
    Sometime you have to send string terminate with new line or carriage return depend on your Arduino sketch.

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

  • Comment Link chethan Saturday, 11 May 2013 23:46 posted by chethan

    i tried the program along with arduino .
    the problem that i am facing is that , after the php code is made to run in wamp ,a new file by the name com20( i have connected the arduino to com20)is being created in the wamp server directory and is nothing is being transmitted to board .
    can anyone please help me .

  • Comment Link Subhendu Saturday, 11 May 2013 10:54 posted by Subhendu

    I can write on the serial port using fwrite($fp,"0");
    Can you please provide me with a simple example on how to read from serial port.
    I am using Windows 7
    I want to display sensor data on my webpage.

  • Comment Link Subhendu Sinha Chaudhuri Friday, 10 May 2013 22:09 posted by Subhendu Sinha Chaudhuri

    I had my arduino attached in COM19 in my Windows 7 64bit. Using ur example I was trying to on the LED on pin 13. But nothing was happening. But the serial monitor of the arduino was showing the result on sending strings.
    In fact the c:\>mode com19:/status was telling COM19 is unavailable.
    Can u please help me
    I have also failed with php_serial.class in Windows after trying for 4 days.

  • Comment Link Admin Sunday, 21 April 2013 13:38 posted by Admin

    Any error message?

    What is the serial settings of your phone?

    Above examples only shows you how to sending messages to serial port, however your phone should running some kind of software to listen the serial port in order to process the incoming messages.

  • Comment Link okan Saturday, 20 April 2013 23:25 posted by okan

    i connect my cell phone(nokia 6300). i checked it is in com4. but in php i cannot connect com4 can you help me.

Leave a comment

Back to Top