Just got your first Arduino, but you don’t have any additional hardware? Gotten a little tired of watching the LED blink by itself, with no interaction? Check this out.

This is the first thing I ever made for Arduino, as I had just received my first Uno and didn’t have any additional hardware. After playing with the included examples and some tutorials I got bored after about an hour (making the internal LED blink is only exciting for so long!).

So I decided to make it a bit more interesting; i wanted to be able to enable and disable the internal LED using a web interface. This is actually quite simple, and could easily be altered to enable remote control of relays or other different types of outputs. The great thing about using a web interface is that it is cross-platform and pretty much enables you to also control your Arduino using most devices with web browsing capabilities, such as smartphones and tablets.

Well, enough talk. Let’s get to it! Here’s what you need:

• An Arduino board with an internal LED (usually on pin 13) or a separate LED
• A webhosting service with PHP support
• The Arduino IDE
• The Processing IDE
• A text editor (e.g. Notepad++, Geany, or whatever you prefer)

First, we’ll start off with the web interface. It’s function is to give the user the choice to either switch the LED on or off. When either one of them is clicked, the command is written to a .txt-file as a 1 (ON) or 0 (OFF) value.
The interface consists of three files; a HTML frontend, a PHP document, and a .txt-file for storing values. So, firstly create these files using a text editor:

    • index.html
    • led.php
    • LEDstate.txt

Index.html should contain the following:

<html>
<head>
<title>LED ON/OFF</title>
</head>
<body>
<!-- This is just for aesthetics, centering the
content within the paragraph -->
<p align="center">
<font size="8">

<!-- This part is a a link, which also sends a request to the php-document,
telling it to write 1 or 0 to LEDstate.txt -->
<b><a href="led.php?state=1">ON</a></b> /
<b><a href="led.php?state=0">OFF</a></b></font>
</p>

</body>
</html>

 
Here’s an example of what it should look like.

Now for the PHP file :

<?php
$onoroff = $_GET["state"]; // Declares the request from index.html as a variable
$textfile = "LEDstate.txt"; // Declares the name and location of the .txt file

$fileLocation = "$textfile";
$fh = fopen($fileLocation, 'w	') or die("Something went wrong!"); // Opens up the .txt file for writing and replaces any previous content
$stringToWrite = "$onoroff"; // Write either 1 or 0 depending on request from index.html
fwrite($fh, $stringToWrite); // Writes it to the .txt file
fclose($fh); 

header("Location: index.html"); // Return to frontend (index.html)
?>

The .txt file (LEDstate.txt) can be left empty.

Upload these three files to your website, and remember the location. We’re gonna need it for later.

Now it’s time to code the Arduino! For this, we can simply use the “Physical Pixel” example code from the Arduino website, written by David A. Mellis, Tom Igoe and Scott Fitzgerald. We only need the Arduino part of it though, so I’ll copy it onto here. What it does is to open up a serial connection to the host computer and listens for serial inputs. If the Arduino receives the command “H” it sets the LED to “HIGH” (ON), or “LOW” (OFF) if it receives the command “L”. (For more information on this, check out the “blink” tutorial).

const int ledPin = 13; // the pin that the LED is attached to - change this if you have a separate LED connected to another pin
int incomingByte;      // a variable to read incoming serial data into

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

void loop() {
  // see if there's incoming serial data:
  if (Serial.available() > 0) {
    // read the oldest byte in the serial buffer:
    incomingByte = Serial.read();
    // if it's a capital H (ASCII 72), turn on the LED:
    if (incomingByte == 'H') {
      digitalWrite(ledPin, HIGH);
    }
    // if it's an L (ASCII 76) turn off the LED:
    if (incomingByte == 'L') {
      digitalWrite(ledPin, LOW);
    }
  }
}

Upload the sketch to your Arduino using the Arduino IDE. To test if it works, open up the serial port monitor and type either “H” or “L” (without quotation marks), then click send. If the LED turns on and off, you’re good to go! If not, check if the pin variable is set to the actual pin your LED is connected to (if you’re not using the internal one – which usually is at pin 13).

Now for the last part that ties it all together! Open up the Processing IDE and enter the following:

