Interfacing PHP with the Arduino (with a splash OS X)

A while ago I bought an Arduino Diecimila, which is an open-source electronics prototyping platform. It’s a very easy to use programmable micro-controller with a bevy of digital and analogue inputs and outputs. It is programmed via USB using the cross-platform Arduino software. The language is C-like with plenty of documentation available online. The Arduino appears to the OS as a serial device which makes two-way communication very easy indeed.

Whilst I really haven’t got a clue what I might use it for, I thought it would be cool if I could create a simple web-based system to control hardware attached to the Arduino. My server-side language of choice is PHP, so I looked for a way to allow it to send and receive data from a serial port. I didn’t have to look very far before I found the PHP Serial class, which looked just the ticket. Unfortunately whilst it caters for Windows and Linux, it doesn’t work under OS X. Fortunately it was just a matter of adding a few more else if‘s to allow for the slight differences in the way stty works in OS X.

I thought it would all be plain sailing from here, but this was not the case. The Diecimila resets whenever a serial connection is opened, so it can be ready to receive a new program. However this can be a problem; suppose I open a serial connection to the Arduino and tell it to light up an LED at 50% brightness. Then later I decide I want it at 100% brightness, so I open up a serial connection again, at which point the Arduino resets and the LED goes out. Not very desirable, and positively useless if the Arduino has been collecting data that you wanted to retrieve.

After some Googling it became apparent that I wasn’t the only one with this issue. Most suggestions were to either remove a tiny SMT capacitor from the board to permanently disable the auto-reset function, or to suppress the behaviour by disabling DTR (in Windows) or HUPCL (in *nix). That sounded better, so I tried it out. The commands required were:

nhup sleep 999 < /dev/cu.usbserial-A7004WqM &
stty -f /dev/cu.usbserial-A7004WqM -hupcl

Now, I’m no command-line/serial expert, so I only have the slightest understanding about what goes on when those two commands are run. What I do know is that it solves the problem so long as the sleep process is still running. It’s hardly an ideal solution (in my opinion). I suspect this might be a problem unique to OS X, as it seemed to work much better when I tried it in Debian.

Then! I found a forum post lurking at the bottom of a thread on the Arduino Forum. It suggests putting a 110 ohm resistor between the 5V and Reset pins, or a 47 ohm between the 3.3V and Reset pins. I had a 47 ohm resistor handy so I whacking it in there and lo! No more automatic resets. Brilliant. The post does go on to say that using the reset button with the 47 ohm resistor is place may be risky, so I’ll have to try and remember to remove it if I ever need to press it.

So now the PHP to Arduino link is useable. Here’s an example of some PHP code to send a character to the Arduino:

    //Include the PHP Serial class
    include "php_serial.class.php";
    //Define the serial port to use (in Windows something like 'COM1')
    //The character to send
    $c = 0;
    $serial = new phpSerial; 

… and an example of the Arduino code to interpret this and do something:

int incomingByte = 0;
void setup()
    Serial.begin(9600); //Start serial connection, 9600 baud
