Using JSSerial to send sensor data to a server running a PHP script via AJAX

One thing that we are missing in JSSerial is an easy way to save sensor data. This example leverages AJAX to send any serial data to a PHP script running on a webserver that simply logs this data.

Additionally, that saved data is pulled up from the server to drive the display of the page so it shows an example of how you can use data coming in via AJAX to drive serial.

Arduino Code

int incomingByte = 0;	// for incoming serial data

void setup()
{
	Serial.begin(9600); 
}

void loop()
{
	// Only continue of data is available
	// Works in a call/response manner
	if (Serial.available() > 0)
	{
	   int r = analogRead(0); // Giving 0 to 1024 with my pot
	   int w = r/8; // Want 0 to 127
	   Serial.write(w);  
	}
}

JSSerial and AJAX JavaScript

View the source of this page to see the JavaScript.

The main thing is that when you call serialread ith reads from the serial port. If it gets data, it makes an AJAX call.

The return of this AJAX call tells the script to update the value on the page and additionally sends data back to the Arduino via a JSSerial write method. Additionally when this happens it calls serialread again.

PHP which receives data from AJAX and sends data back

This script simply echos data coming in back. Of course it could write it to a text file or what not.
<?
	$incoming = $_GET['data'];
	echo($incoming);
?>

In Operation

Serial Port List:
List Ports Output
Open Serial Port Number
Serial Read
Serial Read Output:
Serial Read Output