/*

A simple Processing script for enabling or disabling the LED on an Arduino using a web interface and serial communication.
Author: Sindre Lindstad
Created: 19th of January 2011

http://projects.sindrelindstad.com

*/

 import processing.serial.*;
 Serial port;

 void setup()  {

   /* This part must be altered to fit your local settings. The number in brackets after "Serial.list()" is where you declare what COM port your Arduino is connected to.
      If you get error messages, try a different number starting from 0 (e.g. 0, 1, 2, 3...) . */
    port = new Serial(this, Serial.list()[1], 9600);  // Open the port that the Arduino board is connected to, at 9600 baud

}
 void draw() {

  String onoroff[] = loadStrings("http://YOURDOMAIN.COM/LEDstate.txt"); // Insert the location of your .txt file
  print(onoroff[0]);  // Prints whatever is in the file ("1" or "0")

  if (onoroff[0].equals("1") == true) {
    println(" - TELLING ARDUINO TO TURN LED ON");
    port.write('H'); // Send "H" over serial to set LED to HIGH

  } else {

    println(" - TELLING ARDUINO TO TURN LED OFF");
    port.write('L');  // Send "L" over serial to set LED to LOW
 }

  delay(7000); // Set your desired interval here, in milliseconds
 }

Remember to edit it according to the comments. Now you should be all set to hit the Run/Play button! A small empty window will pop up, but your sketch should be running properly and posting messages in the Processing terminal window.

If you haven’t set it to connect to the right serial COM-port it will post an error to the terminal window. If you haven’t set the correct path to your .txt file, it will post “html” instead of “1″ or “0″. Also note that you cannot use the Arduino IDE serial port monitor (or any other serial monitor) while running the sketch.

If everything works; – hooray! Show your friends, and have them turn your LED on and off from whereever they might be in the world. If it doesn’t work, review everything and make sure it’s all set up properly. If it still won’t work; leave a comment.

-

Reddit user tenbatsu jazzed up the Arduino sketch a bit, and made it a little sexier. It’s designed for the use of three (external) LEDs. A blue LED to fade in and out, a green LED that indicates a “ready” state, and a red LED that indicates a “change” state. Have a look!

const int fadePin = 9;    // The pretty blue LED
const int redPin = 10;    // Red LED
const int greenPin = 11;  // Green LED
const int fadeAmount = 5; // Increment to adjust brightness

int incomingByte;   // A variable to read incoming serial data into
int brightness = 0; // How bright the LED is

void setup()  {
  // Initialize serial communication:
  Serial.begin(9600);

  // Declare outputs:
  pinMode(fadePin, OUTPUT);
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
} 

void loop()  {
  // Indicate ready state
  digitalWrite(greenPin, HIGH);
  digitalWrite(redPin, LOW);

  if (Serial.available() > 0) {
    // Indicate change state
    digitalWrite(redPin, HIGH);
    digitalWrite(greenPin, LOW);

    // See if there's incoming serial data:
    incomingByte = Serial.read();

    if (incomingByte == 'H' && brightness < 255) {
      // Cycle the blue LED from dim to bright
      for (brightness = 0; brightness < 255; brightness += fadeAmount) {
        analogWrite(fadePin, brightness);
        delay(30);
      }
    } else if (incomingByte == 'L' && brightness > 0) {
      // Cycle the blue LED from bright to dim
      for (brightness = 255; brightness > 0; brightness -= fadeAmount) {
        analogWrite(fadePin, brightness);
        delay(30);
      }
    }
  }
}
 

