Tuesday, October 21, 2014

Talking to an Arduino from PHP

I was able to talk to my Arduino without using an Ethernet or a wireless shield.
Best part is that I only have 4 lines in my PHP script :)

Things you need to have :

Arduino board with a USB Cable
Breadboard
1 LED
Few jumper wires
220 OHM resistor

Additionally Arduino IDE, PHP, Apache2 installed Linux box :)

1. Connect Arduino's GND pin to breadboard's ground line.
2. Connect Digital pin 13 to breadboard's + line.
3. Connect LED's Anode(long leg) with the breadboard's + line using the 200 OHM resistor.
4. Connect LED's cathode(short leg) with breadboard's - line directly using a jumper cable.

You are done with the circuit prototype, Now connect the Arduino board to your PC.

Open Arduino IDE, click on tools> Serial port. You can see the device connected to a port similar to "/dev/ttyACM0".

Let's write our PHP snippet,

<?php
  $comPort = "/dev/ttyACM0"; /*Update to the correct port */
  $fp =fopen($comPort, "w");
  fwrite($fp, "switch"); /* We are going to write "switch" */
  fclose($fp); 
?>
That is it, host this snippet switch_uno.php within  /var/www/php-arduino directory. lets write our Arduino sketch.

String val;

void setup()
{
    Serial.begin(9600);
    pinMode(13, OUTPUT);
}

void loop()
{
    while (Serial.available()){
        delay(10);
        char c = Serial.read();
        if (c == ','){
            break;
        }

        val+= c;
    }

    if (val == "switch") {
        if(digitalRead(13) == LOW){
            digitalWrite(13, HIGH);
            delay(100);
            Serial.println(1);
        }else if(digitalRead(13) == HIGH){
            digitalWrite(13, LOW);
            delay(100);
            Serial.println(0);
        }
        val="";
    }


}

Upload above sketch to your Arduino and open the serial monitor window within the Arduino IDE.
In order to execute our PHP snippet,
Lets open a terminal window and change directory to the /var/www/php-arduino directory.

run sudo php switch_uno.php your LED will be on :) If you run the same command again LED will be off.

You can do the same by using PHP serial class also.

No comments:

Post a Comment