Wireless Relay Control with Arduino & the CC3000 WiFi chip

IMG_7517Controlling relays is a central piece in any home automation system. With them, you can easily switch on and off any electrical device in your home, like lights. This project is the second part of a series showing you how to use Arduino & the CC3000 WiFi chip for home automation purposes. The first part was dedicated to how to read data wirelessly from a temperature & humidity sensor.

In this project, we are going to see how to wirelessly control a relay from your computer or your smartphone, to build a wireless-controlled light switch for example.  To make things more efficient, we are going to create a small web server running on the Arduino board, that will receive the commands coming from your computer. As usual, the whole code for this project can be found inside our GitHub repository. Let’s dive in !

Hardware requirements

The whole project is based on the Arduino platform, so of course you will need an Arduino board. I really recommend using the Arduino Uno board for this project, as it is the only board that is currently compatible with the CC3000 library at the time this article was written.

Then, you need the CC3000 chip. As in the previous article, I recommend using the Adafruit CC3000 breakout board, which is the only one I tested that worked without problem. It is nice and compact, has voltage regulators onboard, as well as an onboard antenna. You can also make your own breakout board, as there are many PCB layout available online.

You also need a relay and some components around it. I used a 5V relay for this project, so it can directly be connected to the Arduino Uno board. You also need a standard rectifier diode to protect the relay, and one LED & a 220 Ohm resistor to test if the relay is working correctly.

Finally, you need a breadboard and some jumper wires to make the connections between the different parts.

Software requirements

For this project, you just need the usual Arduino IDE, the Adafruit’s CC3000 library, and the CC3000 MDNS library. We are also going to use the aREST library to send commands to the relay via WiFi. To install a library, just download the required folder, and put it into your /Arduino/libraries/ folder.

You will also need a web server running on your computer. I recommend using MAMP for OS X, EasyPHP for Windows, and visiting this page for Linux.

Hardware configuration

The hardware configuration for this project is actually not that complicated, thanks to the good informations that you will find on the CC3000 breakout board. Connect the IRQ pin of the CC3000 board to pin number 3 of the Arduino board, VBAT to pin 5, and CS to pin 10. Then, you need to connect the SPI pins to the Arduino board: MOSI, MISO, and CLK go to pins 11,12, and 13, respectively. Finally, take care of the power supply: Vin goes to the Arduino 5V, and GND to GND.

Let’s now connect the relay. After placing the relay on the breadboard, you can start identifying the two important parts on your relay: the coil part which command the relay, and the switch part where we will attach the LED. First, connect pin number 8 of the Arduino board to one pin of the coil, and the other pin to the ground of the Arduino board. You also have to place the rectifier diode (anode connected to the ground pin) over the pins of the coil to protect your circuit when the relay is switching.

Then, connect the +5V of the Arduino board to the common pin of the relay’s switch. Finally, connect one of the other pin of the switch (usually, the one which is not connected when the relay is off) to the LED in series with the 220 Ohm resistor, and connect the other side of the LED to the ground of the Arduino board.

The following picture summarizes the hardware connections:

cc3000_relay_bb

Testing individual components

I detailed the configuration of the CC3000 breakout board in a previous article, so we are simply going to test the relay in this part. But don’t worry, we are going to see the CC3000 & WiFi configuration again when testing the whole system.

You can test the relay with the following sketch:

The code is pretty self-explanatory, you can just upload it to the board and the relay should switch states every seconds, and the LED should switch on and off accordingly.

Putting it all together

Let’s now control the relay wirelessly using the CC3000 WiFi chip. The software for this project is based on the TCP protocol, just like the WiFi weather station project I mentioned before. However, for this project, the Arduino board will be running a small web server, so we can “listen” for commands coming from the computer. We will first take care of the Arduino sketch, and then we will see how to write the server-side code and create a nice interface.

First, the Arduino sketch. The goal here is to connect to your WiFi network, create a web server, check if there are incoming TCP connections, and then change the state of the relay accordingly. I will only put the important parts of the code in this article, you can find the whole code here. You need to import the right libraries:

Then, you need to define inside the code what is specific to your configuration: WiFi name & password, and the port for the TCP communications (I used 80 here):