35 Responses to How to remotely enable/disable a LED on your Arduino using PHP and Processing

  1. [...] a self described “Norwegian guy”, has put together this really neat tutorial for people getting started with the arduino. In this tutorial, you can learn how to remotely turn on/off the little blinking light on the [...]

    • waqas says:

      i am confuse in one thing what is processing ide and arduino ide? should i upload both in arduino or how i m confuse?

  2. nightowl says:

    hello, i do this i put the serial port 0 run but nothing happend with the arduino.

    • sindre says:

      If you add this to the setup-part of the code it will print a list of your available serial ports upon initiating the sketch:

       void setup()  {
      
         /* This part must be altered to fit your local settings. The number in brackets after "Serial.list()" is where you declare what COM port your Arduino is connected to.
            If you get error messages, try a different number starting from 0 (e.g. 0, 1, 2, 3...) . */
      
          println(Serial.list());
          port = new Serial(this, Serial.list()[1], 9600);  // Open the port that the Arduino board is connected to, at 9600 baud
      
      }
      

      Then try using one of the serial ports listed in the terminal output.

  3. yukom says:

    that’s works… thanks bro…
    i’ll develop to the next my project using relay…

  4. yukom says:

    @waqas that’s Processing IDE is like an interface of your arduio sketch in Arduino IDE, the analogy like this : Your sketch in arduino IDE is a backend of your project and the Processing sketch in Processing IDE is a front end of user that control your project.

    i hope that’s will help you, i’m sorry my english not good. :D

  5. hugh says:

    this line: port = new Serial(this, Serial.list()[1], 9600);
    Im getting arrayoutofbound exception. need help

    • sindre says:

      You’re probably trying to connect to an unavailable COM-port. First connect the Arduino to your computer, then add this line to the code, and run it. It should list the COM-ports currently used by your computer, before it outputs the ArrayIndexOutOfBoundsException error:

       void setup()  {
      
         /* This part must be altered to fit your local settings. The number in brackets after "Serial.list()" is where you declare what COM port your Arduino is connected to.
            If you get error messages, try a different number starting from 0 (e.g. 0, 1, 2, 3...) . */
      
          println(Serial.list());
          port = new Serial(this, Serial.list()[1], 9600);  // Open the port that the Arduino board is connected to, at 9600 baud
      
      }
      

      Here’s an example output:
      [0] “COM1″
      [1] “COM4″

      In this case it means that the Arduino is connected to either COM1, which is identified as number 0, or COM4, which is identified as number 1. I know my Arduino is connected to COM4, so I use number 1: port = new Serial(this, Serial.list()[1], 9600);

      On your computer, however, it might be another number. If it’s 0, you use this parameter:
      port = new Serial(this, Serial.list()[0], 9600);
      or if it’s 2:
      port = new Serial(this, Serial.list()[2], 9600);

      etc.

      • hugh says:

        thx for you reply. I figured that my arduino is connect to COM3 and it is the only one which shown up. Therefore i change it to port = new Serial(this, Serial.list()[0], 9600);

        Another problem is that, im hosting a server locally with Apache and i put the LEDtext.txt file under etc/cmos/LEDtext.txt and set the corresponding loadStrings(“localhost/cmos/LEDstate.txt”); but its giving me null exception saying the file is not exist. what did i do wrong?

        • hugh says:

          nvm, i tried to set it as my local directory and it works perfectly nice now :)

          I have a question tho, what the purpose of using Processing, can we do something in arduino or just PHP to make the LED be controllable from web?

          • sindre says:

            If you connect the Arduino directly (through USB) to the web server, you can feed it commands from PHP using serial communication.

            Or you could use an Ethernet Shield to connect the Arduino directly to your local network.

            Otherwise you’ll need a link between the webserver and the Arduino – in this case a computer + Processing.

  6. agus joko says:

    Help,,

    I try the code, but the led.php cannot save state 0/1 to LEDstate.php,,
    maybe we must declare the location of LEDstate.txt file??? thx

  7. thanks for this tutorial i made my own version of the led system have a look here http://arduino.mitfiles.com/ it also has a live webcam feed to show you the output

  8. Alex says:

    Hello,
    I am really interested in your project. I followed your instructions but when i compile the processing program, I get this error: “NullPointerException” while the following line is highlighted:

    print(onoroff[0]); // Prints whatever is in the file (“1″ or “0″)

    Could you please help me fix this problem?

    Thanks,
    Alex

  9. Carlo says:

    Can i enable a LED remotely with an Arduino Uno and Arduino Ethernet Shield without a computer??

    I made a remote enable of a motor with the mentioned components, but obviously with a PC, want to do the same without a computer, only with Arduino Uno and Arduino Ethernet shield. It’s possible?

  10. siegkorn says:

    Awesome project!!! thanks for sharing!!!

  11. ninjo says:

    Thank you so much. Finally i found a code that work fine. The only one. Now in trying to do this on a raspberry pi but processing is giving me a few problems.

  12. limuel says:

    this is nice.
    but can you help me about my final year project a real time vehicle tracking system with collision detection. the only problem is that i can’t send the data taken from the GPS and send to my web server by GPRS, i’m using arduino atmega644 kit, GPS receiver shield and GSM/GPRS shield. and form my domain server i use DOT.TK a free domain name provider and a 000webhost.com for a free web hosting.

    can you help me about my problem? by the way the data that will be send by gprs will be automatically save to my database it is also online by the use of 000webhost.com, and the data taht is send is the latitude, longitude and the time or the UTC(Universal Time Coordinates).

    i’m looking forward for your help. hope you can help me about this..
    thank you advance…

    erilwewel@yahoo.com

  13. sachin muley says:

    Sir..
    we did the above mentioned procedure…there is no error in index.html,processing ide and arduino ide. everything is running properly..after clicking on ON in index.html,the text file LED_state.txt is also getting updated to 0 or 1…but the led is not blinking…what is the problem? need help….

  14. Zainub says:

    Hello:
    I want to connect gprs module to an android application. I have teensy++2.0 it uses arduino IDE. I have to turn on and of led through android application. What should I do. Please help me in using AT commands because I have separate GPRS module and Microcontroller (Teensy++2.0).

    Thanking in anticipation

    Zainub Bahar

  15. Pedro Celeste says:

    Hi,

    I have an arduino Uno and a shield 3G + GPRS(http://www.cooking-hacks.com/index.php/documentation/tutorials/arduino-3g-gprs-gsm-gps?utm_source=banner_3g_shield&utm_medium=banner) and I am developing a project, this project goal is to get the coordenates from the Arduino (done) and send that data (Latitude and Longitude) to my web Server (DataBase).

    I follow this example and i think you can help me with this..

    If you can send me a code or some ideias how to complete my project i would really apreciate.

    Best regards

  16. Ankit Joshi says:

    Hello,
    Very nice explanation but i want to know can you perform this same functionality by using webservice through GSM shield.I mean that, i want to operate the led from android mobile wirelessly using GSM shield in arduino without sending sms & voice calls. please reply me as soon as possible.

    Thanks in advance…

  17. [...] - How to remotely enable/disable a LED on your Arduino using PHP and Processing – Enviar datos de PHP a Arduino - Controlling an Arduino with PHP [...]

  18. santha says:

    hello bros .. my arduino cant work… i dunno … i used port 27,, so .. how i can write script

    void setup() {
    port = new Serial(this, Serial.list()[0], 9600);

    i try [0] .. processing IDE work ane teeling arduino to run led OFF
    but i try to index.html… and clink on… no respon ,,, so please help….

  19. Adam McAllister says:

    Ok, so I can get it to turn on and off from my computer…but I hooked it up to another computer and it does not work. How would run turn off the LED from across the world. Do they need to run the Processing program as well.???

  20. Herren Nike Air Max 2011 Mesh-Orange Schwarz Grau Laufschuh bietet maximale D盲mpfung und Flexibilit盲t mit h枚chster Leistung und Stil. Hyperfuse-Obermaterial mit dynamischem Flywire Technologie liefert leichte, flexible Unterst眉tzung, Notched innersleeve und atmungsaktivem Mesh bieten eine nahtlose Komfort. Cushion Zwischensohle und ein full-length Max Air Einheit f眉gen Pl眉sch D盲mpfung f眉r die ultimative Fahrt. Flexkerben f枚rdern einen reibungslosen 脺bergang. Umweltfreundliche Gummiau脽ensohle mit strategisch platzierten BRS 100carbon Gummistollen in der Ferse und Vorfu脽 bietet optimale Traktion. Wt. 10,0 oz.Maximum Sto脽d盲mpfung. Die brutale, repetitive, nach unten gerichtete Kraft des Sports kann verheerend auf den K枚rper anrichten

  21. I have read so many articles concerning the blogger lovers however this paragraph is really
    a pleasant article, keep it up.

    Here is my web-site: harbor isles apollo beach

  22. mahesh ds says:

    its working thanks a lot explained in a perfect manner

  23. Iris says:

    It absolutely was my findings with this that cause me to comprehend that funds and income are an evil within my heart.

    Without doubt, it may serve being an avenue for internet sites to promote their organization.

  24. All of these games plants vs zombies garden warfare download is
    one of the three interesting movies on mobile. From, quiz games like Angry
    Birds game is small but the hordes of ‘nasties’. Being a player
    from moving to the native approach. This game is very
    easy thing you will stay in touch with our web site.
    Even these days, mobile games that involve betting are crowd favorites.

  25. Hello friends, how is all, and what you would like to say concerning this article, in my
    view its truly remarkable designed for me.

  26. The backend part of your company supports these profit centers.
    Then consider yourself one of the few, true internet marketers.

    A internet marketing business, in a nutshell, a business
    that’s designed to run on the internet via a website.

  27. Ramon says:

    Excellent beat ! I wish to apprentice while you amend your website, how could i subscribe for a blog site?
    The account aided me a acceptable deal. I had been a little bit acquainted
    of this your broadcast offered bright clear concept

  28. lloyd says:

    hello guys! I would like to ask if it is working in Windows OS?
    I will appreciate any answers,,

  29. The backend part of your company supports these profit centers.
    As the culture of internet slang grew, it took on new origins from pop culture or video games and television. A internet marketing business, in a nutshell, a business that’s designed to
    run on the internet via a website.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Set your Twitter account name in your settings to use the TwitterBar Section.