Go Down

Topic: PHP >> SerialCom project using WAMP (locally) (now w/Flash front end) (Read 6797 times) previous topic - next topic

xl97

Figured I'd post what worked for me (so far)..

on getting PHP to communicate to the Serial COM ports on you local machine using WAMP Server..  (using a WINDOWS machine)

(I believe it would only be 1 little step further to open this up to the 'internet'.. but putting WAMP server 'online', ad forwarding your router HTTP port to the machine that has WAMP server installed on it)

First.. make sure you have WAMP Server installed  (this lets you locally, install and run, Apache web server, PHP scripting language and MySQL database framework)

WAMP Server:
http://www.wampserver.com/en/


Once you have that installed you can make a folder in the www directory:  C:\wamp\www
(or left click on WAMP icon in sys tray and choose 'www directory' to go to folder)

(I made a folder called arduino_projects)

the Arduino code/sketch I am using as a quick test to determine if the incomingByte is a 1 or a 0.


ARDUINO CODE:


Quote

//first php to serial attemp

int ledPin13 = 13; // the pin that the green LED is attached to
int incomingByte;      // a variable to read incoming serial data into

void setup() {  
 Serial.begin(9600); // initialize serial communication  
 pinMode(ledPin13, OUTPUT);  // initialize the green LED pin as an output
}


void loop() {
 // see if there's incoming serial data:
 if (Serial.available() > 0) {
   Serial.println("Serial data available......");
   incomingByte = Serial.read(); // read the oldest byte in the serial buffer
   //Preform the code to switch on or off the leds
   if (incomingByte == '0') {
     Serial.println("nothing yet......");
     digitalWrite(ledPin13, HIGH); //If the serial data is 0 turn red LED on
     delay(200);
     digitalWrite(ledPin13, LOW); //If the serial data is 0 turn red LED on
     delay(250);
     digitalWrite(ledPin13, HIGH); //If the serial data is 0 turn red LED on
     delay(250);
     digitalWrite(ledPin13, LOW); //If the serial data is 0 turn red LED on
     delay(250);
     digitalWrite(ledPin13, HIGH); //If the serial data is 0 turn red LED on
   
 }
   if (incomingByte == '1') {
     Serial.println(incomingByte, HEX);
     digitalWrite(ledPin13, LOW); //If the serial data is 1 turn red LED off
   }
 }
}







Now.. I have actually gotten '2' different PHP examples working..


PHP SAMPLE 1:

1.) this doesnt seem to use any other extra PHP classes or anything.

Code: [Select]

<?PHP
exec("mode COM3 BAUD=9600 PARITY=N data=8 stop=1 xon=off");

$fp = fopen("com3", "w");
if (!$fp) {
  echo "Not open";
} else {
  sleep(10);
  echo "Open";
  fwrite($fp, "0");
  fclose($fp);
}
?>



**Note:  you'll notice a sleep(); function in there.. this is ONLY there because I have NOT disabled the AUTO-RESET on SERIAL OPEN/CLOSE that the Arduino does (either by edit bootloader/firmware or by adding resistor)

The second PHP approach uses an extra PHP class you need to import..

its called the php_serial.class

and can be downloaded here:

php_serial.class.php:
http://www.phpclasses.org/browse/file/17926.html
or
http://code.google.com/p/php-serial/source/browse/trunk/php_serial.class.php?r=11


put the above class in the same folder/directory as this .php script.

Code: [Select]
<?php 


/* 

Utilizes the PHP Serial class by Rémy Sanchez <thenux@gmail.com> 
(Thanks you rule!!) to communicate with the Arduino Serial! 

*/ 



//Load the serial port class 
require("php_serial.class.php"); 
     
//Initialize the class 
$serial = new phpSerial(); 

    
//Specify the serial port to use... in this case COM1 
//SET THIS TO WHATEVER YOUR SERIAL DEVICE HAPPENS TO BE, 
//YOU CAN FIND THIS UNDER THE ARDUINO SOFTWARE'S MENU
     
//$serial->deviceSet("/dev/tty.usbserial-A7006QCP"); 
$serial->deviceSet("com3"); 
    
//Set the serial port parameters. The documentation says 9600 8-N-1, so 
$serial->confBaudRate(9600); //Baud rate: 9600 
   
//$serial->confParity("none");  //Parity (this is the "N" in "8-N-1") ******THIS PART OF THE CODE WAS NOT NEEDED
//$serial->confCharacterLength(8); //Character length (this is the "8" in "8-N-1") ******THIS PART OF THE CODE WAS NOT NEEDED
//$serial->confStopBits(1);  //Stop bits (this is the "1" in "8-N-1") ******THIS PART OF THE CODE WAS NOT NEEDED
//$serial->confFlowControl("none"); //******THIS PART OF THE CODE WAS NOT NEEDED


