Avatar of DFRobot

by

Tutorial: Using the Arduino Xboard to control a relay

July 6, 2011 in Tutorials

This project will use an arduino, an Xboard, and a pair of xbee modules to control a relay. By using a relay you will be able to control any appliance you hook up to the relay. Also, you can easily expand by adding more relays and modifying the code a little. You can see a video of us using the XBoard to control our office door.

Scope:This project is going to walk you through how to use the XBoard with xbee along with another arduino to control some objects over your local network.

By: HJS
Date: Jul-06-2011
Actuator: Relay
CPU: 2 Arduinos
Pwr source: USB or wall wart.
Input: web page interface

Hardware needed:

 

 

1. We will go through the XBoard setup first.

First you should solder on a male pin header on the Xboard for the FTDI programmer as pictured.

 

XBoard without the Headers installed

XBoard with the headers installed

Use the FTDI programmer to program the XBoard.

FTDI connected to Xboard

In the Arduino IDE go to “tools>Boards> Arduino Fio

copy and paste the Xboard code on to the Arduino IDE.

#include <Client.h>
#include <Ethernet.h>
#include <Server.h>
#include <Udp.h>
#include <SPI.h>
/*
 * Web Server
 *
 * A simple web server: Displays a button to open/close
 * a door and door status
 */
 //-----------------------BEGIN Variable setup -------------------------------

String readString = String(30); //string for fetching data from address
boolean LEDON = false; //LED status flag

int state;
int val=0;

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] =  {
  192, 168, 0, 177 }; //Change your IP Address here
Server server(80); //Standard HTTP server port

//-----------------------END Variable setup-------------------------------

void setup()
{
  pinMode(4, OUTPUT);    

  Ethernet.begin(mac, ip);
  server.begin();
  delay(100);
  Serial.begin(57600);  //XBee module Baud rate
  delay(100);
  }
void loop()
{
//---------------Web Server initialization------------------------------
  Client client = server.available();
  if (client) {

    boolean current_line_is_blank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if (readString.length() < 100)
      {

        readString += c;
      }
///////////Check button status to determine actions to take for submit button///////////////
       if(readString.indexOf("IO=1") >0){ // If door open request sent;
                                          // send instruction to remote arduino
             if (LEDON== false){          //Ensure it only send the info once
             //led has to be turned ON
             LEDON = true;                //Change LED state to print on the page
             Serial.print('G');           //Send command to remote Arduino
            }
           }
           if(readString.indexOf("IO=0") >0){//Same as above but not used in
                                             //this application
           if (LEDON== true){
             //led has to be turned OFF
             LEDON = false;
             Serial.print('K');
           }
           }
///////////////Finish checking and actions for submit button//////////////////

//------------------Standard web Server Jargon-------------------------------
        if (c == 'n' && current_line_is_blank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: html");
          client.println();
          client.println("<html>");
          client.println("<head>");
          client.println("<title>Xboard interface--Door control</title>");
          client.println("</head>");
          client.println("<body>");
          client.print("welcome to DFRobot"); //Print your own message here
          client.println("<br />");
          client.print("//*************************************");
          client.println("<br />");
          client.println("<br />");
          client.print("//*************************************");
          client.println("<br />");
          client.println("<br />");
          client.print("<form>");
          client.print("<input type=radio name=IO value=1 /> Open<br />");
          client.print("<input type=submit value=Submit </form><br />");
          client.println("</body>");
            break;
            }

        if (c == 'n') {
          // we're starting a new line
          current_line_is_blank = true;
        }
        else if (c != 'r') {
          // we've gotten a character on the current line
          current_line_is_blank = false;
        }
      }
    }
//------------------END Standard web Server Jargon-------------------------------

