<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Beyond All Repair &#187; Arduino</title>
	<atom:link href="http://beyondallrepair.com/category/electronics/arduino-electronics/feed/" rel="self" type="application/rss+xml" />
	<link>http://beyondallrepair.com</link>
	<description>The goings on of a computer scientist</description>
	<lastBuildDate>Tue, 30 Nov 2010 00:04:39 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>AVR Programming: Flashing LEDS</title>
		<link>http://beyondallrepair.com/2010/11/avr-programming-flashing-leds/</link>
		<comments>http://beyondallrepair.com/2010/11/avr-programming-flashing-leds/#comments</comments>
		<pubDate>Sat, 13 Nov 2010 15:16:34 +0000</pubDate>
		<dc:creator>Freud</dc:creator>
				<category><![CDATA[Arduino]]></category>
		<category><![CDATA[AVR]]></category>
		<category><![CDATA[Electronics]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[arduino]]></category>
		<category><![CDATA[atmega48]]></category>
		<category><![CDATA[avr]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://beyondallrepair.com/?p=100</guid>
		<description><![CDATA[I&#8217;ve had an arduino for a while now, and I&#8217;ve done a few projects that I would like to deploy.  Rather than using an arduino at about £16 per board, I decided I&#8217;d try to learn how to program AVR chips, the price of which varies, are in the range of £2-£5/chip.  This tutorial will [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve had an arduino for a while now, and I&#8217;ve done a few projects that I would like to deploy.  Rather than using an arduino at about £16 per board, I decided I&#8217;d try to learn how to program AVR chips, the price of which varies, are in the range of £2-£5/chip.  This tutorial will discuss what I&#8217;ve done so far &#8212; namely, the chip equivalent of &#8220;hello world&#8221; (flashing an LED) and using the timers for PWM (pulse-width modulation), which will be coming up in another tutorial.</p>
<p>The AVR chip I&#8217;m using in this tutorial is the ATMega48, which I&#8217;m programming using the <a title="USBTinyISP" href="http://www.ladyada.net/make/usbtinyisp/">USBTinyISP</a>, which I bought in kit form from <a href="http://www.adafruit.com/index.php?main_page=index&amp;cPath=16">Adafruit</a>.  Below is a photograph of my setup.</p>
<div id="attachment_104" class="wp-caption aligncenter" style="width: 501px"><a href="http://beyondallrepair.com/wp-content/uploads/2010/11/IMG_2637-1024x768.jpg"><img class="size-full wp-image-104  " title="USBTinyISP wired to an ATMega48" src="http://beyondallrepair.com/wp-content/uploads/2010/11/IMG_2637-1024x768.jpg" alt="USBTinyISP wired to an ATMega48" width="491" height="369" /></a><p class="wp-caption-text">My USBTinyISP wired to my ATMega48 chip</p></div>
<p>The black component you can see to the left of the breadboard is a ZIF socket I soldered to some header sockets, which allows me to easily program the chip and plug other wires into, of course, if you want to, you can simply plug the chip straight into some breadboard (but this puts a fair amount of force on the legs).  Below is a picture of how to wire the chip up to your programmer.</p>
<div id="attachment_102" class="wp-caption aligncenter" style="width: 430px"><a href="http://beyondallrepair.com/wp-content/uploads/2010/11/ATMega48Programmer.png"><img class="size-full wp-image-102 " title="Connecting the programmer to the ATMega48" src="http://beyondallrepair.com/wp-content/uploads/2010/11/ATMega48Programmer.png" alt="Connecting the programmer to the ATMega48" width="420" height="457" /></a><p class="wp-caption-text">Wiring diagram for connecting the ATMega48 to your ISP</p></div>
<p>I&#8217;ll assume you have your programmer installed working.  In order to compile the code we write for AVR, you&#8217;ll need the avr flavour of gcc, and also avrdude (to upload the code).  For all the windows users out there, there&#8217;s <a title="WinAVR" href="http://winavr.sourceforge.net/">WinAVR</a>, which will install all of the tools you need to compile and upload your code to the AVR chip.  I&#8217;m also using the <a title="AVR Eclipse Plugin" href="http://avr-eclipse.sourceforge.net/wiki/index.php/The_AVR_Eclipse_Plugin">AVR Eclipse Plugin</a>, which makes compiling and up loading much simpler &#8212; in their getting started guide they also walk you through compiling and uploading the code, so its a handy resource for people who would like to learn more about this.</p>
<h2>Bitwise Operations</h2>
<p>This code is a lot more low-level than what you&#8217;d use for the Arduino.  It makes fairly heavy use of bitwise operations so here&#8217;s a quick overview of the main ones we use.</p>
<h3>Bitwise OR</h3>
<p>The | character represents the bitwise OR.  It compares each bit of its parameters, and if one of those bits is 1, the output bit is 1, as is shown in the truth table below.</p>
<table>
<tbody>
<tr>
<th>p</th>
<th>q</th>
<th>p | q</th>
</tr>
<tr>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>
<p>So the operation 010 | 101 would output 111, and the output 001 | 000 would output 001.  This is useful for switching bits on when you don&#8217;t want to affect any other bits in the register.</p>
<h3>Bitwise AND</h3>
<p>The &amp; character represents the bitwise AND.  It compares each bit of its parameters, and will output a 1 only if both bits are 1, as can be seen in the truth table.</p>
<table>
<tbody>
<tr>
<th>p</th>
<th>q</th>
<th>p &amp; q</th>
</tr>
<tr>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>0</td>
</tr>
<tr>
<td>1</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>
<p>The operation 010 &amp; 101 would output 000, and 111 &amp; 010 would output 010.  A common use of the AND operator is to apply masks to values &#8212; to ensure some bits are always off.  For example if we wanted the first and third bits of a register always to be 0 (maybe setting them to 1 could signal the end of the world), when setting that register with a certain value we can simply &amp; it with the mask 010.</p>
<h3>Bitwise XOR (eXclusive OR)</h3>
<p>I&#8217;m not actually using this operator in this tutorial, but I thought I&#8217;d include it anyway, it has interesting uses &#8212; one of which is a simple encryption algorithm, which if used correctly is impossible (I believe) to break.  The ^ character represents a bitwise XOR in C, and it is similar to the OR operator above except that its output is only 1 if only one of the two input bits is 1.  See the table below.</p>
<table>
<tbody>
<tr>
<th>p</th>
<th>q</th>
<th>p ^ q</th>
</tr>
<tr>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>0</td>
</tr>
</tbody>
</table>
<h3>Left Shift Operator &lt;&lt;</h3>
<p>This operator simply shifts the bit in a variable by some number of places.  For example the operation 0001 &lt;&lt; 1  would result in the number 0010, and the number 0001 &lt;&lt; 2 would result in 0100.  If you shift a bit too far, the value will &#8216;overflow&#8217; 0001 &lt;&lt; 4  results in 0000 (assuming we&#8217;re using some 4-bit data type).  This is generally not something you want to do&#8230;  Incidentally there is also a &gt;&gt; operator, which shifts the bits of the left parameter right &#8212; i.e 0100 &gt;&gt; 1 outputs 0010.</p>
<h2>Flashing LEDs!</h2>
<p>Right, now we&#8217;ve got that over and done with, lets get our flash on.  Firstly, we&#8217;ll do this without the use of a timer (i.e. we&#8217;ll hack it out with some loops), then, in a later blog post (which should be coming soon &#8212; I just split it off from this one in order to reduce the length).</p>
<p>If you look at the <a title="Summary of the ATMega48 data sheet" href="http://www.atmel.com/dyn/resources/prod_documents/2545S.pdf">Atmel spec sheets</a> for the ATMega48, you can see that the pins on the chip are divided into 3 ports &#8212; B, C and D.  Each port, except for some reason port C, has 8 pins (C has only 7) numbered 0 to 7.   The pins are arranged as shown in the picture below (note that pins are labelled with their port letter then their pin number).</p>
<div id="attachment_113" class="wp-caption aligncenter" style="width: 310px"><a href="http://beyondallrepair.com/wp-content/uploads/2010/11/ATMega48Ports.png"><img class="size-full wp-image-113" title="ATMega48 Ports" src="http://beyondallrepair.com/wp-content/uploads/2010/11/ATMega48Ports.png" alt="The pin arrangement on an ATMega48 chip" width="300" height="289" /></a><p class="wp-caption-text">The pins on an ATMega 48 chip</p></div>
<p>Wire your LEDs to a breadboard (don&#8217;t forget your resistors), and connect their grounds to one of the spare ground pins on your programmer (see the diagram above).  We&#8217;re going to make these two LEDs flash alternately.  Connect the positive leg of one LED to C5, and the positive leg of the other LED to B1.</p>
<p>Create a C file and include the header file avr/io.h  Next create a main function that returns an int and no parameters.  In this function create a local variable int &#8220;next&#8221; and set that equal to 1.</p>
<p>The first thing we&#8217;ll need to do is to tell the chip that we want pins B1 and C5 to be outputs (similar to the pinMode function in arduino).  To do this we need to set their &#8216;Data Direction&#8217; in the Data Direction Register on the chip (DDR).  We do this by shifting a 1 bit into the &#8220;DDB1&#8243; bit of the DDRB register, and a 1 bit to the DDC5 bit of the DDRC register.  These register names take the form DDR&lt;Port Letter&gt; and the individual bits of those registers DD&lt;Port Letter&gt;&lt;Leg Number&gt;.</p>
<p>Next, create an infinite while loop in which we&#8217;ll place the code to make the LEDs flash.  To turn a pin on, you set the corresponding bit in its port&#8217;s register to 1 (and to turn it off you set it to 0).   See the next lump of code to see how you do this.</p>
<pre>#include &lt;avr/io.h&gt;

int main(void)
{
	int next = 1;
	/*Make Pin 1 of port B an output*/
	DDRB = 1 &lt;&lt; DDB1;
	/*Make Pin 5 of port C an output*/
	DDRC = 1 &lt;&lt;DDC5;

	__asm__ volatile ("nop");

	while(1)
	{
		PORTB = next &lt;&lt; PB1;
		PORTC = (1-next) &lt;&lt; PC5;

		/* Put in a delay (we could use the AVR
		 * function for this).  The ASM instruction "nop"
		 * tells the CPU to do nothing for one clock cycle.
		 * The volatile keyword tells the compiler not
		 * to optimise this instruction out.
		 */
		for(int a = 0; a &lt; 100; a++)
			for(int b = 0; b &lt; 1000; b++)
				__asm__ volatile ("nop");
		next = 1-next;
	}

	return 1;
}</pre>
<p>The above code is all you need for some flashing LEDs.  The first two instructions in the while loop are the ones that do most of the work &#8212; they shift bits into the correct registers in order to turn the LED on or off.  Again the registers are named PORT&lt;Port Letter&gt; and the individual pin data bits P&lt;Port Letter&gt;&lt;Pin Number&gt;.  When coding these chips, remember that ints are only 8 bits long, don&#8217;t do as I did and have this count to 1000 000 in the delay as the number will overflow before it ever gets there (resulting in the program sitting there, spinning forever).</p>
<p>Anyway, that&#8217;s it for now, if you have any questions be sure to leave a comment below &#8212; I&#8217;m no expert, but I&#8217;ll do my best to answer your questions.  If you have suggestions as to how I can improve this code, or tools I can use to speed up development, then please comment.  Keep checking back because another tutorial on how to use timers is imminent.</p>
]]></content:encoded>
			<wfw:commentRss>http://beyondallrepair.com/2010/11/avr-programming-flashing-leds/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making the Mood Lamp Chat.</title>
		<link>http://beyondallrepair.com/2010/04/making-the-mood-lamp-chat/</link>
		<comments>http://beyondallrepair.com/2010/04/making-the-mood-lamp-chat/#comments</comments>
		<pubDate>Sat, 24 Apr 2010 15:19:41 +0000</pubDate>
		<dc:creator>Freud</dc:creator>
				<category><![CDATA[Arduino]]></category>
		<category><![CDATA[Electronics]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[arduino]]></category>
		<category><![CDATA[Bot]]></category>
		<category><![CDATA[Chat]]></category>
		<category><![CDATA[ikea]]></category>
		<category><![CDATA[inter process communication]]></category>
		<category><![CDATA[ipc]]></category>
		<category><![CDATA[Jabber]]></category>
		<category><![CDATA[lamp]]></category>
		<category><![CDATA[mood]]></category>
		<category><![CDATA[PERL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[socket]]></category>
		<category><![CDATA[unix]]></category>
		<category><![CDATA[XMPP]]></category>

		<guid isPermaLink="false">http://beyondallrepair.com/?p=38</guid>
		<description><![CDATA[I&#8217;ve been busy since I last spoke about my lamp.  I&#8217;ve added code to put the lamp into various modes &#8211; so far I&#8217;ve implemented modes for &#8216;white&#8217; (needs some calibration), randomly changing colours, randomly fading in and out with random colours, and of course just off. Modes are changed by sending characters to the [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been busy since I last spoke about my lamp.  I&#8217;ve added code to put the lamp into various modes &#8211; so far I&#8217;ve implemented modes for &#8216;white&#8217; (needs some calibration), randomly changing colours, randomly fading in and out with random colours, and of course just off.</p>
<p>Modes are changed by sending characters to the arduino over the serial connection, so that&#8217;s fairly easy.  In fact I decided that was too easy, and also too inconvenient for me (I don&#8217;t want to have to echo characters to the lamp every time I want to turn it on).  Therefore, to make changing modes easier I wrote a web interface, which contained some PHP code that echoed characters to the lamp based on which button had been pressed by the user.    This was all hosted locally to the lamp, so echoing characters to it was fairly easy.  The next step was to let users control the lamp remotely (i.e. across the internet).  This turned out to be a lot more challenging (or at least I overcomplicated it to the point that it became challenging), and this is the main focus of the article.</p>
<p>Simply allowing users to change the mode of my lamp over the internet would normally be really simple &#8211; open up port 80 on the server that&#8217;s hosting my lamp to the internet &#8211; however shamefully I&#8217;m on a network whose firewall blocks pretty much every inbound port, so hosting the interface locally isn&#8217;t an option.</p>
<p>Another simple option would be to have the lamp periodically poll a location on the internet to decide which mode to use, that way the web interface can just set the value of a file, then when the lamp reads that file, it will set its mode appropriately.  The downside with this is that the update time for the lamp would be quite slow and it would create a lot of http requests to the server.</p>
<p>So, to summarise</p>
<ul>
<li>The connection has to originate from behind the firewall</li>
<li>Responses to users actions should be fast, and should ideally be fetched through a single, persistent connection</li>
</ul>
<p>I&#8217;ve done work with chat bots before, and I just so happen to have access to a Jabber server so I decided I&#8217;d try to allow users to communicate with the lamp through Jabber.   This was actually fairly easy, although I admit I&#8217;m cheating in so far as the actual Jabber code isn&#8217;t running on the arduino, but instead a SheevaPlug (plug computer that runs linux).</p>
<h2>The Client</h2>
<p>The client side code is pretty simple &#8211; just a quick PERL script.  Jabber communication was enabled through the Net::Jabber.</p>
<pre>#!/usr/bin/perl -w

use strict;

use Net::Jabber;

my $server = "-----";
my $port = 5222;
my $username = "-----";
my $password = "-----";

my $client = new Net::Jabber::Client();
my $device = '/dev/ttyUSB0';

my $allowFork = 1;

my $allowFaffage = 1;

#Try to fork the process, then kill the parent process
#leaving only the child process running.   This detaches
#the process from the terminal.
if($allowFork == 1 &amp;&amp; fork())
{
    exit();
}

#Tells the XMPP librabry which functions should be
#called when certain events happen.
$client-&gt;SetCallBacks(message=&gt;\&amp;msgReceived, onauth=&gt;\&amp;authenticated);

#Connect to the server
$client-&gt;Execute(hostname=&gt;$server,
                tls=&gt;0,
                username=&gt;$username,
                password=&gt;$password,
                resource=&gt;"lamp",
                register=&gt;0);

#Sends a message to a user
sub send { my($to,$body) = @_;
                $client-&gt;MessageSend(to=&gt;"$to",subject=&gt;"Cheese",body=&gt;"$body");
}

sub sendHelp { my($to) = @_;
                my $body = &lt;&lt;END;
I'm Harry's Lamp <img src='http://beyondallrepair.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />   Talking to me turns me on, and makes me change colours etc.  Here are the commands that are enabled atm.

    white - Just boring, white light
    random - Makes me randomly fade to colours
    fade - Makes me fade in and out with random colours
    off - Turns me off
END
    &amp;send($to, $body);
}

#Once the lamp bot is up and ready,
#send a message to the owner to tell them.
sub authenticated{
    &amp;send('admin@-----','Lamp bot online');
}

sub msgReceived { my ($err,$message) = @_;
    my $body = $message-&gt;GetBody();
    my $from = $message-&gt;GetFrom();

    $from =~ s#/.*$##; #Get rid of anything after bleh@wahtever.com
    $body =~ s/[^a-zA-Z0-9]//g;  #Get rid of characters that arent alphanumeric
    $body = lc($body);        #Make $body all lower case.

    if($body eq "?" or $body eq "help")
    {
        sendHelp($from);
    }
    elsif($allowFaffage == 1)
    {
        if($body eq "random")
        {
            `echo 'r' &gt; $device`;
        }
        elsif($body eq "white")
        {
            `echo w &gt; $device`;
        }
        elsif($body eq "off")
        {
            `echo o &gt; $device`;
        }
        elsif($body eq "fade")
        {
            `echo i &gt; $device`;
        }
    }

    #Admin things...  Enable and disable the lamp
    #so people can't wake you in your sleep.
    if($from eq 'admin@-----')
    {
        if($body eq "quit")
        {
            exit();
        }
        elsif($body eq "enable")
        {
            $allowFaffage = 1;
            &amp;send($from,'Faffing enabled');
        }
        elsif($body eq "disable")
        {
            $allowFaffage = 0;
            &amp;send($from,'Faffing disabled');
        }
    }
}</pre>
<p>If you&#8217;re unfamiliar with PERL, the above script might be pretty horrific, but hopefully the comments in the code will help you work out what&#8217;s going on.  If you&#8217;d like to learn more about programming in PERL, there&#8217;s a ton of information on the internet, including <a href="http://perldoc.perl.org/index-tutorials.html">the PERL documentation</a>.</p>
<p>Most of the logic is in the msgReceived function, which is executed whenever a message is received.  The algorithm is very basic &#8211; get the body of the message we just received, then sanitise it, then compare it to various strings until we know what the user wants to happen.   Simple&#8230;  The above code runs locally on my plug computer, next I&#8217;ll take you through the code that runs on the server.</p>
<h2>The Server</h2>
<p>The server is actually running two pieces of code &#8211; a PERL script, which is similar to the one above and is used to communicate with the client over Jabber; and a PHP script which generates the user interface, and communicates with the PERL script when users choose to perform an action.</p>
<p>This might seem (and probably is) over complicated, but I&#8217;ll quickly explain my reasons for choosing this architecture.</p>
<ul>
<li>Firstly, PHP is stateless, i.e. variables aren&#8217;t stored between page loads (unless using sessions, or cookies), and usually when a script is finished executing any connections that it has opened are closed.  If I were to use just a single PHP script for generating the interface then communicating with the lamp, every time the script is loaded, a new connection to the Jabber serer would have to be made.  This slows down the load time of the page, and increases the load on both the web server and the jabber server.</li>
<li>Secondly, there is a good chance that two requests could be made to the server at the same time, if this were to happen, there would be two attempts to connect to the jabber server with the same user (which isn&#8217;t allowed).</li>
</ul>
<p>To fix this I decided that it would be nice to have a single script that is always connected to the jabber server, and can be communicated with using local Unix sockets.</p>
<h3>The PERL</h3>
<p>This code is fairly similar to the code above, so I won&#8217;t explain too much about it.  I&#8217;ll jump straight to talking about the well named &#8216;doyourshiz&#8217; subroutine. Avert your gaze if you are of a nervous disposition.</p>
<pre>#!/usr/bin/perl                                       

use Net::Jabber;
use Data::Dumper;
use Socket;      

my $server = "-----";
my $port = 5222;
my $username = "-----";
my $password = "-----";           

my $client = new Net::Jabber::Client();

my $allowFork = 0;

my $insockpath = "/home/freud/lampsocket";

#Detatch from the terminal if we're allowed to.
if($allowFork == 1 &amp;&amp; fork())
{
        exit();
}                                              

$client-&gt;SetCallBacks(message=&gt;\&amp;msgReceived, onauth=&gt;\&amp;authenticated);

$client-&gt;Execute(hostname=&gt;$server,
          tls=&gt;0,
          username=&gt;$username,
          password=&gt;$password,
          resource=&gt;"lamp",
          register=&gt;0);                                                   

sub send { my($to,$body) = @_;
        $client-&gt;MessageSend(to=&gt;"$to",subject=&gt;"Cheese",body=&gt;"$body");
}                                                                                                                 

sub msgReceived{
        print Dumper @_;
}                       

sub authenticated{
        print "Authenticated";
        #We're ready to send messages to the lamp,
        #Start listening for incomming comands from
        #the local socket.
        &amp;doyourshiz();
}                                                   

sub doyourshiz{
        #Create a socket
        socket(INSOCKET, PF_UNIX, SOCK_STREAM, 0) or die("$!");

        unlink($insockpath); #Delete the file we're binding to if
                             #it already exists...

        bind(INSOCKET,sockaddr_un($insockpath)) or die("$!");
        listen(INSOCKET,SOMAXCONN) or die("$!");

        #accept blocks (makes the program wait) until someone
        # connects to the socket.
        for( ;accept(Client,INSOCKET); close Client)
        {
                open(INPUT, "&lt;&amp;Client");
                #Open the client's input stream to 'INPUT' then
                # read from INPUT and send it to the lamp until we've
                # read everything that was sent to us.
                while(defined($line = &lt;INPUT&gt;))
                {
                        chomp $line;
                        &amp;send('lamp address',$line);
                }
                close(INPUT);
                #close the input. (the Client connection is closed in the for loop
                # definition above.).
            }
}</pre>
<p>OK&#8230; The doyourshiz subroutine contains the main application loop.  To start with it opens a Unix Socket, which appears as a special file on your file system (in the example above it has the path /home/freud/lampsocket).  Any applications wanting to communicate with the above script can connect to that socket by using that special file (this will become clearer when I show you the PHP).  The socket is identified inside the script by it&#8217;s identifier INSOCKET (the first argument to the socket command).</p>
<p>Whenever anything connects to that socket the script just relays whatever is sent to it to the lamp via Jabber.  Note that at the moment, the code above will only actually accept one connection at a time (which I realise conflicts with one of my requirements above), ideally the code within the for loop above would be executed in a new thread to allow new users to connect.  I&#8217;ll probably implement this soon&#8230;</p>
<p>Now you&#8217;ve seen the server&#8217;s PERL (which is by far the most complicated bit), it&#8217;s time to look at the PHP code.</p>
<h3>The PHP</h3>
<p>I started by writing a wrapper class that handled connecting and sending to the socket for me, keeping the main bulk of PHP free from socket code.</p>
<pre>&lt;?php
        class HSocket
        {
                private $socket;

                public function __construct($path)
                {
                        $this-&gt;socket = socket_create(AF_UNIX,SOCK_STREAM,0);
                        socket_connect($this-&gt;socket,$path);
                }

                public function __destruct()
                {
                        socket_close($this-&gt;socket);
                }

                public function send($data)
                {
                        socket_write($this-&gt;socket,$data,strlen($data));
                }
        }

?&gt;</pre>
<p>As you can see, the code is fairly simple. It&#8217;s pretty much the same as the PERL code above.  The constructor takes an argument, which is the path to the socket you&#8217;re connecting to, and (dis)connecting is all done for you when instantiating and destroying objects from that class.</p>
<p>When sending data to the socket, we use the command socket_write, which takes three parameters &#8211; the socket you&#8217;re sending to, the data to be sent, and the size of the data in bytes.  If you&#8217;d like to read more about socket programming in PHP check out <a href='http://uk3.php.net/manual/en/book.sockets.php'>the PHP Documentation</a> and for those of you who would like to learn more about PHP, a good place to start is <a href='http://uk3.php.net/manual/en/index.php'>the PHP Manual</a>, and of course Google.</p>
<p>Finally, the code that the user actually executes is below.  This contains the buttons the user presses and it also processes the user&#8217;s actions to determine what values should be sent to the PERL script (and ultimately the lamp).</p>
<pre>&lt;?php
        if(isset($_GET['do']))
        {
                include('HSocket.php');
                $s = new HSocket(&quot;/home/freud/lampsocket&quot;);

                //This switch statement makes sure we don't send anything
                //malicious to the lamp.
                switch(strtolower($_GET['do']))
                {
                case &quot;off&quot;:
                case &quot;white&quot;:
                case &quot;random&quot;:
                case &quot;fade&quot;:
                        $s-&gt;send($_GET['do']);
                break;
                }
        }
?&gt;

&lt;html&gt;
        &lt;head&gt;
                &lt;title&gt;
                        Light Controls
                &lt;/title&gt;

        &lt;/head&gt;

        &lt;body&gt;
                &lt;h1&gt;Mood Lamp&lt;/h1&gt;
                &lt;form action='index.php' method='get'&gt;
                &lt;input name='do' type='submit' value='Off'  /&gt;
                &lt;input name='do' type='submit' value='White'  /&gt;
                &lt;input name='do' type='submit' value='Random'/&gt;
                &lt;input name='do' type='submit' value='Fade'  /&gt;
                &lt;/form&gt;
        &lt;/body&gt;
&lt;/html&gt;</pre>
<p>You&#8217;ll probably be overjoyed to notice that the code above is really quite simple.  It creates a socket with the same path as was used in the PERL script above, and then sends data to it depending on the value of the &#8216;do&#8217; GET variable.  The switch statement helps to make sure that a malicious user can&#8217;t send data to the lamp that could be used to compromise either the server, plug, or lamp.</p>
<p>And there you have it.  If you&#8217;d like to see the code in action, check out <a href='http://beyondallrepair.com/lamp'>the online control panel</a>.  Currently you can&#8217;t see the state of the light (so you&#8217;ll just have to trust me that its working), but my next step is to get a webcam pointed at it, and also to add a feature to allow users to pick a specific colour for the lamp.</p>
<p>If you have any questions, or any suggestions as to what I can do next, please feel free to comment below.  I&#8217;ll try to respond as soon as I can.  If you want to steal any of the code above, then go ahead (it would be nice if you linked back to this post). </p>
]]></content:encoded>
			<wfw:commentRss>http://beyondallrepair.com/2010/04/making-the-mood-lamp-chat/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making an Ikea Mood Lamp</title>
		<link>http://beyondallrepair.com/2010/04/making-an-ikea-mood-lamp/</link>
		<comments>http://beyondallrepair.com/2010/04/making-an-ikea-mood-lamp/#comments</comments>
		<pubDate>Tue, 13 Apr 2010 18:56:50 +0000</pubDate>
		<dc:creator>Freud</dc:creator>
				<category><![CDATA[Arduino]]></category>
		<category><![CDATA[Electronics]]></category>
		<category><![CDATA[arduino]]></category>
		<category><![CDATA[diy]]></category>
		<category><![CDATA[ikea]]></category>
		<category><![CDATA[lighting]]></category>
		<category><![CDATA[mood lamp]]></category>

		<guid isPermaLink="false">http://beyondallrepair.com/?p=13</guid>
		<description><![CDATA[Since I first got my Arduino and some RGB LEDs I&#8217;d wanted to build myself a mood lamp with some funky features (note that I used the word funky and not useful).  Well, I&#8217;ve finally done it, and here is the blog post describing how. For this project I used the Ikea Grönö, which was [...]]]></description>
			<content:encoded><![CDATA[<p>Since I first got my Arduino and some RGB LEDs I&#8217;d wanted to build myself a mood lamp with some funky features (note that I used the word <em>funky</em> and not useful).  Well, I&#8217;ve finally done it, and here is the blog post describing how.</p>
<p>For this project I used the <a title="Ikea Grono Lamp" href="http://www.ikea.com/gb/en/catalog/products/30029224" target="_blank">Ikea Grönö</a>, which was £4.99 when I bought it.  It quite a nice matt glass finish, which helps to diffuse light, and also it comes with the glass shade and the actual light fitting separate from one another (I put the light fitting to one side as I won&#8217;t be using it in this project).</p>
<p>As well as that I used&#8230;</p>
<ul>
<li>3 x NPN Transistors &#8211; TIP122 5A</li>
<li>3 x 47 Ohm Resistors</li>
<li>1 x 100 Ohm Resistor</li>
<li>2 x 330 Ohm Resistors</li>
<li>2 x RJ45 connectors</li>
<li>2 x 16000mcd Red LEDs</li>
<li>2 x 18000mcd Green LEDs</li>
<li>2 x 9000mcd Blue LEDs</li>
<li>1 x Arduino Duemilanove</li>
<li>Some breadboard, wire and solder&#8230;</li>
</ul>
<p>The brightnesses above were only chosen because they were the highest that were available at a fairly reasonable cost.  It might be better to match the brightnesses of all LEDs, although if memory serves, human eyes aren&#8217;t as sensitive to blue light as they are red and green, so it might be worth getting a brighter blue LED (I advise doing some more research).</p>
<p>Anyway, on with the build&#8230;</p>
<p>Firstly, LEDs tend to be highly directional (i.e most light goes in front of the led).  There seem to be lots of diffusing and mixing lenses available at various shops, but I decided I&#8217;d have a go at just scuffing the LEDs with some sandpaper.  I was quite happy with the diffusion of light after having done that, so my next step was to breadboard the LEDs out.  I arranged them into a triangular shape with a common ground rail on the breadboard, and individual positive rails for each diode.</p>
<p>In this project I&#8217;ve used the 5V supply from the arduino, my LEDs however were expecting</p>
<ul>
<li>Red: 1.9V 50mA</li>
<li>Green, Blue: 3.4V 20mA</li>
</ul>
<p>Therefore resistors must be added to stop the components from being &#8216;popped&#8217; (trust me, blown up LEDs stink).  The required resistance can be easily calculated using Ohms Law &#8211; V = IR.</p>
<p>V = The potential difference across the resistor (Volts).</p>
<p>I = The current in the circuit in series with the resistor (Amps).</p>
<p>R = The resistance of the resistor (Ohms).</p>
<p>So, we need the following values.</p>
<ul>
<li>Red: R = V/I = (5.0 &#8211; 1.9) / .050 = 3.1 / .050 = 62 Ohms</li>
<li>Green, Blue: (5.0 &#8211; 3.4) / .020 = 1.6 / .02 = 80 Ohms</li>
</ul>
<p>Simple&#8230; Here&#8217;s a video of the lamp shade placed over the breadboarded leds.</p>
<div style="text-align: center;"><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="480" height="385" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/v/Pi-K-Z57IOs&amp;hl=en_GB&amp;fs=1&amp;" /><param name="allowfullscreen" value="true" /><embed type="application/x-shockwave-flash" width="480" height="385" src="http://www.youtube.com/v/Pi-K-Z57IOs&amp;hl=en_GB&amp;fs=1&amp;" allowscriptaccess="always" allowfullscreen="true"></embed></object></div>
<p>Although you can&#8217;t see it in that video, with only one LED of each colour it was far too hard to see when the surrounding light levels were high so I decided I&#8217;d add another led of each colour so they were arranged as in the following diagram.</p>
<div id="attachment_17" class="wp-caption aligncenter" style="width: 210px"><a href="http://beyondallrepair.com/wp-content/uploads/2010/04/ledarrangement.png"><img class="size-full wp-image-17" title="LED Arrangement in Arduino mood lamp" src="http://beyondallrepair.com/wp-content/uploads/2010/04/ledarrangement.png" alt="LED Arrangement in Arduino mood lamp" width="200" height="190" /></a><p class="wp-caption-text">LED Arrangement in Arduino mood lamp</p></div>
<p>I used three TIP122 NPN Transistors to allow the LEDs to draw more current than if I were just feeding them directly from the PWM outputs on the Arduino. The diagram below shows the circuit design as it was breadboarded out.  This is in fact basically the same as the final circuit diagram (except with an Cat 5 patch cable separating the transistors from the resistors and LEDs).</p>
<div id="attachment_24" class="wp-caption aligncenter" style="width: 511px"><a href="http://beyondallrepair.com/wp-content/uploads/2010/04/BreadboardCircuitDiagram2.png"><img class="size-full wp-image-24" title="Circuit diagram for breadboarded ikea mood lamp" src="http://beyondallrepair.com/wp-content/uploads/2010/04/BreadboardCircuitDiagram2.png" alt="Circuit diagram for breadboarded ikea mood lamp" width="501" height="369" /></a><p class="wp-caption-text">The breadboarded mood lamp circuit. Numbers in circles correspond to the digital output pins on the Arduino. R1 = 100 Ohms, R2 = 47 Ohms, R3 = 330 Ohms.</p></div>
<p>Note the resistors and LEDs in parallel.  Now that the LEDs are in parallel, the series part of the circuit must have twice the current required by the LEDs (Red: 100mA, Green and Blue 40mA).  Therefore we require the following resistances.</p>
<ul>
<li>Red: 31 Ohms</li>
<li>Green, Blue: 40 Ohms</li>
</ul>
<p>You could of course just go to the next resistor size up, but I like to make things complicated so I decided I&#8217;d try to get as close as I can with the resistors that I had at my disposal.  When combining resistors in parallel, the total resistance of the resistors in parallel is  1/R = 1/R1 + 1/R2 + &#8230; + 1/Rn</p>
<p>In the above diagram, R1 = 100 Ohms, R2 = 47 Ohms, R3 = 330 Ohms, meaning that the resistances above are</p>
<ul>
<li>Red: 1/R = 1/100 + 1/47.  R = 32 Ohms</li>
<li>Green, Blue: 1/R = 1/47 + 1/330.   R = 41 Ohms</li>
</ul>
<p>So, after breadboarding that and finding everything worked, I soldered everything to two breadboards.  One containing the LEDs and Resistors, another containing the transistors and leads to connect to the arduino.  I also soldered some RJ45 sockets on to the boards, to allow me to connect the two components together over long distances (I could have used other means, but I have miles of patch cable lying around).  Something to remember when soldering the RJ45 sockets is that if you don&#8217;t plan on using crossover cable, you should solder the two sockets in reverse to one another as in the diagram below.</p>
<div id="attachment_26" class="wp-caption aligncenter" style="width: 311px"><a href="http://beyondallrepair.com/wp-content/uploads/2010/04/rj45s.png"><img class="size-full wp-image-26" title="Connections on the RJ45 Sockets" src="http://beyondallrepair.com/wp-content/uploads/2010/04/rj45s.png" alt="RJ45 socket pins" width="301" height="114" /></a><p class="wp-caption-text">An example of how you could solder the connections on your RJ45 sockets.</p></div>
<p>Once you&#8217;ve done that, connect everything up and make sure everything works before glueing the LEDs to the bottom of your lamp.  Then you&#8217;re pretty much done (except for coding the actual Arduino).  The code I have so far is very simple, it simply fades between colours.</p>
<pre>
<div id="_mcePaste">const int led[] = {3,5,6};</div>
<div id="_mcePaste">const int delayTime = 10;</div>
<div id="_mcePaste">#define RG 0</div>
<div id="_mcePaste">#define GB 1</div>
<div id="_mcePaste">#define BR 2</div>
<div id="_mcePaste">void setColour(const int * led, const int * colour)</div>
<div id="_mcePaste">{</div>
<div id="_mcePaste">    for(int i = 0; i &lt; 3; i ++)</div>
<div id="_mcePaste">    {</div>
<div id="_mcePaste">        analogWrite(led[i],colour[i]);</div>
<div id="_mcePaste">    }</div>
<div id="_mcePaste">}</div>
<div id="_mcePaste">void cycle(int which, const int * led)</div>
<div id="_mcePaste">{</div>
<div id="_mcePaste">    int a;</div>
<div id="_mcePaste">    int b;</div>
<div id="_mcePaste">    switch(which)</div>
<div id="_mcePaste">    {</div>
<div id="_mcePaste">        case RG:</div>
<div id="_mcePaste">            a = led[0];</div>
<div id="_mcePaste">            b = led[1];</div>
<div id="_mcePaste">        break;</div>
<div id="_mcePaste">        case GB:</div>
<div id="_mcePaste">            a = led[1];</div>
<div id="_mcePaste">            b = led[2];</div>
<div id="_mcePaste">        break;</div>
<div id="_mcePaste">        default:</div>
<div id="_mcePaste">            a = led[2];</div>
<div id="_mcePaste">            b = led[0];</div>
<div id="_mcePaste">    }</div>
<div id="_mcePaste">    for(int i = 0; i &lt;= 255; i ++)</div>
<div id="_mcePaste">    {</div>
<div id="_mcePaste">        analogWrite(b, i);</div>
<div id="_mcePaste">        analogWrite(a, 255 - i);</div>
<div id="_mcePaste">        delay(delayTime);</div>
<div id="_mcePaste">    }</div>
<div id="_mcePaste">}</div>
<div id="_mcePaste">void setup()</div>
<div id="_mcePaste">{</div>
<div id="_mcePaste">    for(int i = 0; i &lt; 3; i++)</div>
<div id="_mcePaste">    {</div>
<div id="_mcePaste">        pinMode(led[i],OUTPUT);</div>
<div id="_mcePaste">    }</div>
<div id="_mcePaste">}</div>
<div id="_mcePaste">void loop()</div>
<div id="_mcePaste">{</div>
<div id="_mcePaste">    cycle(RG, led);</div>
<div id="_mcePaste">    cycle(GB, led);</div>
<div id="_mcePaste">    cycle(BR, led);</div>
<div id="_mcePaste">}</div>
</pre>
<p>And the moment you&#8217;ve all been waiting for &#8211; a video of the final product&#8230;</p>
<div style="text-align: center;"><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="480" height="385" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/v/OV2MQ173y00&amp;hl=en_GB&amp;fs=1&amp;" /><param name="allowfullscreen" value="true" /><embed type="application/x-shockwave-flash" width="480" height="385" src="http://www.youtube.com/v/OV2MQ173y00&amp;hl=en_GB&amp;fs=1&amp;" allowscriptaccess="always" allowfullscreen="true"></embed></object></div>
<div style="text-align: left;">So there you have it.  I&#8217;m sure I&#8217;ve probably missed something out, so feel free to ask questions.  My next step is to add some code that lets me change the light over the network, so keep checking back for more updates.</div>
]]></content:encoded>
			<wfw:commentRss>http://beyondallrepair.com/2010/04/making-an-ikea-mood-lamp/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