We can then create the CC3000 instance, server and aREST instance:

In the setup() part of the sketch, we can now connect the CC3000 chip to the network:

Now you can ask, how will the computer know where to send the data ? One way would be to run the sketch once, then get the IP address of the CC3000 board, and modify the server code again. But we can do better, and that’s where the CC3000 MDNS library comes into play. We will basically assign a fixed name to our CC3000 board with this library, so we can write down this name directly into the server code. This is done with this piece of code:

We also need to listen for incoming connections:

Now, we will code the loop() function of the sketch that will be continuously executed. We first have to update the mDNS server:

The server running on the Arduino board will basically wait for incoming connections & handle the requests:

Then, the server side. The main part will be an HTML file, called interface.html, which will host two buttons to command the relay:

The buttons are linked to some JavaScript code, that will call a PHP file that will communicate with the Arduino board. I won’t get into the details of JavaScript, but if you want to learn more about this language, I recommend following the JavaScript for Beginners course on Udemy. This is the code for the JavaScript file, which is basically the function called when a button is clicked:

This PHP code is stored in the curl.php file, and we get the desired command from the interface with:

Then, the code establishes the connection with the Arduino board with:

The PHP code then sends the request to the server:

I also added some CSS to make things look a bit better. The complete code for this project can be found on our GitHub repository.

Finally, it’s time to test everything. Make sure your web server is running on your computer. At this point, you can also upload the Arduino sketch to the board and open the serial monitor. Then, simply open the file interface.html on your local server (make sure you are accessing the folder from localhost) and press any button you want. On the Arduino side, you should see that the board is connecting to your WiFi network, getting an IP, and then waiting for incoming connections. Try now to press a button on the web interface: it should change the state of the relay nearly instantly. This is what you should see inside your browser:

Screen Shot 2014-05-04 at 09.45.30

In case this doesn’t work, it could be that your computer doesn’t support the mDNS server (that allow the access to the Arduino board using the arduino.local name). But no worries: the sketch will actually print out the IP address of the CC3000 chip every time it starts. If you are having problems with the project, simply copy this IP address and replace the arduino.local with this IP address inside the PHP file.

Finally, you can also use your smartphone or tablet to use your WiFi-controlled relay. Simply enter the local IP address of your computer (where the web server is running) on your mobile device browser (and don’t forget the port, for example 192.168.0.4:80), and navigate in your project’s folder. You should see the exact same interface, and be able to control the relay from your device! If you managed to get it working, bravo, you just built a WiFi-controlled light switch! Of course, you can control much more than lights with this project. Just make sure your relay supports the power required for the device you want to control, and you’re good to go!

Update 04/05/14: The project was updated and is now using the aREST library. It greatly simplified the code and made the project works more reliably. Let me know if you encounter any issues with the new code!

This is the list of the components that were used in this project:

Receive the latest news about home automation
Over 1000 home automation enthusiasts already joined our list !

Do you want to receive the latest news about open-source hardware and home automation ? Then join our mailing list today by entering your name and email below. It is 100% free and you can unsubscribe at any time if you're not satisfied.

