PHP and the Arduino – Follow-up
I’ve had a bit of interest on the original entry, asking for more detail on the code used in the video demonstation at the end.
Download the relevent files here: arduinophp.zip
The zip file contains three files: index.php, serial.php and arduino_serial.pde. Two more files are required: the jQuery JavaScript library, and the PHP Serial class.
The code isn’t exactly elegant. It was just something I was playing around with, so there is probably scope for a lot of improvement. I’m not always great at explaining things like this, but I’ll give it a crack:
index.php
This doesn’t actually need to be a PHP file, since it only contains HTML and JavaScript. It’s just force of habit that caused me to save it as .php instead of .html.
This is the file I navigated to on my iPod touch. It consists of a HTML form containing two option boxes; one to select the LED and another to select the brightness. The value attributes on the options contains the actual data that’s sent to the Arduino.
An onClick event is added to the submit button that triggers the AJAXness, which is done using jQuery’s getJSON function. It calls serial.php with the values from the option boxes as GET variables. It also displays the returned values from serial.php on the page.
serial.php
This file does the actual communication with the Arduino. If first checks that the necessary GET variables are set, then does a bit of input sanitising and then constructs a packet to send via the serial port to the Arduino. The packet is three bytes:
- The first byte is an @ symbol, which denotes the start of the packet to the Arduino.
- The second byte is the index (0, 1, 2) of the LED to adjust, encoded to ASCII using PHP’s chr function.
- The third byte is the desired brightness (0 – 255), similarly encoded using chr.
This is then sent, and the response from the Arduino is echoed.
arduino_serial.pde
This is the code loaded onto the Arduino itself. The most important part of it is the nest of ifs that check for and interpret the data packet sent by serial.php:
if (Serial.available() > 2) { // if there are at least 3 bytes in the serial buffer int p,i; incomingByte = Serial.read(); // read first byte if(incomingByte == 64){ // check if it is packet start (@ = 64 in ASCII) p = Serial.read(); // read second byte if(p >= 0 && p < numPins){ // check it is within a valid range i = Serial.read(); // read the third byte if(i >=0 && i <=255){ // check it is within a valid range set(p,i); // set LED p to brightness i printVals(); // respond with status } } } }
That’s basically it. Hopfully that makes sense…