Saturday, October 19, 2013

Using Raspberry Pi as IRC Client

I wanted to be continually logged into IRC and also use it as a logging client for message on the #doothings IRC channel.
What better way than to use Raspberry Pi?

Steps for using Raspberry Pi as IRC Client

  1. We will use IRSSI, whici is a terminal based IRC client.
  2. Install it by running sudo apt-get install irssi
  3. Also install screen by running sudo apt-get install screen
  4. screen and then press Enter
  5. IRSSI irssi
  6. /server irc.freenode.net
  7. /join #doothings
  8. Now you have logged-in to the #doothings IRC Channel.
  9. To Detach from the Client. Press Ctrl + a and then d
  10. You should be back to the terminal window.
  11. To rejoin the IRC window run screen -r

Settings for irssi

  1. To ignore joins / quits / nicks changes on a specific channel.
    /ignore -channels #chan1,#chan2,#chan3 * JOINS PARTS QUITS NICKS
  2. Auto Connect to a Server on startup
    /SERVER ADD -auto -network IRCnet irc.freenode.net 6667
  3. Auto Join to Specificed channels
    /CHANNEL ADD -auto #doothings IRCnet
  4. To Keep logging all these conversations
    /SET AUTOLOG ON
  5. To set Nicks and Real Name etc.
    /SET -> This should show all existing configured parameters.
    To change these just say
    /SET param-name value like /SET nick nism-pi
  6. /SAVE to save the entire configuration.
    All these steps if you think need to be improved, you can send in a pull request here https://github.com/iot-pune/raspberrypi/blob/master/IRC-client.md

Thursday, October 10, 2013

Using Raspberry Pi as a torrent client.

Using Raspberry Pi as a torrent client

Advantage of using raspberry pi as a torrent client is that it uses very less power. For a comparison,

Power consumption of Raspberry Pi device is very less. (5V, 500 mA (2.5W) without any devices connected).

So obviously, its a better solution for downloads that take a long time. and better to keep raspberry pi always on over a desktop / laptop.

