Control Your Arduino With PHP Via C++…and Why Not JQuery!

For a couple of days now I have been looking for a PHP class that would help me send data to my Arduino board. So far the only class everybody points to is this one, but I haven’t been able to get it to work with Windows!

My Fix: PHP, JQuery and Visual C++

Instead of just using PHP I have decided to split the job between Visual C++ and PHP ( and I’ve added JQuery while we are at it. Visual C++ is a great framework witch which you can easily program serial port communication, all I have to do with PHP is send data to my C++ program.

What Our Program Will Do

I want to make a set of buttons and using HTML with which I can control my Arduino’s pin 13 light.

How The Program Will Work

I will have three files for this project, the HTML, PHP and C++ programs. My PHP and C++ will have the same name, but they don’t have to if you don’t want.

Whenever someone clicks on one of the buttons in my HTML page I will send a value, using JQuery, to my PHP script. The PHP script will send that value to my C++ program which will send it to my Arduino. The C++ program will send some data back to PHP and JQuery to display it in HTML.

I plugin my Arduino board at random USB ports, so I will also have a text field with which I can change ports, this way I won’t have to compile my C++ program every time I decide to plug in the board at a different port.

The values I will be sending are "on" if the user clicks and "off" if the user clicks , I will also be sending the port name which is in my text field.

My C++ will send the value "1" to the Arduino if the value sent to it was "on", it will send "0" if the value was "off"

My HTML Page: The User Interface

I will need two buttons, each with their respective values, a textfield and a div for my C++ response.

The HTML

		<p>
			<div id="response">
			</div>
		</p>
		<p>
			<label>PORT</label>
			<input type="text" id="com" size="5" />
		</p>
		<p>
			<button value="on">On</button><button value="off">Off</button>
		</p>

The JQuery

My JQuery is also very simple. If you don’t know what am doing here check out my JQuery tutorial on this subject.
JQuery AJAX Tutorial.

		<!-- include JQuery-->
		<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
		<!-- JQuery script-->
		<script type="text/javascript">
			$(document).ready(function(){
				var port;
				var value;
				$("button").click(function(){
					value=$(this).val();
					port=$("#com").val();
					$("#response").hide(1000);
					$.post('arduino.php',{message:value,port:port},function(response){
						$("#response").html(response).show(1000);
					});
				});
			});
		</script>

My PHP Script: The Messanger

Please call this file arduino.php as this is the name we gave it in JQuery.

// line jquery code
...$.post('arduino.php',{...

My C++ Arduino program will be called arduino.exe and the data I will be sending to its main function is the port name and message (either 0 or 1 ) in this order. The C++ response will be stored in the variable $output, as an array of each line and the status in the variable $returnStatus.

I use the status variable to debug my programs but it’s optional.

If you are unfamiliar with how C++’s main function can take parameters check out my tutorial on this subject.

How To Use C++ and PHP Together

PHP Code:

$message=$_POST['message'];
$port=$_POST['port'];


exec("arduino.exe {$port} {$message}",$output,$returnStatus);

foreach($output as $line)
{
 echo '<p>';
 echo $line;
 echo '</p>';
}
echo "Return Status: {$returnStatus}";

My C++ Code: The Interpreter

I will be using the serial port class. This class I very easy to use and I talked about it in detail in my previous post. I also show how to use Visual C++.
How To: Control Your Arduino With PHP
I think the code is self explanatory and well commented so here it is.

#include "stdafx.h"
using namespace System;
using namespace System::IO::Ports;

int main(array<System::String ^> ^args)
{
	Console::WriteLine("Visual C++ Program Output:");
	if(args->Length==2)
	{
		String^ message=args[1]; // get message ( 0 or 1 )
		String^ port=args[0]; // get port name
		
		
		// arduino settings
		SerialPort^ arduino;
		arduino = gcnew SerialPort(); // make arduino object
		arduino->PortName =port; // set port name
		arduino->BaudRate = 9600; // set baud rate
		arduino->ReadTimeout = 500; // set read time out
		arduino->WriteTimeout = 500; // set write time out
		// open port
		try
		{
			arduino->Open(); // open port
				//check that user typed one of the options
				if(String::Compare(message,"on")==0) // if sent value was "on"
					arduino->Write("1"); // send 1 to arduino
				else if(String::Compare(message,"off")==0)
					arduino->Write("0"); // send 0 to arduino
				else
					Console::WriteLine(message+" was not an option");
			// close port to arduino
			arduino->Close();
		}
		catch (IO::IOException^ e  ) 
		{ 
			Console::WriteLine(e->GetType()->Name+": Port is not ready");
			return 2;
		}
		catch (ArgumentException^ e)
		{
			Console::WriteLine(e->GetType()->Name+": incorrect port name syntax, must start with COM/com");
			return 3;
		}

	}
	else
	{
		Console::WriteLine("Error: arduino.exe needs at least two parameters.");
		return 1;
	}

    return 0;
}

My Arduino Code: The Receiver

My Arduino code is also very simple, notice that am comparing values received not as integers but as characters.

int ledPin = 13;
int state=0;
void setup() {
    pinMode(ledPin, OUTPUT);
    Serial.begin(9600);
}

void loop() {
  if (Serial.available() > 0)
  {
    state = Serial.read();
    switch(state)
    {
      case '1':
        digitalWrite(ledPin,HIGH);
      break;
      case '0':
        digitalWrite(ledPin,LOW);
      break;
      default:
      break; 
    }
  }
}

That’s it for this post, leave your questions or comments below.

blog comments powered by Disqus