//-----------------Print door status on web page and auto refresh----------------
     if (LEDON){
          //printing LED status
         client.print("<font size='5'>DOOR status: ");
         client.println("<font color='green' size='5'>OPEN");
         client.println("<META HTTP-EQUIV=REFRESH CONTENT=2;url=http://192.168.0.177/>"); //Autorefresh
                        //Auto-refresh the site after 2 seconds to reset the door status to closed
     }
     else{
          client.print("<font size='5'>DOOR status: ");
          client.println("<font color='grey' size='5'>CLOSED");
     }
          client.println("<hr />");
          client.println("<hr />");
          client.println("</body></html>");
          //clearing string for next read
          readString="";
//-----------------END Print door status on web page and auto refresh----------------
    client.stop();
  }

/*Routine to read response from remote Arduino
 *and light local LED on PIN4
 */
   if (Serial.available() > 0) {
    val = Serial.read();
    if (val == 'H') { //These values ('H')can be changed to what ever you want
                      //just make sure you change them in both the server
                      //program and the client program
      digitalWrite(4, HIGH);
      delay (20);
     }
    if (val == 'L') {
      digitalWrite(4, LOW);
       delay (20);
    }
   }
}

Modify the IP address to fit your local network requirements. 192.168.X.177 You should check what your local IP address is and set the “X” to the same number as your network, usually “x=1″. Also,  modify the Serial baud rate to your Xbee module’s speed.

Now upload the sketch, once that is done, you can plug the xboard in to your router using the CAT5 cable. Also, you can now mount the XBee module (remember to remove it every time you want to upload a sketch). Make sure you supply power to the XBoard.

You can now test your webserver by pointing your web browser of choice to: 192.168.X.177
A plain text site should come up with some control options.

You can now set the XBoard aside. We are done with it.

2. Setting up your arduino.

You will need some sort of Xbee adaptor for the arduino. I recommend the DFRobot expansion shield as it will also make hooking up additional sensors and buttons easier.
But you could aslo use an Xbee USB adapter (you will need to solder on the header to hook it up to the arduino).

First lets  modify the Serial baud rate to your Xbee module’s speed. Then upload the sketch on to the arduino.

/*
 This example code is in the public domain.
*/
const int RELAY=2;
int val;

void setup() {
  pinMode(RELAY, OUTPUT);
  pinMode(13, OUTPUT);
  Serial.begin(57600);
  delay(500);
 Serial.print('L');
 digitalWrite(13, HIGH); //indicates locked positon
}

void loop() {

 if (Serial.available() > 0) {
    val = Serial.read();
    if (val == 'G') //If a 'G' is received unlock the door
    {
       Serial.print('H');//respond to server with aknowledgement
       digitalWrite(13, LOW); //indicates an unlock
      digitalWrite(RELAY, HIGH);//actuate relay to unlock the door
      delay (500);
      digitalWrite(RELAY,LOW); //disengage relay
      digitalWrite(13, HIGH); //turn on LED to indicate locked mode
      Serial.print('L'); //respond to server notifying door is locked
    }
    }

}

/* Note: you could add functionality to your project by adding a button on the outside of the door to function as a door bell.
additionally you would need some sort of notifier either on the Xboard (Spkr or LED or both) or on the webserver (blinking text).
*/

Once the code has finished uploading you can plugin the Xbee and relay.
The relay has been set to digital pin 2 on the Arduino so please hook up the relay’s data pin to pin 2 on the Arduino or modify the sketch to fit your requierments.

3. Test the whole shebang!

At this point hopefully you have been able to open the web interface through your browser. Now you should be able to click on the “open” and “submit” button and you should here the relay make a clicking sound which means everything is working! YAY!

Here is a video of us using the Xboard to open the Office door which is locked via a magnetic door lock. :)

If something is wrong it could be due to the Xbees not being paired correctly.

 

This is a simple project to show off the new XBoard by DFRobot. If you have any other ideas for the Xboard please let us know in the comments below.

 

Share on FacebookShare on TwitterPin it on PinterestDigg ThisSubmit to reddit