Steps

  1. sudo apt-get update
    sudo apt-get upgrade
  2. sudo apt-get install deluged
    sudo apt-get install deluge-console
  3. Start the deluge daemon by running deluged
    It creates the necessary files that we can now edit.
    Stop this after some time (5-10 seconds) by running sudo pkill deluged
  4. Now edit the auth file. But first create a backup.
    cp ~/.config/deluge/auth ~/.config/deluge/auth.copy`
    Editing the auth file. nano ~/.config/deluge/auth
    Add a line at the bottom of the configuration file with the following convention: user:password:level
    Example : pi:pi:10 (10 is full-access/administrative level for the daemon)
  5. Now let's update the settings for allowing remote connections.
    deluged
    
    deluge-console
    
    config -s allow_remote True
    
    config allow_remote
    
    exit
    
  6. Restart deluged for this configuration to take effect.
    sudo pkill deluged
    
    deluged
    
  7. Intall deluge-web to be able to access it from remote.
    sudo apt-get install python-mako
    
    sudo apt-get install deluge-web
    
    deluge-web
    
  8. Access deluge-web from a remote machine on the same network.
    Navigate to http://<rasberrypi-ip>:8112/ .
    You have a torrent server at your service!
    Enter the password as deluge and immediately change it.
  9. In addition to accessing the web-gui from you can also access it from an Android application like Torrent Manager.
    While using this app just provide the password which was changed in step 8.

    You can take a look at the RaspberryPi code repository of IOT-Pune

Wednesday, October 2, 2013

Home Automation with RaspberryPi Python - Django


Home Automation with RaspberryPi Python - Django

So after attending the 2 meet-ups for IOT-Pune. I got a Raspberry Pi and decided to play around with it a little bit. The following post will walk you through the steps needed to turn on/off a light bulb.

Things needed
1. Raspberry Pi
2. Relay switch
3. light bulb with wire to plug into main power supply

Lets us start!!!

  • sudo apt-get install python-dev python-setuptools
  • sudo pip install django
  • django-admin.py startproject mysite
  • cd mysite/
  • django-admin.py startapp ledblink
  • cd mysite
  • open file named setting.py and add the ledblink app in the INSTALLED_APPS so that it looks like this
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'ledblink',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)
  • add this to the templates dir make sure you  add import os at the top of the page
TEMPLATE_DIRS = (
     os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)
  • cd ledblink
  • open the views.py file and change it to this
from django.shortcuts import render
from django.http import HttpResponse
import RPi.GPIO as GPIO
import time


GPIO.setmode(GPIO.BOARD)
GPIO.setup(18,GPIO.OUT)


def blinker(request):
    if 'on' in request.POST:
        GPIO.output(18,1)
    elif 'off' in request.POST:
        GPIO.output(18,0)
    return render(request,'control_page.html')
    
  • Let us add the template control pages so go ahead and create a templates directory in your ledblink app and add the following html code and name it control_page.html
<!DOCTYPE html>
<html>
<head>

</head>
<body>

<form action="" method="post">{% csrf_token %}
<input type="submit" name="on" value="on" />
<input type="submit" name="off" value="off" />
</form>
</body>
</html>

  • now let us create a url that links to this view. Goto the urls.py file in mysite directory cd ../mysite
from django.conf.urls import patterns, include, url
from ledblink.views import blinker
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    url(r'^ledblink/$',blinker),
    # Examples:
    # url(r'^$', 'mysite.views.home', name='home'),
    # url(r'^mysite/', include('mysite.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
)
  • Goto main folder of the project where the manage.py file is located and run the following command
sudo python manage.py runserver 192.168.0.106:8000

open up a web browser and type http://192.168.0.106:8000/ledblink/ in the address bar and you should have the following result




now lets get to the part where we connect every thing to the raspberry pi.



  • Sorry I couldn't get a better picture even though Nishant suggested to take the book out. :P But yoy connect the 5V out of the Pi that is pin 2 to the positive on the relay . The ground pin 6 to the regative of the relay and finaly GPIO18 to the corresponding pin on the relay board.

  • Plug the bulb in the main power supply. Go ahead and try turning on the bulb from the web Browser


Friday, August 2, 2013

Arduino with real time web application using web sockets


Purpose of this experiment is to demonstrate real time aspect of the web to pull data from an Arduino.

Arduino can be clubbed together with several sensor to receive data of surroundings and do anything with data. Once you have data with you, imagination is the limit like sending surrounding temperature to Twitter as tweet, check mail when you come close to your computer, turn off volume when an ad comes on TV etc. 

Following POC shows use of Arduino with LDR sensor to plot real time graph of Light around you.

You will need following things for our project : 

  1. Arduino UNO or Freeduino 
  2. LDR or photo-resistor 
  3. 10k ohm resistor (Voltage divider)
  4. Computer 
LDR is basically a simple light sensor that changes the resistance with light. We will measure amount of voltage is on LDR using analog read of Arduino. With Arduino analog read, 5v is highest value read as 1023 and 0v is lowest value read as 0.

Let connect things 



Connect your LDR and resistor as shown in figure., 

Now coding part,
The idea here is to read sensor reading using Arduino and send them to computer for further processing, so we will read sensor data and send it serial port of computer where Arduino is connected. 

filename: LDR.ino

int LDR = 0;

void setup(){
  Serial.begin(9600);
}

void loop(){ 
  int Reading = analogRead(LDR);
  Serial.println(Reading);
  delay(250);
}


Code is pretty self-explanatory. Now the web part here we will use websocket for reading values and plotting real time graph out of read values. We will not discuss websocket and its implementation as this is out of scope of this project (which itself is big topic for discussion).

In order to run the code you need to install Python with following modules 
  1. geventwebsocket.handler 
  2. gevent 
  3. serial 
Python provides module called 'serial' which enables to read and write to serial port of computer.
Here websocket server written in Python, 

filename: LDRreader.py 

from geventwebsocket.handler import WebSocketHandler
from gevent import pywsgi
import gevent
import serial

# PORT used for websocket client
PORT = 8090
import os
import random
def handle(ws):
    """  This is the websocket handler function.  Note that we
    can dispatch based on path in here, too."""
    serial_read = serial.Serial('COM31', 9600)
    if ws.path == '/data':
        for i in xrange(10000):
            signal = serial_read.readline()
            ws.send("0 %s %s\n" % (i, signal))
            print "0 %s %s\n" % (i, signal)
            gevent.sleep(0.1)

def app(environ, start_response):
    if environ['PATH_INFO'] == '/test':
        start_response("200 OK", [('Content-Type', 'text/plain')])
        return ["blah blah"]
    elif environ['PATH_INFO'] in ("/data"):
        handle(environ['wsgi.websocket'])
    else:
        start_response("404 Not Found", [])
        return []


def main():
print "In main, Starting WSGIServer"
server = pywsgi.WSGIServer(('0.0.0.0', PORT), app,
handler_class=WebSocketHandler)
try:
server.serve_forever() 
except:
pass

if __name__ == "__main__":
main()

Now websocket client which will actual receive data and plot it on web browser, you need this library for plotting graph. Download and keep in same directory where LDR.html is present. 

filename: LDR.html

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="jquery.flot.js"></script>
<script>
var iets = "";
window.onload = function() {
    var data = {};
try {
var s = new WebSocket("ws://localhost:8090/data");
}
catch (e) {
var s = new MozWebSocket("ws://localhost:8090/data");
}
    s.onopen = function() {
        console.log('Websocket Open');
        s.send('hi');
    };
    s.onmessage = function(e) {

      console.log('got ' + e.data);
      var lines = e.data.split('\n');
      for (var i = 0; i < lines.length - 1; i++) {
        var parts = lines[i].split(' ');
        var d = parts[0], x = parseFloat(parts[1]), y = parseFloat(parts[2]);
        if (!(d in data)) data[d] = [];
        data[d].push([x,y]);
      }
      var plots = [];
      for (var d in data) plots.push( { data: data[d].slice(data[d].length - 200) } );
      $.plot( $("#holder"), plots,
              {
                series: {
                  lines: { show: true, fill: true },
                },
                yaxis: { min: 0 },
              } );

      s.send('');
    };
};
</script>
</head>
<body>
<h3>LDR Plot</h3>
<div id="holder" style="width:800px;height:350px"></div>
</body>
</html>

Now start our websocket server using 
# python LDRreader.py  

now go to browser and type http://localhost:8090 and bam !!! 

You will see plotting graph.


Sunday, July 21, 2013

Getting started with the BeagleBone Black

Arduino is the most ubiquitous development platform, period. Anyone who has entered the world of DIY electronics most probably started off with an Arduino. The reasons for this are it's ease, the enormous amount of documentation in the form of wikis, code samples, video tutorials, etc.
But there comes a point when the Arduino just isn't enough for your needs. You need more muscle.

Enter BeagleBone Black.
A 1Ghz, 512MB RAM "mini-computer" with 2 GB of onboard memory.
At $45, its in the competitive price range of the RaspberryPi (35$), pcDuino(59$), etc.

It comes from one of the oldest players in the Embedded Linux worlds, Beagleboard.org. It's their 4th ARM dev board, and the 1st in this price range (previous boards were Beagleboard, Beageboard xM and the Beaglebone white).

Pros as compared to the Pi:
Since the Pi has gained a lot of popularity, it's easier to compare it with that.

  • More processing power(1Ghz as compared to 700Mhz)
  • No need for SD card( has 2 GB of onboard flash, which is more than enough to run your fav Linux distro. Of course it has uSD card slot, just in case you think you need more space)
  • No need for external power supply( directly plugs in to your laptop/PC and runs like the Arduino)
  • Has a LOT more interfaces as compared to the Pi( more GPIOs. Has onboard PWM, ADC too unlike the Pi)
    Full list here http://circuitco.com/support/index.php?title=BeagleBoneBlack
  • Has many many capes available.
    http://circuitco.com/support/index.php?title=BeagleBone_Capes
    Capes are analogous to shields for Arduino.
    It's not always possible to give all kinds of interfaces on the board. So based on your project needs, you can use one of the available capes to add even more functionality.

    You can of course find a lot more comparisons if you ask Google ;) 
Getting started:
Since the BBB rocks Linux on board, you don't really have any restriction on the kind of programming language you choose. 
Any kind of input/output is done by using 

Links to get started:
  1. SRM (System Reference Manual. Read through this once to get familiar with all the features and interfaces.)
  2. Wiki
  3. Mailing list (this should be your first stop for any issues once you get your Black. It's very active and very helpful. Remember to search previous posts before posting your doubt, someone might have had the same doubt)
  4. IRC - #beagle on Freenode
  5. Derek Molloy's blogs ( has some really cool tutorials, videos, etc to get started)
  6. Userspace Arduino project
Get it:
Some of the Indian shops which will ship you a Black are
  1. http://tenettech.com/product/2912/beaglebone-blackhttp://tenettech.com/product/2912/beaglebone-black
  2. http://shop.sumeetinstruments.com/index.php?route=product/product&keyword=beaglebone+black&category_id=0&product_id=965
  3. http://www.crazypi.com/index.php?route=product/product&product_id=79&search=beagle

    Note: these guys don't really have permanent links to their products. So if above links don't work, try searching for them from the Homepage.
DigiKey, Adafruit, element14, etc are the official distributors for the BBB. More info about them here http://beagleboard.org/Products

Saturday, July 13, 2013

Open Source Home Automation Project using Arduino UNO + Ethernet Shield



This is Open Source Home Automation Project based on Arduino Uno and Arduino Wiznet based Ethernet shield.





How Does it Work

The main brain for this project is Arduino UNO Board along with Arduino Ethernet Shield to give it a wireless connectivity.Arduino runs a code to control a Relay board according to the input and also serves a web page through which respective output to the relay board can be controlled.Through relay controller board we can control lamps, tubes or any AC power sockets.
You will be able to control all of your AC Appliances wirelessly with the help of any WIFI Enabled device.

STEP 1:


Relay Controller Board Build Tutorial:

Quantity of the components depends upon how many channels you want e.g. if you want to control more than one light then you will have to add that much number of relays on your controller board.
Here is the material list which will be needed to build the board: (Quantity of the components given for making 1 channel relay controller)


Sr.NoComponent NamesQuantity
1Relay (I have used GOODSKY RWH-SH-105D Relay)1
2Transistor 2N39041
31K Resistor2
410K Resistor1
51N4148 Diode1
6Red Led 3mm1
73 Pin PCB Mount Connector1
81 Pin PCB Mount Connector1


Above components are for making of single controller board you can multiply number of the components depending on how many relay controller you want.







Here in the circuit diagram Pin no.2 will be connected to the arduino control output pin and other two will be connected to +5V and Gnd accordingly.
After soldering all of your components according to the above circuit diagram the board should look like this.




Front View




Rear View



This is single relay controller board. You can extend this to as many as you want. I have made 5 channel relay controller board as below.







Note:

All the usual warnings apply: Mains voltage (120VAC or 220VAC) can kill you. This project, if done incorrectly, could certainly burn down your house. Do not work on or solder to any part of a project while it is plugged into the wall socket - just unplug it before modifying anything!


STEP 2:

Getting IP Address Of Arduino Ethernet Shield:


 Mount your Arduino Ethernet shield on Arduino Uno as shown:





Now connect your Uno Board to PC with USB cable and open Arduino IDE. After Opening up you will find blank Arduino window. Now go to File--> Example --> Ethernet --> dhcp address printer sketch. Your Ethernet shields MAC address is printed on back of it as follow you will need this in DHCP ADDRESS PRINTER code to get the IP address of your Ethernet shield.



In DHCP address printer sketch put your MAC address as given on back of the Ethernet shield and upload it to the Arduino board.




After finished uploading connect Arduino Ethernet shield to internet with Ethernet cable once connected then open up you serial monitor of Arduino IDE the IP address allotted to your Ethernet shield will be displayed e.g. (xxx.xxx.x.xxx) note it down somewhere because you are going to need this in further codes.


STEP 3:


BuildingMainCircuitConnection :

Now we are ready with our Relay controller board. So, it’s time to move on to the Main Circuit Connections. Here I have given the pin configuration for the whole Autohome Project.

Arduino Digital Pin No.Pin Usage
4will be used for Infrared Receiver
5used as Output Pins to control Relays
6used as Output Pins to control Relays
7used as Output Pins to control Relays
8used as Output Pins to control Relays
9used as Output Pins to control Relays
10will be used by Arduino Ethernet Shield
11will be used by Arduino Ethernet Shield
12will be used by Arduino Ethernet Shield
13will be used by Arduino Ethernet Shield

Note: For relays it is recommended to power it from separate source not from Arduino (I have powered it from Arduino only but since here we are working with single board. As board number increases Arduino won’t be able to supply sufficient power to the boards.)
Here is the connection diagram:



In this way you can do necessary soldering work to make following connection.
You can also make your own protoshield which can easily fit on top Arduino like this:






Once you finish soldering stuff, now you are ready for your main code upload.


STEP 4:

Uploading Arduino AutoHome code to the Board:

Here is the Arduino AutoHome code just copy and paste it into your Arduino IDE sketch.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
//for use with IDE 1.0
//open serial monitor to see what the arduino receives
//use the \ slash to escape the " in the html
//for use with W5100 based ethernet shields
// this project is hosted at
// http://code.google.com/p/arduino-autohome/
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x78, 0xE0 }; // <------- PUT YOUR MAC Address Here
byte ip[] = { 192, 168, 1, 102 }; // <------- PUT YOUR IP Address Here
byte gateway[] = { 192, 168, 1, 254 }; // <------- PUT YOUR ROUTERS IP Address to which your shield is connected Here
byte subnet[] = { 255, 255, 255, 0 }; // <------- It will be as it is in most of the cases
EthernetServer server(80); // <------- It's Defaulf Server Port for Ethernet Shield
String readString;
//////////////////////
void setup()
{
  pinMode(6, OUTPUT); // Pin Assignment through which relay will be controlled
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  
  
  //start Ethernet
  
  Ethernet.begin(mac, ip, gateway, subnet);
  server.begin();
  
  //enable serial data print
  
  Serial.begin(9600);
  Serial.println("server LED test 1.0"); // so that we can know what is getting loaded
}
void loop()
{
   
  
  // Create a client connection
  EthernetClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        
        //read char by char HTTP request
        if (readString.length() < 100) {
          //store characters to string
          readString += c;
          //Serial.print(c);
        }
        //if HTTP request has ended
        if (c == '\n') {
          ///////////////
          Serial.println(readString); //print to serial monitor for debuging
          /* Start OF HTML Section. Here Keep everything as it is unless you understands its working */
          
          client.println("HTTP/1.1 200 OK"); //send new page
          client.println("Content-Type: text/html");
          client.println();
          //client.println("<meta http-equiv=\"refresh\" content=\"5\">");
          client.println("<HTML>");
          client.println("<HEAD>");
          client.println("<meta name='apple-mobile-web-app-capable' content='yes' />");
          client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />");
          client.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://arduino-autohome.googlecode.com/svn/trunk/autohome.css\" />");
          
          
          client.println("</HEAD>");
          client.println("<body bgcolor=\"#D0D0D0\">");
          
          client.println("<hr/>");
          client.println("<hr/>");
          client.println("<h4><center><img border=\"2\" src=\"https://lh3.googleusercontent.com/-C6BoJrRUFko/UEUFeCwkvdI/AAAAAAAAAOc/E7gcYvPV6r4/s960/Logo.jpg\" /></center></h4>");
          client.println("<hr/>");
          client.println("<hr/>");
          
          client.println("<br />");
          client.println("<br />");
          client.println("<br />");
          client.println("<br />");
          client.println("<br />");
         
         // Relay Control Code
          client.println("<a href=\"/?relay1on\"\">Turn On Light 1</a>");
          client.println("<a href=\"/?relay1off\"\">Turn Off Light 1</a><br />");
          
          client.println("<br />");
          client.println("<br />");
          client.println("<br />");
          client.println("<br />");
          
          client.println("<a href=\"/?relay2on\"\">Turn On Light 2</a>");
          client.println("<a href=\"/?relay2off\"\">Turn Off Light 2</a><br />");
          
          client.println("<br />");
          client.println("<br />");
          client.println("<br />");
          client.println("<br />");
          
          client.println("<a href=\"/?relay3on\"\">Turn On Light 3</a>");
          client.println("<a href=\"/?relay3off\"\">Turn Off Light 3</a><br />");
          
          client.println("<br />");
          client.println("<br />");
          client.println("<br />");
          client.println("<br />");
          
          client.println("<a href=\"/?relay4on\"\">Turn On Light 4</a>");
          client.println("<a href=\"/?relay4off\"\">Turn Off Light 4</a><br />");
          client.println("<br />");
          client.println("<br />");
          
          
          
         
            // control arduino pin via ethernet Start //
          
          
          if(readString.indexOf("?relay1on") >0)//checks for on
          {
            digitalWrite(6, HIGH); // set pin 4 high
            Serial.println("Led On");
            client.println("<link rel='apple-touch-icon' href='http://chriscosma.co.cc/on.png' />");
            //client.println("Light 1 Is On");
            client.println("<br />");
        }
          else{
          if(readString.indexOf("?relay1off") >0)//checks for off
          {
            digitalWrite(6, LOW); // set pin 4 low
            Serial.println("Led Off");
            client.println("<link rel='apple-touch-icon' href='http://chriscosma.co.cc/off.png' />");
            //client.println("Light 1 Is Off");
            client.println("<br />");
        }
          }
          
          if(readString.indexOf("?relay2on") >0)//checks for on
          {
            digitalWrite(7, HIGH); // set pin 4 high
            Serial.println("Led On");
            client.println("<link rel='apple-touch-icon' href='http://chriscosma.co.cc/on.png' />");
            //client.println("Light 2 Is On");
            client.println("<br />");
          }
          else{
          if(readString.indexOf("?relay2off") >0)//checks for off
          {
            digitalWrite(7, LOW); // set pin 4 low
            Serial.println("Led Off");
            client.println("<link rel='apple-touch-icon' href='http://chriscosma.co.cc/off.png' />");
            //client.println("Light 2 Is Off");
            client.println("<br />");
          }
          }
          
           if(readString.indexOf("?relay3on") >0)//checks for on
          {
            digitalWrite(8, HIGH); // set pin 4 high
            Serial.println("Led On");
            client.println("<link rel='apple-touch-icon' href='http://chriscosma.co.cc/on.png' />");
           // client.println("Light 3 Is On");
            client.println("<br />");
          }
          else{
          if(readString.indexOf("?relay3off") >0)//checks for off
          {
            digitalWrite(8, LOW); // set pin 4 low
            Serial.println("Led Off");
            client.println("<link rel='apple-touch-icon' href='http://chriscosma.co.cc/off.png' />");
            //client.println("Light 3 Is Off");
            client.println("<br />");
          }
          }
          
          
           if(readString.indexOf("?relay4on") >0)//checks for on
          {
            digitalWrite(9, HIGH); // set pin 4 high
            Serial.println("Led On");
            client.println("<link rel='apple-touch-icon' href='http://chriscosma.co.cc/on.png' />");
            //client.println("Light 4 Is On");
            client.println("<br />");
          }
          else{
          if(readString.indexOf("?relay4off") >0)//checks for off
          {
            digitalWrite(9, LOW); // set pin 4 low
            Serial.println("Led Off");
            client.println("<link rel='apple-touch-icon' href='http://chriscosma.co.cc/off.png' />");
            //client.println("Light 4 Is Off");
            client.println("<br />");
          }
          }
          
         // control arduino pin via ethernet End //
         
         
         
          // Relay Status Display
          client.println("<center>");
          client.println("<table border=\"5\">");
          client.println("<tr>");
          
          if (digitalRead(6))
          {
           client.print("<td>Light 1 is ON</td>");
           
          }
          else
          {
            client.print("<td>Light 1 is OFF</td>");
           
          }
          
          
          client.println("<br />");
          
          if (digitalRead(7))
          {
           client.print("<td>Light 2 is ON</td>");
           
          }
          else
          {
            client.print("<td>Light 2 is OFF</td>");
            
          }
          
          client.println("</tr>");
          client.println("<tr>");
          
          if (digitalRead(8))
          {
           client.print("<td>Light 3 is ON</td>");
           
          }
          else
          {
            client.print("<td>Light 3 is OFF</td>");
            
          }
          
         
        
         
          if (digitalRead(9))
          {
           client.print("<td>Light 4 is ON</td>");
          
          }
          else
          {
            client.print("<td>Light 4 is OFF</td>");
           
          }
          
          client.println("</tr>");
          client.println("</table>");
          
          client.println("</center>");
          
          
          
          //clearing string for next read
          
          readString="";
          client.println("</body>");
          client.println("</HTML>");
          delay(1);
          //stopping client
          client.stop();
        }
      }
    }
  }
}




Upload this code to your UNO board. Now you are ready to your your Automation Project, just plug your Ethernet shield to router and and you will be able to find the control page on the IP Address specified by in in the Arduino Code. So directly enter the  IP address in the web browser of the the device which is on the same network as that of your Arduino.

So you will have the control page as shown below:





As you understand the code you can modify to your need.
So enjoy controlling things wirelessly..