void loop()
    if(Serial.available() > 0){
        incomingByte =;
        if(incomingByte = 0){
            analogWrite(9, 128); //Pin 9 to 50% if 0 received
        else if(incomingByte = 1){
            analogWrite(9, 255); //Pin 9 to 100% if 1 received

This works brilliantly. With only slightly more complex code (thanks to a post on Principia Labs for a great explanation on effective serial commands), and a bit of AJAXy goodness, I have something like this:

Now all I have to do if think of a use for it…

This entry was posted in Hardware and tagged , , . Bookmark the permalink.

25 Responses to Interfacing PHP with the Arduino (with a splash OS X)

  1. Pingback: PHP with the Arduino and OS X |

  2. Brian says:

    Cool project, and thanks for the shout out!

  3. Frank says:

    I’m trying to give command to disable DTR (autoreset is based on this signal):

    “stty -F /dev/ttyUSB0 -hupcl”

    directly throygh phpSerial without any hardware mod

    But I still haven’t any success…any help/hint?


    • Tinlad says:


      Before using the resistor to suppress the auto-reset, I did have some success with this PHP:

      $h = popen('nohup sleep 5 < /dev/ttyUSB0 &', 'r')
      exec('stty -F /dev/ttyUSB0 -hupcl')

      (WordPress is going mad when I try and post PHP in comments, so I’ve had to leave the semi-colons off the ends of the lines)

      As I said in the post, the sleep line may only be required on OS X, so the first two lines may be superfluous if you’re on a different OS. The usleep() was required to create a delay between the stty command being executed and the script trying to open the serial port – without it it didn’t work. It’s a bit nasty and hacky, and there may be a more elegant way of doing it, but it’s the best I could do.

      I haven’t got my Arduino hooked up at the moment, so unfortunately I can’t do any more testing, but I hope that’s been of some help to you.


  4. Adumas says:

    Hi… I hope you can help.

    I have tried several times to get the php serial class to work under windows. At best I get an HTTP 500 error…

    I have tried communication with Remy but to no avail.  

    Can you help?

    here is my php code:

    echo (‘hello’);
    include “../php/php_serial.class.php”;
        //Define the serial port to use (in Windows something like ‘COM1′)
        $serial = new phpSerial;
    echo (‘goodby’);

    here is my arduino code:
      Analog sensor reader
      Language: Arduino/Wiring
      read data from the serial and turn On or OFF
      a light depending on the value
    // data received from the serial port
    // set the pin to digital i/o 4
    char val;
    int ledPin = 4;
    void setup() {
      pinMode(ledPin, OUTPUT);     // set pin as output
      Serial.begin(9600);          // start serial communication at
                                   // 9600 baud
    void loop() {
      if (Serial.available()){      // if data is available to read,
        val =;        // read it and store it in val
      if (val == ‘H’) {              // if H was received
        digitalWrite(ledPin, HIGH);  // turn the LED on
      } else {
        digitalWrite(ledPin, LOW);   // Otherwise turn it OFF
      delay(100);                    // Wait 100 milliseconds for
                                     // the next reading

    • Tinlad says:


      I can’t see anything wrong with the code you’ve posted. Does PHP ever give you any error messages, or is it always a HTTP 500 code? Check if display_errors is enabled in your php.ini; if it’s not, switch it on so that PHP can give you error information.

      I don’t know if you’ll face the same auto-reset problem under Windows as I did in OS X, but you may also want to look into how to disable DTR on the serial port (the Windows equivalent of HUPCL I mentioned in the post), or try the resistor trick.

      I don’t suppose that I’ve been much help, but good luck finding the problem. If you have any more information I’ll gladly try and help.


  5. SonyaSunny says:

    Hi there,
    Not sure that this is true:), but thanks for a post.

    Thank you

  6. Jeff says:

    Is there any chance of you sharing some of your ajaxy goodness? I’m assuming that you controlled the led brightness with the PWM or did you did it with the amperage off the 3.3 v plugs?

    • Tinlad says:

      Hi Jeff,

      I used the PWM outputs to control the LED brightness. I’ve put the two main files for my implementation in this ZIP file: I used the jQuery JavaScript library for the actual AJAXy part, along with the PHP Serial class as outlined in the main post – you’ll need to download those separately.

      It’s not the most elegant code in the world – it was just a proof of concept for me – but I’ve added some comments so it’ll hopefully make sense to you.

      Hope that helps.


  7. Jeff says:

    That file was really useful for me in seeing how to send commands through arduino but since this is my first time using one I was wondering if you wanted to give me any pointers on what to do for the specific arduino code. I looked at the stuff on this page here and it only has two settings for 50% and 100% and I’m not sure what bytes the php page is outputting so I don’t know what else to add to the loop on that page.

    • Tinlad says:

      Hi Jeff,

      I’ve emailed you with the Arduino code I used. I realise now that the PHP file I put up for download in my previous comment might not have been terribly useful without the Arduino code that interprets what it sends.


      EDIT: I’ve added a follow-up post.

  8. Pingback: » PHP and the Arduino - Followup

  9. Gwinyai says:

    I have tried to use the php code in windows and it tells me that the reading of the serial port has not been implemented in windows, is it because windows xp does not allows direct access of the serial port.

    • Tinlad says:

      To be honest, I don’t know. I haven’t tried this under Windows. I suspect it is possible, but that it’s just the PHP Serial class hasn’t implemented it (or implemented it correctly).

  10. Jim W. says:

    Tinlad, can you post your revised php_serial code with the changes for this to work under OS X?  I’m just starting a project and would rather not reinvent the wheel.

  11. Pingback: More Arduino + LCD + PHP fun « Arduinian Tales

  12. Amy says:

    hi .
    im using arduino and online database. but i have problem on how to connect the db with arduino.i dont have idea how to pull data from online db to display at LCD via my arduino.

  13. Pingback: PHP, Arduino and MacOS | PHP Luxembourg

  14. Pingback: functiodomo blog

  15. Sherluck says:

    Hi, can i ask something. Could it be possible to interface an arduino to a database? Cause I will use my database as n external storage of sort of information and then this database will transmit an specific data to the arduino with its another interfaced gsm modem to send plain text message to a sender. In other words an arduino is connected with a database and a gsm modem. Please reply.. I really need help to do my project….

  16. Pingback: Comunicación con Arduino a través de un servidor PHP. – Functiodomo. Domótica para su hogar

  17. RardliaxBrirl says:


    Thanks for this…

  18. Pingback: Controlling Arduino Board With PHP Web-Based Script - Tutorials - Into Robotics

  19. Ezu says:

    very good tutorials that help me to find what I need to build a web based application and control sensors from internet

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current day month ye@r *