Controlling an Arduino with PHP

Since PHP is my language of choice, it wasn’t long before I wanted to use it to control my Arduino.

This turned out to be easier said than done – under Windows anyway, with a lot of vague (mis)information out there. Not to mention a lot of “RTFM” advice.

The way I ended up doing is still a little too hacky for me to be happy with – PHP is clearly the wrong tool for the job here.

The Problem

PHP has trouble communicating with serial ports – a class is available to handle serial communication for you, but under Windows is write only.

I installed RealTerm, which has a feature to echo a serial port to a TCP/IP port, which PHP has no problem dealing with. Essensially, RealTerm will relay things back and forth between my PHP script and the Arduino.

This worked great, but seems like an unnecessary layer, just for the sake of using PHP.

To test this, I made a simple circuit with two LEDs and a servo, and wrote a quick AJAXy page to control the script, which would send commands to the arduino.

s90 would turn the servo to 90 degrees

g15 would turn the green LED to 15

r0 would turn the red LED off

I made a quick video to show the result

And to show the data being relayed through RealTerm…

EDIT: Forgot to add, this also solves the problem of the Arduino resetting itself every time a serial connection is opened, because RealTerm opens one serial connection and keeps it open, regardless of the actual connections my PHP script makes.

5 comments / Add your comment below

  1. Actually, I don’t see a problem in having the intermediate layer here; with this, it would be possible to have the web interface hosted on a different server (e.g. web host) to the Arduino.

    With that said, unless you leave your PC on 24/7, the ethernet shield would probably be a better option.

  2. Good point re: extra layer.

    Ethernet shield definitely a better solution if you wanted to build something more permanent, though controlling via the serial port could have uses – if you wanted to use, say, a webcam, which wouldn’t work with just the arduino anyway.

  3. Can i see the php script for connecting the device?

    Can I use the serial RFID Reader to read the rfid ID into a textbox?

Leave a Reply to Cyberspice Cancel reply

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