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);
      }
    }
  }
}
 

71 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. randolph pereira says:

    Guys if you get Nullexception -File does not exist
    If you are using free webhosting .text files may be blocked ,
    so just change the format to .doc and change the extension in the processing code as well as lel.php and volla it will work

  22. [...] How to remotely enable/disable a LED on your Arduino using PHP and Processing – tutorial to learn how to build a web interface for sending commands to an Arduino board in order to switching the LED on or off. The web interface consist of three main files including here the HTML file, a PHP file with instructions, and a .txt-file for storing values; [...]

  23. Ezu says:

    very good tutorials that help me to find what I need to build a web based application and control sensors from internet

  24. SiamakHadadi says:

    Hi, Excellent tutorials and thank you very much.

    I have a problem in ardoino mega 2560.

    sketch in arduino IDE is True (every think in serial port is O.K.)
    sketch in Process is True, too.
    But when i run processing and trun off LEDstate i See This msg:
    TELLING ARDUINO TO TURN LED OFF
    but my led on board is always turn ON!?

    Please Help me, Tank you.

  25. rogers says:

    can u help me with the index. what to i have to do once the code is copied on the notepad++

  26. rogers says:

    when i run the program with google chrome it gives an error, i cant get the on / off page ..can someone help pls

  27. pp says:

    Can this project run without computer?
    If it can’t how can i do?
    Sorry for my bad english.
    Thank you.

  28. Matthew says:

    I’m getting the following error on my website after going through your instructions:

    Warning: fopen(LEDstate.txt) [function.fopen]: failed to open stream: Permission denied in /www/zxq.net/b/l/a/blahblahhello/htdocs/led.php on line 6
    Something went wrong!

    do you know what I should be doing?

  29. Flavio says:

    I’m sorry, but how can I “…Open up the Processing IDE…” for editing?
    I am new to Arduino programming, and this tutorial is the 99% of my desired project… ( I want to control my Arduino’s ports by PHP ) but I don’t know how and what is the processing IDE. (I’m using UDOO with Ubuntu installed.)
    Can you help me to know how to do this?

    Sorry for my bad English.
    Greetings from Italy.

    Flavio B.

  30. Mason says:

    Thanks so much Sindre, this is just what I was looking for! Works great!

  31. Sinte says:

    Thank you so mach Sindre.

  32. aditya says:

    Hello I am new to Arduino programming. I’ve tried your program and it is going well, but now I am trying to control three different LEDs. whether it is possible in a way that you use? because I tried with as add new files. txt and new input but does not go well, 2 LED will not turn on. Can you help me?

    sorry for my bad english..
    thank you.
    aditya.scania@gmail.com

  33. Heidi Heweidy says:

    My port is COM11 but I still dont know how to get the serial number of it!

  34. Bauke says:

    This script rules! But I’ve countered some issues..

    1. If i’m in safari and click on and then off it works, but after pressing 2 times on on or off the script doesn’t seems to work anymore… Anyone knows why?

    2. (Sorry i’ve never done processing before) How to do this without your arduino connected to a pc?

  35. Mo says:

    Hello

    I’v problem

    import does not name a type

    please help me

  36. I have fun with, cause I discovered just what I used to be having a look for. You’ve ended my 4 day long hunt! God Bless you man. Have a nice day. Bye

  37. Mike Melvin says:

    Awesome…worked like a charm. Thanks so much

  38. ankit says:

    awesome work…and thanks…
    how can we do the same for 2 or more LEDs.
    can anyone help me out.
    ur reply is highly appreciated.

  39. Amin says:

    Hi,
    This is close to what I want to do. I would like to use Wi-Fi in order to trigger the led to turn on or off. Can you guide me on how i can do that?

    Thanks,
    Amin
    http://Www.personalizedmall.com

  40. jaradar says:

    It’s very useful article, but can i call/invoke a web service from processing?
    Is Spacebrew effective in such case??
    thanks in advance.

  41. Thank you for the good writeup. It in fact was a amusement account
    it. Look advanced to more added agreeable
    from you! By the way, how can we communicate?

  42. Stephen says:

    SIR I THANK YOU SO MUCH FOR THIS! It worked perfectly! :D CHEEEEEERRSS!!!!

  43. Stephen says:

    Hey sir! Good day! I’ve been searching for hours just to solve this problem, the application that i exported from processing doesn’t launch!!! WHY??? T_T

  44. Stephen says:

    Anyone here knows how to use SQL Database to read instead of using the .TXT?

  45. Jonas says:

    Heya! I’m at work surfing around your blog from my new iphone 4!
    Just wanted to say I love reading through your blog and look
    forward to all your posts! Keep up the outstanding work!

  46. [...] El documento es una traducción y desarrollo conforme a lo mostrado en el sitio Projects.sindrelinstand [...]

  47. Excellent blog here! Additionally your website a lot up
    very fast! What web host are you the use of? Can I get your affiliate link on your host?
    I wish my web site loaded up as fast as yours lol

  48. Darren says:

    I see a lot of interesting content on your website.

    You have to spend a lot of time writing, i know how
    to save you a lot of time, there is a tool that creates
    unique, google friendly posts in couple of seconds, just type in google – laranita’s free content source

  49. site says:

    bookmarked!!, I really like your website!

    my blog post site

  50. Battles are positioned up as the selection is broken down into categories,
    such as a computer, console or handheld like angry birds friends hack
    the UK and Sweden continue the fastest grossing app on the Internet facility.

    my blog post :: Angry birds friends cheats ipad

  51. Have you ever thought about publishing an ebook or guest authoring on other blogs?
    I have a blog based on the same topics you discuss and would
    really like to have you share some stories/information. I know my subscribers would value your work.
    If you’re even remotely interested, feel free to shoot me an email.

  52. Nont says:

    Dear friends your were created a great example&article for internet control , i made my example to control led over inter using PHP and Arduino+Ethernet Shield too, check it out at : http://www.iointouch.com/?p=6

  53. Kenshin says:

    I’m having a problem at the last step in which when I go to compile and run the processing code it says “Error opening serial port /dev/ttyS1: incorrect serial port”. I have made my way through the majority of serial ports (0-31). I am pretty sure that my arduino red board is connected to the ttyUSB0 port on my laptop, but when I try this I get a similar message. Any ideas on how to fix this would be much aprreceated.

    • Jack Barnes says:

      Kenshin,

      I am also trying to do this with a linux serial address. I am using a RasPi, and everything is loaded up and ready, but I cant get it to run.

      It errors with a inside Serial.ports() message. Has anyone else been able to get the RasPi version of this to work? If so how did you get passed the Serial address issue?

  54. Georgetta says:

    I do not even know the way I finished up here, but I assumed this post was
    great. I don’t recognise who you’re but definitely you’re going to a well-known blogger if you are
    not already. Cheers!

    my web blog … forslean weight loss review (Georgetta)

  55. Indira says:

    Quality articles is the important to invite the viewers to pay a quick
    visit the site, that’s what this web page is providing.

  56. It’s fantastic that you are getting ideas from this post as well as from our dialogue made at this time.

  57. You can trust their opinion over reviews found online.
    Do not put that in the hands of someone who is not trustworthy.
    Are you a member of any national brain injury associations.

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.