12 responses to Tutorial: Using the Arduino Xboard to control a relay

  1. As a Newbie, I am continuously exploring online for articles that can aid me. Thank you

  2. Is Arduino x board similar to ethernet shield?

    • Hi,

      It is similar, all of the Arduino Ethernet samples included in the Arduino IDE are compatible with the Xboard.

      • is it possible If I’m not using Xbee for my other project using Xboard ?

        are we still use same code to setup Xboard (“We will go through the XBoard setup first”)
        like we use xbee ?

        thank you

  3. Hi!
    Just received this board and it’s great!
    Open the package, plug and run!
    On this tutorial, it says:
    [ In the Arduino IDE go to “tools>Boards> Arduino Fio” ]
    But Arduino Fio works with 8MHz and Xboard with 16MHz, thus a serial communication with a pc didn’t work.
    I’ve solved it by choosing “tools>Boards> Arduino Pro or Pro Mini 5V16MHz w/ Atmega328″
    Is this the best option? is there anything else we need to take into account? (differences between Pro and Xboard)
    Thanks, anf great work!

    • We updated the XBoard to a faster crystal and the optiboot bootloader. Then new version will not work with FIO, but it will work fine with Arduino Pro selection.

  4. Cześć wszystkim na http://www.dfrobot.com.
    Jestem tutaj pierwszy raz na forum, i chciałem powiedzieć Witam.
    Nie mam pewności czy to odpowiednie miejsce, mimo wszystko witam serdecznie forumowiczów ;)

  5. This genuinely responded to our problem, many thanks!

  6. Hi, Just received my xboard and found your tutorial with no problem but the *.jpg pictures are not displaying. The error code is ‘multisite support not enabled’. Could you please fix this oversite. I need to see how/where to hook up the ftdi programmer I have. Thanks. Looks to be a great product.

  7. Thanks for the express lane education and product demo – it worked out of the box and after some bling – simply put – makes many things I already have into even more expensive bookends (im getting more when I can afford it).

    I reused the X-Board v1 example code here, with Arduino 1.0 IDE, and after very minor changes for a c user, was able to flash and run modified code onto X-Board v2 without issue (no need to un-plug device from Xbee socket).

    Some changes are as follows:-

    Moved #include <SPI.h> library include to fist line of code, before the Ethernet.h library include. Remarked the Server.h, Client.h, and Udp.h library includes. Added the servo.h library include.

    Changed String(30) to be String(98)

    Added a server.begin(); into the start of the loop () function (correcting the Ethernet client/server 35 secT/O, and allowing the Heart beat to return = no more solid red light).

    Corrected escape code by adding the (wiki formatted) missing back slash symbol into string tests at c == 'n', and c == 'r'.

    Remarked the HTML body close element tag from the ‘Standard web Server Jargon‘ code block, as there is another in the ‘Print door status on web page and auto refresh‘ code block.
    As a personal note:- Added xhtml, and I moved the lower Print door stat code block into the Std web server Jargon code block so they are now one, with other minor changes like calling the client.stop(); before the break;.. Along with change of original client.stop(); into a client.flush();

    Able to flash with tools::Boards::Uno but because im fussy I reused the example in DFRobot.com community posts, and modified my boards.txt file to add another Uno option with xboard.build.variant=eightanaloginputs

    One last thing I did was to pat my self on the head, this product is rock solid and kicks back hard when kicked. Has to be one of the best things that I have been lucky enough to find on the Internet in years.

    Not posting link to modified code, as its not been tested/approved for use by the Mod or DF. I am happy to help out and post code as needed, when I have time.

    PS: wiki-formatting may change correct c code into junk.

    :-)

    • Forgot 2 things;

      The MAC address – it may be best to use a even number for the first value. Something like 0×00 is a even value (and is used by NIC cards), while 0xDE takes some brain cells to work out (I dont have many left; As this add-on post confirms). Not sure if this is an issue but it could make a difference to someone who cant ping (could be the 35secT/O and not this).

      XP and before should have a DHCP router or something that performs DHCP services on the network/client/xboardv2 route. Windows 7 home with a CAT-cross-over-cable works without change to DHCP (as long as your in scope, etc). Only bothered to set IP and MAC addresses on the X-Boardv2. Am wondering if any future v3 will have pre-burnt MAC?

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>

 
You will need to log on to vote!