45 replies
  1. ben
    ben says:

    If I understand correctly, this runs a local web server on your computer that the arduino/cc3000 connects to and pushes data onto it?

    If so, what challenges would there be to put the webserver itself on the arduino/cc3000 itself? Could tools like espruino and node.js help?

    Esprinuo I believe is an opensource javascript interpreter.. which if the webserver is on a remote computer, could serve updating javascript pages for the arduino to process.

    In the case of node.js, a webserver could be implemented in javascript, but perhaps requires more processing power.

    Reply
    • Marco Schwartz
      Marco Schwartz says:

      Hey Ben,

      Exactly! I guess the main challenge comes from the CC3000 library, from what I heard the Adafruit library does not yet support the web server capabilities of the CC3000 chip. But the hardware would allow it, and it works for example on the official Arduino WiFi shield, so there is nothing that would prevent that from working in the future.

      Reply
      • Guilherme
        Guilherme says:

        Doesn’t it Arduino Yun attend these necessities? In fact I just ordered one to do some experiments running ASW EC2 instances as my remote web servers.

        Reply
      • das
        das says:

        Hi Marco,
        Can rest API be used on a non local network . Lets say I have a network at work and I want to turn on a light from home >?

        I have arduino boards Mega and a YUN so wanted to see what sort of YUN projects I could do that were handy .

        Also I have a YUN that is a 100 m from a wifi spot . Do you think it is possible to get wifi from there or will I need to use some sort of XBEE and two ccontrolr boards at each end ?

        Any ideas welcome ….

        Reply
        • Marco Schwartz
          Marco Schwartz says:

          Hello, thanks for the interesting question. For now, no it cannot. I plan to integrate web sockets in the aREST library to make these kind of things possible.

          For your second question, I would use XBee indeed, or you would probably have to use WiFi relays in the middle which is pretty inconvenient. XBee modules have such ranges, see: https://www.sparkfun.com/products/11215

          Reply
  2. Joe
    Joe says:

    Hi Marco,

    Thanks for the tutorial. I learned A LOT.

    After loading everything up on the arduino, running the webserver, and getting to your web interface I have run into a problem. When I click on the On or Off button I end up on a 404 Page not found. It seems to be attempting to load simple_relay.php which I cannot find in the Github directory. Am I missing a file?

    Reply
  3. rommel acosta
    rommel acosta says:

    how can i connect 8 relay in one arduino wifi ac power controller i need it in my thesis i have no idea for that can you give me complete instruction and materials to buy.
    thnks dude….
    hope u reply me on that pls..

    Reply
    • Marco Schwartz
      Marco Schwartz says:

      Hello,

      An Arduino can handle 8 relays without much problems, you will just have to modify the code to use 8 relays. For complete instructions and materials to buy, please send me an email directly.

      Reply
  4. David
    David says:

    In this example we have predefined SSID and Password. can’t this assigned dynamically while the device switched on .
    How can we tackle this problem? How can i make user configurable ssid and password.

    Reply
  5. afterthought
    afterthought says:

    Hi Marco,
    All parts are seemingly working-but not together.
    1)I placed the server.php into the “sites” folder. I ran it in the terminal. I get a “socket created,Socket bin OK waiting for data” on the terminal
    2) Apache,PHP,MySQL,Web sharing are on
    3)Arduino with your relay_upd sketch running and the Serial Monitor “Awaiting response…Time to connect,send and read 15008″
    4) In order to get to the relay.php I put into the browser the number from SystemPreference->Sharing->WebSharing
    address WHICH IS DIFFERENT FROM THE CONNECTION NUMBER ON THE Serial Monitor in its last 2 digits.(1.2 vs
    0.1) I click on relay.php and I get the ON and OF Buttons and 3 warning messages.

    When I click on the On or Off buttons-nothing happens. The serial monitor keeps sending the above described messages.

    Please, help
    Thanks

    Reply
  6. afterthought
    afterthought says:

    Hi Marco,
    I am still struggling to make the relay work.
    I put in a few Serial.println in the middle of your Sketch:

    Except for the first printline “rA” nothing returns from the other two.

    This is the Serial Monitor output:

    Started AP/SSID scan

    Connecting to NETGEAR96…Waiting to connect…Connected to WiFi network!
    Requesting address from DHCP server…OK
    rÁ=

    Attempting connection…
    Connect to 192.168.1.2:9999
    connected!
    Issuing request…
    Awaiting response…Time to connect, send & read:
    15010
    rÁ=

    Attempting connection…
    Connect to 192.168.1.2:9999
    connected!
    Issuing request…
    Awaiting response…Time to connect, send & read:
    15011
    rÁ=

    This is the part of your Sketch which was modified by placing in 3 Serial.println .

    void loop() {

    // Send request to get relay state
    relayBuffer[0] = ‘r’;
    Serial.println(relayBuffer); //I put it in for checking, line 75
    send_request_udp();

    // Change relay state accordingly
    if (relayBuffer[0] == ’0′) {
    digitalWrite(relay_pin,LOW);
    Serial.println(relay_pin); //I put it in for checking, line 81
    }

    if (relayBuffer[0] == ’1′) {
    digitalWrite(relay_pin,HIGH);
    Serial.println(relay_pin); //I put this in for checking, line 87
    }
    }

    The “server_php” is puting out

    Waiting for data …
    192.168.1.4 : 1643 — rWaiting for data …
    192.168.1.4 : 1644 — rWaiting for data …
    192.168.1.4 : 1645 — rWaiting for data …
    192.168.1.4 : 1709 — rWaiting for data …
    192.168.1.4 : 1710 — rWaiting for data …
    192.168.1.4 : 1711 — rWaiting for data …
    192.168.1.4 : 1712 — rWaiting for data …
    192.168.1.4 : 1713 — rWaiting for data …
    192.168.1.4 : 1714 — rWaiting for data …
    192.168.1.4 : 1715 — rWaiting for data …
    192.168.1.4 : 1716 — rWaiting for data …
    192.168.1.4 : 1717 — rWaiting for data …
    192.168.1.4 : 2211 — Waiting for data …
    192.168.1.4 : 2212 — Waiting for data …
    192.168.1.4 : 2213 — Waiting for data …
    192.168.1.4 : 2214 — Waiting for data …

    There is nothing in the “relay_state.txt” file.

    Where do I have the problem??? I would appreciate your help
    Many thanks

    Reply
  7. Luke
    Luke says:

    Hi Marco,

    Your site, blog and example code is very valuable and interesting, thanks for sharing your experiences :)

    I am interested in developing a system which uses the CC3000 for bi-directional communication between the Arduino and server – for example we exchange packets with the server to send a command to the Arduino, eg switch relay state, and we send packets back to the server – for example logging temperature from sensors, both at the same time, together.

    This sort of resembles your CC3000 weather station demonstration and your CC3000 relay control demonstration combined together into a single system with both relay and sensor.

    I was wondering if you might have some example code or software for this sort of application, or any suggestions or comments about what I would need to look out for in order to modify your code to handle this situation in an elegant way.

    Is it worth keeping TCP for the sensor data and UDP for the relay data, or perhaps moving both to UDP for both?

    Reply
    • Marco Schwartz
      Marco Schwartz says:

      Hello Luke,

      Thanks for your nice message ! I’ve developed what you mentioned indeed, I manage to have bi-directional WiFi transmission by running a server on the Arduino board with the CC3000 chip. However the code is not stable enough yet to publish a tutorial about it. I would suggest looking at the CC3000 server examples in the CC3000 library. I would also suggest to drop UDP and only use TCP, it is much easier to code and fast enough in the latest version of the WiFi library.

      Reply
  8. Jiose
    Jiose says:

    Hi Marco!

    I was just wondering how to get this work in TCP mode like the previous tutorial? It seems I am having problems with UDP connection. I’m new to this stuff so I was hoping I can figure how can I get this to work. Thanks! More power!

    Reply
  9. Brett
    Brett says:

    Marco,

    Marco,

    Do you have any experience with putting the CC3000 into “shut down” mode to save power? I’ve read a couple articles by TI that show systems using the CC3000 running off a battery and coming out of a shutdown,where they claim the CC3000 will transition back into RX mode in less 700ms. I don’t think the Adafruit CC3000 library supports this functionality, but was wondering if you had any suggestions? Great tutorial!

    Thanks!
    Brett

    Reply
    • Marco Schwartz
      Marco Schwartz says:

      Hello Brett, thanks! No, I never tried out this functionality with the CC3000, but you’re right it would be great to have indeed. The only suggestion I would have is to message the Adafruit people directly to request this feature!

      Reply
  10. John
    John says:

    Hi Marco! Great tutorial!

    When I connect to a WLAN where I use “WLAN_SEC_WPA2″ all works right, but when I need to use “WLAN_SEC_WEP” I can’t connect to a WLAN. I need to do something else?

    Thanks!

    Reply
  11. Guri
    Guri says:

    Hello there!

    First of all thanks for your code. I am relatively new to Arduino, so please do forgive me if I am asking some very basic questions. So far I have managed to install a server (Apache 2.2.2) and PHP. The Wifi Shield CC3000 connects to my network and then connects to DHPC Servers and even sends the data every i get the following message

    Connect to xxx.xxx.xxx.xx:80
    Connected & Data sent
    Closing connection

    However, when I go to my Localhost/Relay.PHP

    Nothing happens at all. I am not sure what am i doing wrong. Any advise/assistance will be greatly appreciated.

    Best!

    Guri

    Reply
    • Marco Schwartz
      Marco Schwartz says:

      Hello Guri,

      Thanks for your comment! By going to the relay.php file, you should at least see the two buttons of the interface. Are they not doing anything ? However, I will soon change the tutorial for a much more efficient implementation using a web server running on the Arduino board, so stay tuned !

      Reply
      • Guri
        Guri says:

        Thanks for the reply Marco!

        I see the two buttons – Yes and No, however nothing happens. I am wondering if it is how I have placed my files? Should I declare the complete path for the repository?

        I will be waiting for the update!

        thanks for sharing this, its great!!

        Best,

        Guri

        Reply
          • Guri
            Guri says:

            Thanks Marco!

            I am able to get to a point where I get “Listening for connections…” and then I press the “On” / “Off” button using the relay.html file (placed on my local server> C:\Apache 2.2.2\htdocs I have placed the update_state.php” in the same folder but nothing happens.

            I know I might have stretched your generosity a bit too far, but I am new to this and I am very keen on creating this wifi relay!

            Any assistance is greatly appreciated.

            Thanks in anticipation!

            Best,

            Guri

  12. Sam
    Sam says:

    This is awesome! I would rather put the page on a remote server that is always on. Would something like Xively work for this or maybe serve the page directly on the cc3300?

    Reply
  13. Matt
    Matt says:

    Marco,

    I have a Mac OS-X running MAMP and a Adafruit CC3000 shield trying to run your sketch for the Wi-Fi relay on an Uno. I make the connection through my AP, however the connection between my Uno and the computer server does not seem to be stable. I get this output from your program on the serial interface;

    Started AP/SSID scan
    Connecting to GreenOak(my wi-fi network)-waiting to connect–connected to wi-fi network!
    Requesting address from DHCP server…OK
    Listening for connections……..
    (then I go to my Mac and bring up the localhost:8080/relay.html on my browser and it displays the two buttons,
    I push the “ON” button, and the following output occurs:)
    HEAD / HTTP/1.1
    Content-Type:text/html
    On
    (then everything stops on the serial monitor and the Uno has to be reset to do anything else, and the relay never gets energized!).
    I have all the support files (html,php,jscript,jquery,) all in the MAMP/ htdocs file on my Mac and can not get this to work any further than this point.

    Can you give me some suggestions on how to resolve this problem, so I can make the relay turn on?
    Any help would be vastly appreciated!!!!!
    Thanks,
    Matt

    Reply
  14. Aadi
    Aadi says:

    I have a website hosted remotely. It supports PHP. How would I be able to connect using that? I am able to connect in my house with my laptop as server..i just want to use internet now.

    Reply
    • Marco Schwartz
      Marco Schwartz says:

      Hello Aadi,

      That won’t work with a distant server, the aREST API is for now only compatible with devices within your local network. To control the relay from a distant website you will need to use a service like Temboo.

      Reply
  15. golfredo
    golfredo says:

    Hello Marco, i m using one of your sketches, to send temperature readings to xively, it works just fine. but i also want to have it visualized on an LCD, (serial or not), the thing is that, when connect my lcd, i cant see the info, because on the loop, it is connecting, after a cycle it shows it but that happens every 10 seconds.

    Reply
  16. Athansios
    Athansios says:

    Hello,

    I am trying to make the example with the relay but i want to upload the html & javascript files in external webserver, not local. Can you help me please?

    Reply
  17. Kaushal
    Kaushal says:

    Hello Marco,

    I am new to these technology. Recently I am working on this project. Can you help me how to find TCP port number i.e The port to listen for incoming TCP connections? You have used port 80 here for example but how can I determine for my computer?

    Thanks

    Regards.

    Reply

Trackbacks & Pingbacks

  1. […] Open Home Automation | Wireless Relay Control with Arduino & the CC3000 WiFi chip – Open …. […]

Leave a Reply

Want to join the discussion?
Feel free to contribute!

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 class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">