//Now we "open" the serial port so we can write to it 
$serial->deviceOpen(); 

sleep(5);  

//to turn the GREEN LED ON, we issue the command  
$serial->sendMessage("0");      
    
     
//We're done, so close the serial port again 
$serial->deviceClose(); 

?>




BOTH of these have worked.. at least enough to get the LED to blink on pin13. :)

I have NOT tried reading anything (yet).. or even researching into what will work... (or wont)



now that we have a BASIC PHP >> ARDUINO communication going..

I will attempt the following as the next step/demo.

1.) altering our Arduino code to accept/read/parse more than 1 byte.. (perhaps a value of 0-255 for PWM)
2.) making a little FLASH interface/front-end  (slider or stepper) to send this data to Arduino and adjust the PWM brightness on a led/pin.

thanks...

xl97

hey gang...

ok taking this another step further in my learning/journey....

I wanted to see if I could simple make a 'nicer' front end for this by using Flash.
and also send a bit more data, then just a 1 or 0....

so the idea to have a Flash front end/gui with a slider or stepper to send a value of 0-255.. and then have the Arduino represent that value on a PWM enabled pin.

So we have a few changes.. and a few NEW things.  :)



1.)  the PHP code we used previously has changed a bit..  (needs to be able to handle NEW (dynamic) data being sent to it form the FLASH front end..


(notice the new line declaring a variable from POST data sent from Flash


PHP Script:
Code: [Select]

<?PHP

$pwmValue=$_POST["pwmValue"];

exec("mode COM3 BAUD=9600 PARITY=N data=8 stop=1 xon=off");

$fp = fopen("com3", "w");

if (!$fp) {
   echo "Not open";
}else {
   sleep(5);
   echo "Open";
   echo $pwmValue;
   fwrite($fp, $pwmValue);
   fclose($fp);
}
?>



(here is the new Arduino code.. same samples posted all over on how to parse multiple digit string using a starting and delimiting character  (thanks PaulS.. fo rthe post on read on it)...)

Arduino Code:

Code: [Select]
#define SOP '<'
#define EOP '>'
bool started = false;
bool ended = false;

char inData[5];
byte index;

int ledPin = 9; // pwm test pin
int newValue = 0;

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

void loop(){
  // Read all serial data available, as fast as possible
  while(Serial.available() > 0){
    char inChar = Serial.read();
    //Serial.println(inChar);
    if(inChar == SOP){
      index = 0;
      inData[index] = '\0';
      started = true;
      ended = false;
    }
    else if(inChar == EOP){
      ended = true;
      break;
    }
    else{
      if(index < 5){
        inData[index] = inChar;
        index++;
        inData[index] = '\0';
      }
    }     
  }
   
  // Packet data done..   
  if(started && ended){
    newValue = atoi(inData);
    analogWrite(ledPin, newValue);   
    // Reset for the next packet
    started = false;
    ended = false;
    index = 0;
    inData[index] = '\0';   
  }
}



You can test what we have here so far.. by itself.. it should work(as is) using the serial monitor from the Arduino IDE.. you can test by wrapping any number from 0-255 between the < and > tags/characters



The last portion of this project was the Flash front end.. which is VERY (very) simple..

I'll upload the .swf as well a source .fla to look at how it was put together.. but the code for the flash side is just this: (nothing more)

ActionScript Code:
Code: [Select]

//set stepper boundaries
pwmStepper.minimum = 0;
pwmStepper.maximum = 255;

//create load vars instance
var pwmData:LoadVars = new LoadVars();

sendBtn_mc.onRelease = function(){
pwmData.pwmValue = "<"+pwmStepper.value+">";
trace("DATA CHECK: "+pwmData.pwmValue);
pwmData.sendAndLoad("flash_to_phpSerial.php", pwmData, "POST");
}



Feedback..pointers..   anything you got is always appreciated.

thanks

xl97

Here are the files to use a Flash front end/gui to send 3 x PWM values to the Arduino to control an RGB led connected to it..

values sent are in the following format: 
  *(using a starting and ending character)
  *(splitting data string into name token and value tokens)
  *(doing a string compare after the 'split')

<r=xxx>
<g=xxx>
<b=xxx>

example:<r=100><g=5><b=55>

Is how the data/string is sent form Flash to PHP, and hence to the COM PORT.

Wiring diagram for RGB:



Arduino Code:
Quote

#define SOP '<'
#define EOP '>'
bool started = false;
bool ended = false;

char inData[5];
byte index;

int redLed = 9; // pwm test pin
int redValue = 0;
int blueLed = 10; // pwm test pin
int blueValue = 0;
int greenLed = 11; // pwm test pin
int greenValue = 0;

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

void loop(){
  // Read all serial data available, as fast as possible
  while(Serial.available() > 0){
    char inChar = Serial.read();
    //Serial.println(inChar);
    if(inChar == SOP){
      index = 0;
      inData[index] = '\0';
      started = true;
      ended = false;
    }
    else if(inChar == EOP){
      ended = true;
      break;
    }
    else{
      if(index < 5){
        inData[index] = inChar;
        index++;
        inData[index] = '\0';
      }
    }     
  }

  // Packet data done...parse/evaluate data
  if(started && ended){

    //putstring("VALUE TOKEN: ");
    Serial.println(inData);
    char *nameToken = strtok(inData, "=");
    if(nameToken){
      //check if red data coming over
      if(strcmp(nameToken, "r") == 0){   
        char *valueToken = strtok(NULL, "\0");
        if(valueToken){
          //putstring("VALUE TOKEN: ");
          //Serial.println(valueToken);
          redValue = atoi(valueToken); 
          analogWrite(redLed, (255 - redValue));
        }
        else{
          //putstring("DEFAULT VALUE USED: ");
          //if param is missing, default to 0
          redValue = 0; 
          analogWrite(redLed, (255 - redValue));
        }
      }
      //check if green data coming over
      if(strcmp(nameToken, "g") == 0){   
        char *valueToken = strtok(NULL, "\0");
        if(valueToken){
          //putstring("VALUE TOKEN: ");
          //Serial.println(valueToken);
          greenValue = atoi(valueToken); 
          analogWrite(greenLed, (255 - greenValue));
        }
        else{
          //putstring("DEFAULT VALUE USED: ");
          //if param is missing, default to 0
          greenValue = 0; 
          analogWrite(greenLed, (255 - greenValue));
        }
      } 
      //check if blue data coming over
      if(strcmp(nameToken, "b") == 0){   
        char *valueToken = strtok(NULL, "\0");
        if(valueToken){
          //putstring("VALUE TOKEN: ");
          //Serial.println(valueToken);
          blueValue = atoi(valueToken); 
          analogWrite(blueLed, (255 - blueValue));
        }
        else{
          //putstring("DEFAULT VALUE USED: ");
          //if param is missing, default to 0
          blueValue = 0; 
          analogWrite(blueLed, (255 - blueValue));
        }
      } 
    }

    // Reset for the next packet
    started = false;
    ended = false;
    index = 0;
    inData[index] = '\0';   
  }
}






PHP script used to forward data to COM PORT of choice:

Code: [Select]

<?PHP

     $pwmValue=$_POST["pwmValue"];

     exec("mode COM4 BAUD=9600 PARITY=N data=8 stop=1 xon=off");

     $fp = fopen("com4", "w");

     if (!$fp) {
        echo "Not open";
     }else {
        fwrite($fp, $pwmValue);
        fclose($fp);
     }

?>





ActionScript code:  (w/.swf & .fla)

Code: [Select]
//set stepper boundaries
redStepper.minimum = 0;
redStepper.maximum = 255;
blueStepper.minimum = 0;
blueStepper.maximum = 255;
greenStepper.minimum = 0;
greenStepper.maximum = 255;

//create load vars instance
var pwmData:LoadVars = new LoadVars();

sendBtn_mc.onRelease = function(){
//pwmData.pwmValue = "<"+redStepper.value+">";
//pwmData.pwmValue = "<r"+redStepper.value+">"+"<g"+greenStepper.value+">"+"<b"+blueStepper.value+">";
//pwmData.pwmValue = "<r-"+redStepper.value+"r>"+"<g-"+greenStepper.value+"g"+"<"+blueStepper.value+">";
pwmData.pwmValue = "<r="+redStepper.value+">"+"<g="+greenStepper.value+">"+"<b="+blueStepper.value+">";
trace("DATA CHECK: "+pwmData.pwmValue);
//pwmData.sendAndLoad("flash_to_phpSerial.php", pwmData, "POST");
pwmData.send("flash_to_phpSerial.php", "_blank", "POST");
}





Attached is all files you would need to test this demo out:

* phpSerial_pwmRGBv2.pde  (goes in your Arduino sketchbook folder.... upload/write sketch to your Arduino)

--These files all go into your 'www' directory in your Wamp Server installation  (C:\wamp\www\)

* flash_to_phpSerial.php  - this is he PHP script that handles the data passing form Flash to the Serial Com Port
* flash_to_phpSerial_rgb.html
* flash_to_phpSerial_rgb.swf
* AC_RunActiveContent.js
* flash_to_phpSerial_rgb.fla  -  Flash front end source file


Let me know if everything works for you...or if there are better ways to handle/do these things..etc.


blackfury007

hi friends... am new to arduino. i am having a big doubt. i am doing a project on nfc shield using UNO. so i want to know when the nfc tags are read by the sheild it should compare the ID of tag with sql server and if matched it should go for next loop... what should i do for that... pleasee help me...

xl97

IMHO...

this thread/project will NOT help you..


this is for Windows.. and that being said.. the PHP (I believe) only have 1 way communication..

(ie: it can only PUSH out data to the COM port "TO" the Arduino... but can NOT receive any data "FROM" the Arduino)

From what I have read.. (on Windows)  PHP is only working 1 way.. not 2 way communication.

Look around and see if you there is some sort of local 'proxy' app that will do for you  (gobetweeno?)  or something similar?


clrathnayake

Hello friends, I'm new to arduino. I'm trying to make a distance reader in PHP using HC-SR04 ultrasonic sound sensor with a arduino (without ethernet shield). Basically I need to show distance data on the PHP page. Although I tried the following method it didn't work  :smiley-confuse: . How should I capture and display this sensor data using PHP.  

My Arduino Code:

/* HC-SR04 Sensor
 * TRIG connection of the sensor attached to digital pin 2
 * ECHO connection of the sensor attached to digital pin 4
  This example code is in the public domain.
*/


const int trigPin = 2;
const int echoPin = 4;

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

void loop()
{
 long duration, cm;

 pinMode(trigPin, OUTPUT);
 digitalWrite(trigPin, LOW);
 delayMicroseconds(2);
 digitalWrite(trigPin, HIGH);
 delayMicroseconds(10);
 digitalWrite(trigPin, LOW);

 pinMode(echoPin, INPUT);
 duration = pulseIn(echoPin, HIGH);

 cm = microsecondsToCentimeters(duration);
 
 Serial.print(cm);
 Serial.print("cm");
 Serial.println();
 
 delay(1000);
}

long microsecondsToCentimeters(long microseconds)
{
 return microseconds / 29 / 2;
}




My PHP Code:

<?php
exec("mode COM32 BAUD=9600 PARITY=N data=8 stop=1 xon=off");

$fp = fopen("com32", "w");
if (!$fp) {
  echo "Not open";
} else {
  sleep(10);
  echo "Port Open";
$string = fgets($fp);
echo $string;
  fclose($fp);
}
?>

info:
Port : COM32
PHP version : 5.5.15
Platform : Windows 8.1

misolans

<?php
exec("mode COM32 BAUD=9600 PARITY=N data=8 stop=1 xon=off");

$fp = fopen("com32", "w");

info:
Port : COM32

Change your port from 32 to 4 or less... Sometimes it get's buggy when using more than COMx>=5.

septillion

Noce project but uhm..
I wanted to see if I could simple make a 'nicer' front end for this by using Flash.
Drop the stupid flash and use HTML5 / JavaScript...

Change your port from 32 to 4 or less... Sometimes it get's buggy when using more than COMx>=5.
I really never ever had any problem with that.Use COM 7 to 12 all the time, no problem.
Use fricking code tags!!!!
I want x => I would like x, I need help => I would like help, Need fast => Go and pay someone to do the job...

NEW Library to make fading leds a piece of cake
https://github.com/septillion-git/FadeLed

xl97

Noce project but uhm..Drop the stupid flash and use HTML5 / JavaScript...
thanks for the unsolicited advice.. 

"but uhm..".....  that was a 4+ year old project.. maybe more by the time it was posted.

I understand/know Flash is not a very popular/valid media anymore..

but it still can do many things HTML5/JS (flash killers) can not do natively.. or at least much easier.

The test was chosen for a reason.

septillion

that was a 4+ year old project..
I'm sorry! I missed it was a very old tread kicked back up! :o Flash in 2012 was indeed way more common :)

And yeah, maybe Flash can do things easier out of the box, that indeed made Flash great. But that's also the weak spot of Flash, everybody can do everything with a flash app... Even Adobe is abandoning the sinking ship called Flash :D
Use fricking code tags!!!!
I want x => I would like x, I need help => I would like help, Need fast => Go and pay someone to do the job...

NEW Library to make fading leds a piece of cake
https://github.com/septillion-git/FadeLed

xl97

haha..

I understand.

I wasnt championing for it.  But there was and still are some use case scenarios..

(if it was more secure, it would have been more widely accepted in the end)


Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy