<?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>Superjazz</title>
	<atom:link href="http://www.penjuinlabs.com/blog/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://www.penjuinlabs.com/blog</link>
	<description>Blabber about computing and electronics.</description>
	<lastBuildDate>Wed, 05 Aug 2009 23:41:25 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Silly universe, this is what you get when you give me free time.</title>
		<link>http://www.penjuinlabs.com/blog/?p=102</link>
		<comments>http://www.penjuinlabs.com/blog/?p=102#comments</comments>
		<pubDate>Sun, 29 Mar 2009 09:54:18 +0000</pubDate>
		<dc:creator>jeremy</dc:creator>
				<category><![CDATA[electronics]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[glcd]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.penjuinlabs.com/blog/?p=102</guid>
		<description><![CDATA[ 
(I was messing around with PIL and realised that the dithering capabilities were perfect for my graphical LCD. As you can see, it turned out rather well!)
]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.penjuinlabs.com/blog/wp-content/uploads/2009/03/img_6626.jpg" alt="dino_lcd" title="dino_lcd" width="483" height="322" class="alignnone size-full wp-image-101" /> </p>
<p>(I was messing around with PIL and realised that the dithering capabilities were perfect for my graphical LCD. As you can see, it turned out rather well!)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.penjuinlabs.com/blog/?feed=rss2&amp;p=102</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Installing PyGTK on Windows</title>
		<link>http://www.penjuinlabs.com/blog/?p=94</link>
		<comments>http://www.penjuinlabs.com/blog/?p=94#comments</comments>
		<pubDate>Sat, 28 Mar 2009 06:30:23 +0000</pubDate>
		<dc:creator>jeremy</dc:creator>
				<category><![CDATA[linux]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[gtk]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.penjuinlabs.com/blog/?p=94</guid>
		<description><![CDATA[GTK is awesome. PyGTK is awesome. PyGTK on Windows is far, far less than awesome. I recently wrote some software that runs fine on my Linux box after a couple of apt-gets, but unfortunately the software is for Windows users. I spent a good part of the morning getting all the stuff needed for PyGTK [...]]]></description>
			<content:encoded><![CDATA[<p>GTK is awesome. PyGTK is awesome. PyGTK on Windows is far, far less than awesome. I recently wrote some software that runs fine on my Linux box after a couple of apt-gets, but unfortunately the software is for Windows users. I spent a good part of the morning getting all the stuff needed for PyGTK installed in a VM; it was a painful process of trial and error. To save everyone else the trouble, here is how I ended up doing it.<span id="more-94"></span></p>
<p><strong>Python 2.5 or 2.6?</strong></p>
<p>I am a 2.6 guy, but if you are using PyGTK on Windows, 2.6 is a bad way to go. As of 2.6, the default compiler for python is VS2008, not MinGW. All of the binaries that are compiled by the gnome groups are done with MinGW, so you can&#8217;t actually use these with 2.6 (or at least I couldn&#8217;t). It sucks, I know. If you start getting errors like this:</p>
<pre>"C:\libs\Python-2.6.1\Lib\site-packages\gtk-2.0\gobject\constants.py", line
22, in &lt;module&gt;
    from _gobject import type_from_name
ImportError: DLL load failed: The specified module could not be found.</pre>
<p>you need to roll back to 2.5.</p>
<p><strong>Lots of installers</strong></p>
<p>To install PyGTK, run these installers (in this order):</p>
<ol>
<li><a href="http://python.org/ftp/python/2.5.4/python-2.5.4.msi">python-2.5.4.msi</a></li>
<li><a href="http://downloads.sourceforge.net/gtk-win/gtk2-runtime-2.16.0-2009-03-22-ash.exe?download">gtk2-runtime-2.16.0-2009-03-22-ash.exe</a></li>
<li><a href="http://ftp.gnome.org/pub/GNOME/binaries/win32/pycairo/1.4/pycairo-1.4.12-2.win32-py2.5.exe">pycairo-1.4.12-2.win32-py2.5.exe</a></li>
<li><a href="http://ftp.gnome.org/pub/GNOME/binaries/win32/pygobject/2.14/pygobject-2.14.2-2.win32-py2.5.exe">pygobject-2.14.2-2.win32-py2.5.exe</a></li>
<li><a href="http://ftp.gnome.org/pub/GNOME/binaries/win32/pygtk/2.12/pygtk-2.12.1-3.win32-py2.5.exe">pygtk-2.12.1-3.win32-py2.5.exe</a></li>
</ol>
<p>Then jump into python and check that it has installed okay:</p>
<p><code>&gt;&gt;&gt; import gtk<br />
&gt;&gt;&gt;<!--formatted--></code></p>
<p>In case these packages ever go away, I will mirror them <a href="http://www.penjuinlabs.com/files/pygtk_bundle_o_fun.zip">here</a>. Happy pythoning!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.penjuinlabs.com/blog/?feed=rss2&amp;p=94</wfw:commentRss>
		<slash:comments>28</slash:comments>
		</item>
		<item>
		<title>Getting your joystick to work under Ubuntu Intrepid Ibex (8.10)</title>
		<link>http://www.penjuinlabs.com/blog/?p=82</link>
		<comments>http://www.penjuinlabs.com/blog/?p=82#comments</comments>
		<pubDate>Sun, 22 Mar 2009 09:06:00 +0000</pubDate>
		<dc:creator>jeremy</dc:creator>
				<category><![CDATA[linux]]></category>

		<guid isPermaLink="false">http://www.penjuinlabs.com/blog/?p=82</guid>
		<description><![CDATA[So, I&#8217;ve finally gone Linux-only on my desktop with a nice fresh install of Ubuntu 8.10. I have to say that Ubuntu has improved greatly since I last used it on the desktop (I have been running Ubuntu Server for a while with no issues as well), but there are still a few nagging problems. [...]]]></description>
			<content:encoded><![CDATA[<p>So, I&#8217;ve finally gone Linux-only on my desktop with a nice fresh install of Ubuntu 8.10. I have to say that Ubuntu has improved greatly since I last used it on the desktop (I have been running Ubuntu Server for a while with no issues as well), but there are still a few nagging problems. One of these was the Xorg autodetection driver; while mostly awesome, it would recognise my gamepad as a mouse and then intercept all input from it. However, a couple of quick edits and a restart fixed it up nicely (this post assumes that your joystick is supported by <a href="http://en.wikipedia.org/wiki/HAL_(software)">HAL</a> under Linux, but is just behaving badly).<span id="more-82"></span></p>
<p><strong>Installing/Removing Software</strong></p>
<p>The first thing we need to do is remove the Xorg joystick driver.</p>
<p><code>sudo apt-get purge xserver-xorg-input-joystick</code></p>
<p>This stops it meddling with your joystick once and for all. To make things easier, we will install <code>jscalibrator</code> to test the controller.</p>
<p><code>sudo apt-get install jscalibrator</code></p>
<p>If you now run <code>jscalibrator</code> from the command line, it should detect your joystick/gamepad and look something like this:</p>
<p style="text-align: center;"><img class="size-full wp-image-88 aligncenter" title="jscalibrator" src="http://www.penjuinlabs.com/blog/wp-content/uploads/2009/03/screenshot.png" alt="jscalibrator" width="659" height="386" /></p>
<p>If you see the name of your controller in the titlebar, all is well! If you don&#8217;t, then the HAL is not detecting your controller and you need to fix that problem first (beyond the scope of this tutorial). My controller is a Logitech Wireless Xbox controller that a friend gave me. It was broken, so I fixed it and I modified to work with a PC usb port. It&#8217;s okay if none of your button presses show up at the moment, that is what we are trying to fix. To make sure that HAL is working, you can type</p>
<p><code>lshal | grep "&lt;controller name&gt;"<!--formatted--></code></p>
<p>where &lt;controller name&gt; is the name in the titlebar of jscalibrator. So for me it look like this</p>
<p><code>jeremy@jer:~$ lshal | grep &quot;Logitech Xbox Cordless Controller&quot;<br />
info.product = &#039;Logitech Xbox Cordless Controller&#039;  (string)<br />
input.product = &#039;Logitech Xbox Cordless Controller&#039;  (string)<br />
jeremy@jer:~$<br />
</code></p>
<p>And it shows up! This step is actually unnecessary because jscalibrator gets the names from the HAL, but it is nice to know how everything ties together!</p>
<p><strong>Adding your joystick to the HAL exceptions list</strong></p>
<p>As far as I can tell, Xorg currently assumes all joysticks to be mice simply because it does not know any better. So in order for it to leave the joystick alone we have to tell HAL to keep it away from Xorg. To do this, open</p>
<p><code>/etc/hal/fdi/policy/joystick.fdi</code></p>
<p>with your favourite <code>sudo</code>-ed editor and change it to look like this (it should be a new file):</p>
<p><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;<br />
&lt;deviceinfo version="0.2"&gt;<br />
&lt;device&gt;<br />
&lt;match key="input.product" contains="Logitech Xbox Cordless Controller"&gt;<br />
&lt;remove key="input.x11_driver" /&gt;<br />
&lt;/match&gt;<br />
&lt;/device&gt;<br />
&lt;/deviceinfo&gt;<!--formatted--></code></p>
<p>except in the place of &#8220;Logitech Xbox Cordless Controller&#8221; put the name of your controller. For completeness sake, we need to restart HAL so it reads our new policy file:</p>
<p><code>sudo /etc/init.d/hal restart</code></p>
<p>Now log out and log back in to restart the X server, and your joystick should be good to go! Try clicking some buttons and moving around the joystick in jscalibrator to test it.</p>
<p style="text-align: center;"><img class="size-full wp-image-89 aligncenter" title="jscalibrator working" src="http://www.penjuinlabs.com/blog/wp-content/uploads/2009/03/screenshot-3.png" alt="jscalibrator working" width="659" height="386" /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.penjuinlabs.com/blog/?feed=rss2&amp;p=82</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Update on&#8230;.things</title>
		<link>http://www.penjuinlabs.com/blog/?p=78</link>
		<comments>http://www.penjuinlabs.com/blog/?p=78#comments</comments>
		<pubDate>Sun, 15 Mar 2009 11:41:09 +0000</pubDate>
		<dc:creator>jeremy</dc:creator>
				<category><![CDATA[uncategorized]]></category>

		<guid isPermaLink="false">http://www.penjuinlabs.com/blog/?p=78</guid>
		<description><![CDATA[Well, &#8216;09 has been a good year so far. I love python, so I wrote a personal blog in it, you can find it here. Also, I started Engineering at UQ and am having an awesome time.
I bought a unibody Macbook 13&#8243; and love it  .
No-one probably comes here since I was serving 500s [...]]]></description>
			<content:encoded><![CDATA[<p>Well, &#8216;09 has been a good year so far. I love python, so I wrote a personal blog in it, you can find it <a href="http://jeremyherbert.net/">here</a>. Also, I started Engineering at UQ and am having an awesome time.</p>
<p>I bought a unibody Macbook 13&#8243; and love it <img src='http://www.penjuinlabs.com/blog/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> .</p>
<p>No-one probably comes here since I was serving 500s for about 3 months, so I best get writing again!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.penjuinlabs.com/blog/?feed=rss2&amp;p=78</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Graduating from Arduino to AVR</title>
		<link>http://www.penjuinlabs.com/blog/?p=64</link>
		<comments>http://www.penjuinlabs.com/blog/?p=64#comments</comments>
		<pubDate>Sun, 04 Jan 2009 05:43:10 +0000</pubDate>
		<dc:creator>jeremy</dc:creator>
				<category><![CDATA[avr tutorial]]></category>
		<category><![CDATA[electronics]]></category>
		<category><![CDATA[arduino]]></category>
		<category><![CDATA[avr]]></category>
		<category><![CDATA[hardware]]></category>

		<guid isPermaLink="false">http://www.penjuinlabs.com/blog/?p=64</guid>
		<description><![CDATA[I often see quite large scale projects online made with Arduinos, but as a person who has moved from AVRs to Arduino what I see doesn&#8217;t make a lot of sense. The arduino is essentially a prototyping device and while there is nothing really wrong with using it in a final design, much can be [...]]]></description>
			<content:encoded><![CDATA[<p><img style="padding: 10px 10px 10px 10px; float: right;" title="Atmega128" src="http://www.futurlec.com/Pictures/ET-AVR_Stamp_ATMega128_D.jpg" alt="An AVR Microcontroller" width="300" height="301" />I often see quite large scale projects online made with Arduinos, but as a person who has moved from AVRs to Arduino what I see doesn&#8217;t make a lot of sense. The arduino is essentially a prototyping device and while there is nothing really wrong with using it in a final design, much can be gained from moving away from it.  Just to clarify: I understand that an arduino is built around an AVR, but the problem is that much of the power (and complexity) is abstracted away by the software. Perhaps it&#8217;s just me, but I like to know exactly what is going on inside my processor. On top of this, AVR Simulator is a godsend for hunting down that last bug.</p>
<p>The real reason behind this whole thing is price. From <a href="http://www.littlebirdelectronics.com/">Little Bird</a>, the cheapest Arduino is $17.50 while the sale is on, and that has no USB chip on it. The ones with the USB chip are &gt;$40, not to mention the price of accessories. An Atmega88 at Futurlec is $3.80, a crystal is $1, caps are a few cents and so is the pullup resistor for reset (this will all be explained in a later post).</p>
<p><strong>Development Environment</strong></p>
<p>The basic tools I use for AVR development are:</p>
<ul>
<li><a href="http://www.atmel.com/dyn/products/tools_card.asp?tool_id=2725">AVR Studio</a> - A free IDE with AVR Simulator built in</li>
<li><a href="http://winavr.sourceforge.net/">WinAVR</a> &#8211; A free C compiler for AVRs (based on gcc) and other tools</li>
<li><a href="http://www.atmel.com/dyn/Products/tools_card.asp?tool_id=2735">STK500</a> &#8211; There is a multitude of free or prebuilt development boards on the net</li>
</ul>
<p>You won&#8217;t need any of these till the next tutorial; we are just going to talk about hardware for now.<span id="more-64"></span></p>
<p><strong>AVR Hardware</strong></p>
<p>You can find the datasheet for the Atmega88 <a href="http://www.atmel.com/dyn/resources/prod_documents/doc2545.pdf">here</a>. Download it and save it somewhere safe or take it down to the print shop and get it bound; you are going to need to use it <em>a lot</em>. To start with today, let&#8217;s take a look at all the funky acronyms on the first page. Make sure you have it open in a different browser window or tab so you can follow along (a wikipedia tab can&#8217;t hurt either).</p>
<p>RISC stands for Reduced Instruction Set Computer. An instruction is exactly what you think it is; a piece of information passed to the CPU telling it to do something. Examples include MOV (Move), AND (Bitwise AND) and LEA (Load Effective Address). As you can see by the next line on the page, the AVR only has 131 instructions so after a bit of practice you can pretty much remember the whole set. As a point of comparison, the regular x86 architecture for PCs is a CISC architecture (Complex Instruction Set Computer) and has <a href="http://en.wikipedia.org/wiki/X86_instruction_listings">thousands</a> of instructions. The beauty of a high level programming language like C is that you don&#8217;t need to remember any instructions; the compiler translates your code into the correct ones depending on the architecture you are compiling for.</p>
<p>The next line tells you that the mega88 has 32 8bit registers (the size of a C char). Registers act in a very similar way to memory, but they are located inside the CPU and thus are much, much faster to access. The &#8220;Fully Static Operation&#8221; bullet simply indicates that, as long as power is still applied, the AVR will maintain its current state if you take the clock source away and will pick up where it stopped once the clock is enabled again. 20 MIPS @ 20MHz means that it can process 20 million instructions per second when the clock source is 20MHz; pretty snappy!</p>
<p>You have 3 types of memory inside of an AVR: Flash, EEPROM and SRAM. The flash is where you store your code (the binary equivalent of all your instructions). Flash is non-volatile, meaning that it will not be erased if you take away the power. Whilst you can reprogram the flash memory while your code is running, it can cause all sorts of nasty things to happen so just assume that flash is read only unless you are using a device programmer or loading new code. So how do you store things between power cycles then? EEPROM (Electrically Erasable Programmable Read Only Memory) is also non-volatile, but you can read and write to it as much as you want (the name is kind of a misnomer). Just remember though, the EEPROM has a limited number of guaranteed erase cycles (100 000 for the mega88) so don&#8217;t go too nuts writing to it or it will wear down. SRAM is volatile (you will lose it between power cycles) but it is much faster than the other two types and doesn&#8217;t suffer from the wear down problem. </p>
<p><strong>Bootloaders</strong></p>
<p>Let&#8217;s take a quick jump back to Arduino land. If you&#8217;ve been paying attention, you should have been wondering why you can program an Arduino without a programming device, but you need one for every other AVR. This is the result of a magical little piece of software called the bootloader. A bootloader is a piece of software that retrieves new code from a non-standard location and loads it into the flash memory. In the Arduino, the bootloader retrieves the code over USB from the Arduino software. If you look in the memory section of the datasheet, you will see one of the bullets is &#8220;Optional Boot Code Section&#8221;; this is where the bootloader resides. When you click Upload in the Arduino software, the chip is put through a soft reset, after which the bootloader starts up and waits for data over the USB port. You can write a bootloader to load code from almost anywhere but you need a real device programmer to load the bootloader onto the chip the very first time and the maximum code size is often quite small so you will need to plan accordingly (you can&#8217;t perform RSA signature checking for example). An interesting point to note here is that the Arduino bootloader pretends to be an STK500 in order to leverage the already prevalent STK500 drivers.</p>
<p><strong>Device Features</strong></p>
<p>In a PC, all of these components we have been talking about are separated. The CPU is a different module to the RAM, which is a different module to the Southbridge, etc. The difference between a microprocessor and a microcontroller is that in the latter most of these components are already built in. You sacrifice some flexibility for simplicity but even then, certain AVRs have an external memory interface and almost all you can connect an external EEPROM to. Some of the modules that are built in to microcontrollers are not critical to their operation but simply provide an easier way to perform common tasks. If we look at the &#8220;Peripheral Features&#8221; section on the summary page, we can see what extra tasks this AVR can handle.</p>
<p>The mega88 three timers, two of which are 8 bit and one that is 16. This means that the modules can count to 255 (0xFF) and 65535 (0xFFFF) respectively. All three timers can be given a separate prescaler, meaning that for n cycles of the oscillator on the device with prescaler q, the clock will increase by the closest rounded down integer of n/q. Now that is a bit of a mouthful, so an example is probably in order: if you set the prescaler to 64, then the timer will increment every 64 clock cycles. Likewise, if you set the prescaler to 1024 then the timer will increment every 1024 cycles. The &#8220;Compare Mode&#8221; refers to the timer modules&#8217; ability to trigger interrupts. I will talk about interrupts in more detail at a later time, but they are essentially events that tell the CPU to drop everything and handle this event immediately. The &#8220;Real Time Counter with Separate Oscillator&#8221; bullet refers to the fact that you can also have a counter that increments independently of the CPU clock cycles; you provide it with its own oscillator.</p>
<p>The next bullet down states that the mega88 has six PWM channels. PWM, or Pulse Width Modulation, is quite a complex topic (there are still a few bits I am hazy about) but for now, just pretend that it is a way of generating analog volatages in our digital environment. The six channels means that there are six pins on the device capable of PWM.</p>
<p>ADC (Analog to Digital Converter) allows you to read an analog voltage. So while a regular pin could only tell you whether it is +5v or 0v, an ADC pin could tell you that the voltage is currently +2.5v or +3.8v. The &#8220;10 bit&#8221; refers to the resolution of the module, or to how many decimal places it can be accurate. 10 bit means that it can tell you with an accuracy of 0 to 1023 (0&#215;3FF). If this doesn&#8217;t make sense, don&#8217;t worry; more on this will come later. In the TQFP and QFN packages you get 8 pins that have these ADC modules attached, while in the PDIP package you get 6. <a href="http://en.wikipedia.org/wiki/TQFP">TQFP</a> (Tiny Quad Flat Pack, see image at the top of this post) and <a href="http://en.wikipedia.org/wiki/QFN">QFN</a> (Quad Flat No leads) are chip packages used by soldering machines and expert solderers; you will most likely come accross <a href="http://en.wikipedia.org/wiki/PDIP">PDIPs</a> (Dual Inline Packages) in your electronics capers which are much larger and, unless you have the dexterity of a neurosurgeon, easier to deal with.</p>
<p>UART, SPI and I²C are all data transfer protocols; USART (Universal Synchronous/Asynchronous Receiver Transmitter) is the same one the COM port on your PC uses (although COM ports have been mainly phased out by now). SPI (Serial Peripheral Interface) is a special interface for talking to high speed devices like external EEPROMs or flash memory. Finally, I²C (Inter-Intergrated Circuit) is a protocol for connecting lots and lots of devices together. I²C is the protocol you will come accross the most in microcontroller-compatable chips; things like digital I/O, digital thermometers, external ADCs, real-time clocks (actual time clocks) and more. All of these have been abstracted by the underlying hardware to make them easier to use.</p>
<p>Although there is a lot more in this section, I am only going to talk about two more important parts now because let&#8217;s face it, this post is already long enough. The first is the external and internal interrupt sources. The AVR has many interrupts, from a timer match to a pin being pulled to +5v to a byte being received over I²C. They are very useful because they allow the AVR to become reactive as opposed to having to check for events over and over again (this makes the code much simpler as well). Finally, we have the 23 programmable I/O lines. If you look at page 2, &#8220;Pin Configurations&#8221;, you can see that most of the pins have P followed by a letter and then a number. This is a programmable I/O line that you can set to high or low. As an example, PC5 stands for Port C, pin 5. There are four ports on the mega88. The other labels in brackets refer to the modules we have been talking about previously and the pins that they can control.</p>
<p><strong>In Conclusion</strong></p>
<p>So concludes the basic introduction to AVR microcontrollers. Next time, we&#8217;ll go through a simple &#8220;Hello World&#8221; type application.</p>
<p>I would just like to say that I understand AVRs are complex. I never said that they weren&#8217;t. But if Arduinos are too expensive to include in your project or you would like to write your own libraries for them, learning about the underlying hardware is a must. Or perhaps, like me, you just like to know what is going on under the hood.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.penjuinlabs.com/blog/?feed=rss2&amp;p=64</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Happy New Year!</title>
		<link>http://www.penjuinlabs.com/blog/?p=60</link>
		<comments>http://www.penjuinlabs.com/blog/?p=60#comments</comments>
		<pubDate>Sat, 03 Jan 2009 04:14:17 +0000</pubDate>
		<dc:creator>jeremy</dc:creator>
				<category><![CDATA[uncategorized]]></category>
		<category><![CDATA[projects]]></category>

		<guid isPermaLink="false">http://www.penjuinlabs.com/blog/?p=60</guid>
		<description><![CDATA[If there is anyone out there reading this, happy new year! I have had so much time lately to work on my own projects that it is becoming difficult to choose which one to work on. On top of this, I found out that I have even more time off then I expected. My New [...]]]></description>
			<content:encoded><![CDATA[<p>If there is anyone out there reading this, happy new year! I have had so much time lately to work on my own projects that it is becoming difficult to choose which one to work on. On top of this, I found out that I have even more time off then I expected. My New Year&#8217;s resolution is to write a decent, informative post at least once a week (excluding exam weeks), so to the 5 or so people who have subscribed to my RSS, I promise more is coming soon!</p>
<p>My latest two projects: developing a photography gallery for <a href="http://www.nelpix.com">nelpix.com</a> and creating a sort of race timer for little remote control cars (more on that later).</p>
<p>Have a great year everyone!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.penjuinlabs.com/blog/?feed=rss2&amp;p=60</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The trap of false optimisation</title>
		<link>http://www.penjuinlabs.com/blog/?p=56</link>
		<comments>http://www.penjuinlabs.com/blog/?p=56#comments</comments>
		<pubDate>Fri, 21 Nov 2008 03:38:55 +0000</pubDate>
		<dc:creator>jeremy</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[optimisation]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.penjuinlabs.com/blog/?p=56</guid>
		<description><![CDATA[Every so often, a post pops up in my RSS reader that is something along the lines of &#8220;20 optimisation tricks&#8221; or &#8220;10 techniques to make your code run faster&#8221;. Sure, everyone wants their code to run faster, but a number of these techniques only serve to make code run slower and become less readable. [...]]]></description>
			<content:encoded><![CDATA[<p>Every so often, a post pops up in my RSS reader that is something along the lines of &#8220;20 optimisation tricks&#8221; or &#8220;10 techniques to make your code run faster&#8221;. Sure, everyone wants their code to run faster, but a number of these techniques only serve to make code run slower and become less readable. The problem is that people blindly accept these posts as factual information(myself included) because optimisation is hard, and the next time they come across a situation they use the false optimisation which makes their code run slower. I decided to investigate a one of the tips I read recently.<span id="more-56"></span></p>
<p>The tip I read related to the use of if/else blocks; the article said that I would be better off without the else part by setting the else value of a variable before the if statement. I think code can explain this better than a sentence, so here it is (the for loops are to make the code run for a measurable amount of time):</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;"># speedtest1.py</span>
<span style="color: #808080; font-style: italic;"># testing the speed of two optimisations</span>
variable = <span style="color: #ff4500;">0</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">for</span> n <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span>, <span style="color: #ff4500;">10000000</span><span style="color: black;">&#41;</span>:
	i = <span style="color: #ff4500;">0</span>
	<span style="color: #ff7700;font-weight:bold;">if</span> variable:
		i = <span style="color: #ff4500;">1</span>
&nbsp;
	variable ^= <span style="color: #ff4500;">1</span> <span style="color: #808080; font-style: italic;"># flip it!</span></pre></div></div>

<p>Now the code I would normally write looks something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;"># speedtest2.py</span>
<span style="color: #808080; font-style: italic;"># testing the speed of two optimisations</span>
variable = <span style="color: #ff4500;">0</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">for</span> n <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span>, <span style="color: #ff4500;">10000000</span><span style="color: black;">&#41;</span>:
	<span style="color: #ff7700;font-weight:bold;">if</span> variable:
		i = <span style="color: #ff4500;">1</span>
	<span style="color: #ff7700;font-weight:bold;">else</span>:
		i = <span style="color: #ff4500;">0</span>
&nbsp;
	variable ^= <span style="color: #ff4500;">1</span> <span style="color: #808080; font-style: italic;"># XOR flip!</span></pre></div></div>

<p>So the next logical step would be to run both scripts through the python profiler, cProfile. My testing system is a stock Q6600 running Windows XP and Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45).<br />
Their technique:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">         <span style="color: #0000dd;">5</span> <span style="color: #000000; font-weight: bold;">function</span> calls in <span style="color:#800080;">5.626</span> CPU seconds
&nbsp;
   Ordered by<span style="color: #339933;">:</span> standard name
&nbsp;
   ncalls  tottime  percall  cumtime  percall filename<span style="color: #339933;">:</span>lineno<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">function</span><span style="color: #009900;">&#41;</span>
        <span style="color: #0000dd;">1</span>    <span style="color:#800080;">0.000</span>    <span style="color:#800080;">0.000</span>    <span style="color:#800080;">5.626</span>    <span style="color:#800080;">5.626</span> <span style="color: #339933;">&lt;</span>string<span style="color: #339933;">&gt;:</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">&lt;</span>module<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #0000dd;">1</span>    <span style="color:#800080;">5.313</span>    <span style="color:#800080;">5.313</span>    <span style="color:#800080;">5.625</span>    <span style="color:#800080;">5.625</span> speedtest1.<span style="color: #202020;">py</span><span style="color: #339933;">:</span><span style="color: #0000dd;">3</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">&lt;</span>module<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #0000dd;">1</span>    <span style="color:#800080;">0.000</span>    <span style="color:#800080;">0.000</span>    <span style="color:#800080;">5.626</span>    <span style="color:#800080;">5.626</span> <span style="color: #009900;">&#123;</span>execfile<span style="color: #009900;">&#125;</span>
        <span style="color: #0000dd;">1</span>    <span style="color:#800080;">0.000</span>    <span style="color:#800080;">0.000</span>    <span style="color:#800080;">0.000</span>    <span style="color:#800080;">0.000</span> <span style="color: #009900;">&#123;</span>method <span style="color: #ff0000;">'disable'</span> of <span style="color: #ff0000;">'_lsprof.Profiler'</span> objects<span style="color: #009900;">&#125;</span>
        <span style="color: #0000dd;">1</span>    <span style="color:#800080;">0.313</span>    <span style="color:#800080;">0.313</span>    <span style="color:#800080;">0.313</span>    <span style="color:#800080;">0.313</span> <span style="color: #009900;">&#123;</span>range<span style="color: #009900;">&#125;</span></pre></div></div>

<p>My technique:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">         <span style="color: #0000dd;">5</span> <span style="color: #000000; font-weight: bold;">function</span> calls in <span style="color:#800080;">4.619</span> CPU seconds
&nbsp;
   Ordered by<span style="color: #339933;">:</span> standard name
&nbsp;
   ncalls  tottime  percall  cumtime  percall filename<span style="color: #339933;">:</span>lineno<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">function</span><span style="color: #009900;">&#41;</span>
        <span style="color: #0000dd;">1</span>    <span style="color:#800080;">0.000</span>    <span style="color:#800080;">0.000</span>    <span style="color:#800080;">4.619</span>    <span style="color:#800080;">4.619</span> <span style="color: #339933;">&lt;</span>string<span style="color: #339933;">&gt;:</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">&lt;</span>module<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #0000dd;">1</span>    <span style="color:#800080;">4.323</span>    <span style="color:#800080;">4.323</span>    <span style="color:#800080;">4.618</span>    <span style="color:#800080;">4.618</span> speedtest2.<span style="color: #202020;">py</span><span style="color: #339933;">:</span><span style="color: #0000dd;">3</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">&lt;</span>module<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #0000dd;">1</span>    <span style="color:#800080;">0.000</span>    <span style="color:#800080;">0.000</span>    <span style="color:#800080;">4.619</span>    <span style="color:#800080;">4.619</span> <span style="color: #009900;">&#123;</span>execfile<span style="color: #009900;">&#125;</span>
        <span style="color: #0000dd;">1</span>    <span style="color:#800080;">0.000</span>    <span style="color:#800080;">0.000</span>    <span style="color:#800080;">0.000</span>    <span style="color:#800080;">0.000</span> <span style="color: #009900;">&#123;</span>method <span style="color: #ff0000;">'disable'</span> of <span style="color: #ff0000;">'_lsprof.Profiler'</span> objects<span style="color: #009900;">&#125;</span>
        <span style="color: #0000dd;">1</span>    <span style="color:#800080;">0.296</span>    <span style="color:#800080;">0.296</span>    <span style="color:#800080;">0.296</span>    <span style="color:#800080;">0.296</span> <span style="color: #009900;">&#123;</span>range<span style="color: #009900;">&#125;</span></pre></div></div>

<p>As you can see from the profile reports, there is just over a whole second of difference in CPU time for each of the scripts on my system, with the &#8220;optimised&#8221; one actually being the slower one.</p>
<p>While it might seem like I am out to attack these optimisation posts, I actually think they are a good idea. It is interesting to see other people&#8217;s coding techniques, but one must remember that computers are pseudo-unique and that something might not work better for everyone. I suggest that people who post these techniques on their blogs should provide sample code as well, so the technique can be evaluated on a case by case basis.</p>
<p><strong>Note:</strong> I didn&#8217;t mention the poster of the article because it has little to do with the problem at hand. I&#8217;m sure google will help you find it if you want it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.penjuinlabs.com/blog/?feed=rss2&amp;p=56</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Graduation</title>
		<link>http://www.penjuinlabs.com/blog/?p=51</link>
		<comments>http://www.penjuinlabs.com/blog/?p=51#comments</comments>
		<pubDate>Fri, 21 Nov 2008 02:33:33 +0000</pubDate>
		<dc:creator>jeremy</dc:creator>
				<category><![CDATA[uncategorized]]></category>

		<guid isPermaLink="false">http://www.penjuinlabs.com/blog/?p=51</guid>
		<description><![CDATA[As of today, I no longer attend school! I envisage that this will leave me with much more free time for my own projects. I also expect to update this blog a lot more with little guides, so watch this space!
]]></description>
			<content:encoded><![CDATA[<p>As of today, I no longer attend school! I envisage that this will leave me with much more free time for my own projects. I also expect to update this blog a lot more with little guides, so watch this space!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.penjuinlabs.com/blog/?feed=rss2&amp;p=51</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using lambda in Python</title>
		<link>http://www.penjuinlabs.com/blog/?p=44</link>
		<comments>http://www.penjuinlabs.com/blog/?p=44#comments</comments>
		<pubDate>Thu, 02 Oct 2008 03:19:25 +0000</pubDate>
		<dc:creator>jeremy</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.penjuinlabs.com/blog/?p=44</guid>
		<description><![CDATA[SPOILER ALERT: This post contains a solution to Project Euler problem 20.
I gave some more Project Euler a go last week and when I came across problem 20, I knew it was time for me to finally learn how to use closures. I could not find much accessible information for beginners, so I figured I would [...]]]></description>
			<content:encoded><![CDATA[<p><strong>SPOILER ALERT:</strong> This post contains a solution to Project Euler problem 20.</p>
<p>I gave some more Project Euler a go last week and when I came across problem 20, I knew it was time for me to finally learn how to use closures. I could not find much accessible information for beginners, so I figured I would write up what I discovered. That means it&#8217;s time to grab a cup of coffee and put on your theory cap, because this topic needs a bit of explanation.<span id="more-44"></span></p>
<p><strong>Closures and Anonymous Functions</strong></p>
<p>It is important to make a distinction between these two concepts. Too often I have seen technical books and manuals introduce them as the same thing.</p>
<p>A closure is a very important part of recursive programming. To unashamedly copy Wikipedia&#8217;s definition, a closure is, <em>&#8220;a function that is evaluated in an environment containing one or more bound variables.&#8221;</em> This means that there are one or more variables that are useable by the function in the form of local variables or arguments.</p>
<p>An anonymous function is a function that is not given a name.</p>
<p><strong>Closure + Anonymous Function = ?</strong></p>
<p>My suspicion as to why people so many people get closures and anonymous functions mixed up is because in python, they are both used for 99% of cases. The keyword used in python for this is <tt>lambda</tt>. There are also many recursion specific functions, but I will only be mentioning <tt>map()</tt> and <tt>reduce()</tt>.</p>
<p>So first up, lets look at how one would solve this problem without recursion.</p>
<p><strong>Project Euler Problem 20</strong><br />
<code>n! means n*(n-1)*...*3*2*1<br />
Find the sum of the digits in the number 100!</code></p>
<p>This is easily solvable with a few for loops:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;"># problem20_norecursion.py</span>
<span style="color: #808080; font-style: italic;"># solving problem 20 without using recursion techniques</span>
&nbsp;
factorial_result = <span style="color: #ff4500;">1</span>
sum_result = <span style="color: #ff4500;">0</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">for</span> number <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>,<span style="color: #ff4500;">101</span><span style="color: black;">&#41;</span>: <span style="color: #808080; font-style: italic;"># from 1 to 100</span>
	factorial_result <span style="color: #66cc66;">*</span>= number
&nbsp;
<span style="color: #ff7700;font-weight:bold;">for</span> number <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>factorial_result<span style="color: black;">&#41;</span>:
	sum_result += <span style="color: #008000;">int</span><span style="color: black;">&#40;</span>number<span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">print</span> sum_result</pre></div></div>

<p>Now this works very well, but the problem seems like it can be solved in less than 7 lines. It is only two very simple operations that could be easily combined.</p>
<p><strong>lambda</strong><br />
As mentioned previously, <tt>lambda</tt> allows us to create both anonymous functions and use closures in python. The name is derived from the calculus of recursion and function definition, lambda calculus. Creating an anonymous function is just as easy as creating a regular function, only it needs to be assigned somewhere so you can access it. Return values are not needed; they are handled automatically by the interpreter. For now, we will just use a variable. Anyone who has done a reasonable amount of python before should understand what is going on in this example:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;"># lambda_examples.py</span>
<span style="color: #808080; font-style: italic;"># examples of the usage of lambda</span>
&nbsp;
f = <span style="color: #ff7700;font-weight:bold;">lambda</span> x: x+<span style="color: #ff4500;">1</span>
g = <span style="color: #ff7700;font-weight:bold;">lambda</span> x: x<span style="color: #66cc66;">*</span><span style="color: #ff4500;">2</span>
h = <span style="color: #ff7700;font-weight:bold;">lambda</span> x, y: x<span style="color: #66cc66;">*</span>y
&nbsp;
<span style="color: #ff7700;font-weight:bold;">print</span> f<span style="color: black;">&#40;</span><span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> g<span style="color: black;">&#40;</span><span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> h<span style="color: black;">&#40;</span><span style="color: #ff4500;">5</span>,<span style="color: #ff4500;">6</span><span style="color: black;">&#41;</span></pre></div></div>

<p>And the output is:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff4500;">6</span>
<span style="color: #ff4500;">10</span>
<span style="color: #ff4500;">30</span></pre></div></div>

<p>As you can see, the syntax is identical to a <tt>def</tt> statement.<br />
<strong>map() and reduce()</strong><br />
<tt>map()</tt> and <tt>reduce()</tt> are the two most useful recursion functions in python (in my opinion anyway). Let&#8217;s take a closer look at them.</p>
<p>The <tt>map()</tt> function takes two arguments, the first being a function with one argument and second being a sequence. It is essentially a condensed for-loop; it takes the function and feeds it every element in the sequence individually and returns a list of the results. The trick here is to not create a function outside the map() brackets, rather to create a temporary one and pass it as an argument using <tt>lambda</tt>. A few examples might help explain this:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;"># examples demonstrating the map() function</span>
&nbsp;
the_list = <span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span>, <span style="color: #ff4500;">2</span>, <span style="color: #ff4500;">3</span>, <span style="color: #ff4500;">4</span>, <span style="color: #ff4500;">5</span>, <span style="color: #ff4500;">6</span>, <span style="color: #ff4500;">7</span>, <span style="color: #ff4500;">8</span><span style="color: black;">&#93;</span>
new_list = <span style="color: #008000;">map</span><span style="color: black;">&#40;</span><span style="color: #ff7700;font-weight:bold;">lambda</span> x: x+<span style="color: #ff4500;">1</span>, the_list<span style="color: black;">&#41;</span>
<span style="color: #808080; font-style: italic;"># new_list = [2, 3, 4, 5, 6, 7, 8, 9]</span>
&nbsp;
new_list = <span style="color: #008000;">map</span><span style="color: black;">&#40;</span><span style="color: #ff7700;font-weight:bold;">lambda</span> x: x<span style="color: #66cc66;">%</span>2, the_list<span style="color: black;">&#41;</span>
<span style="color: #808080; font-style: italic;"># new_list = [1, 0, 1, 0, 1, 0, 1, 0]</span></pre></div></div>

<p>Simple, isn&#8217;t it?</p>
<p><tt>reduce()</tt> is slightly more complicated. It again takes two arguments, however the function now must take two arguments. This is because after performing the operation, the return value is passed as the first argument of the next iteration. So having</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">result = <span style="color: #008000;">reduce</span><span style="color: black;">&#40;</span><span style="color: #ff7700;font-weight:bold;">lambda</span> x,y: x<span style="color: #66cc66;">*</span>y, <span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>,<span style="color: #ff4500;">10</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>is equivalent to</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">result = <span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span><span style="color: #66cc66;">*</span><span style="color: #ff4500;">2</span><span style="color: black;">&#41;</span><span style="color: #66cc66;">*</span><span style="color: #ff4500;">3</span><span style="color: black;">&#41;</span><span style="color: #66cc66;">*</span><span style="color: #ff4500;">4</span><span style="color: black;">&#41;</span><span style="color: #66cc66;">*</span><span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span><span style="color: #66cc66;">*</span><span style="color: #ff4500;">6</span><span style="color: black;">&#41;</span><span style="color: #66cc66;">*</span><span style="color: #ff4500;">7</span><span style="color: black;">&#41;</span><span style="color: #66cc66;">*</span><span style="color: #ff4500;">8</span><span style="color: black;">&#41;</span><span style="color: #66cc66;">*</span><span style="color: #ff4500;">9</span><span style="color: black;">&#41;</span></pre></div></div>

<p>It is pretty obvious which looks nicer! Hopefully you can see that <tt>reduce()</tt> will allow us to do what we need to solve this problem.</p>
<p><strong>Problem 20 with Recursion</strong></p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;"># problem20_recursion.py</span>
<span style="color: #808080; font-style: italic;"># solving problem 20 using recursion techniques</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #008000;">reduce</span><span style="color: black;">&#40;</span> <span style="color: #ff7700;font-weight:bold;">lambda</span> x,y: <span style="color: #008000;">int</span><span style="color: black;">&#40;</span>x<span style="color: black;">&#41;</span>+<span style="color: #008000;">int</span><span style="color: black;">&#40;</span>y<span style="color: black;">&#41;</span>, <span style="color: #008000;">str</span><span style="color: black;">&#40;</span> <span style="color: #008000;">reduce</span><span style="color: black;">&#40;</span> <span style="color: #ff7700;font-weight:bold;">lambda</span> x, y: x<span style="color: #66cc66;">*</span>y, <span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>,<span style="color: #ff4500;">101</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span> <span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Granted, this is not the prettiest line of code I have ever written but it clearly demonstrates how recursion allows you to pack significant complexities into a single statement. <tt>lambda</tt> with a few other functions means you can turn whole loops into a single line or perform complex operations with simple lines of code. </p>
<p>Besides, all the cool kids are doing it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.penjuinlabs.com/blog/?feed=rss2&amp;p=44</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Using the vs1002 MP3 IC with an AVR</title>
		<link>http://www.penjuinlabs.com/blog/?p=42</link>
		<comments>http://www.penjuinlabs.com/blog/?p=42#comments</comments>
		<pubDate>Sun, 07 Sep 2008 00:51:36 +0000</pubDate>
		<dc:creator>jeremy</dc:creator>
				<category><![CDATA[electronics]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[avr]]></category>

		<guid isPermaLink="false">http://www.penjuinlabs.com/blog/?p=42</guid>
		<description><![CDATA[In one of my various orders to Sparkfun, I picked up a vs1002 IC on a breakout board. Just yesterday I got round to having a good look at it, and I figured if I show my code then others will not have to do the boilerplate and just get it working. My setup is [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-medium wp-image-43" title="VS1002 breakout" src="http://www.penjuinlabs.com/blog/wp-content/uploads/2008/09/00519-03-l-300x300.jpg" alt="A MP3 decoding IC" width="300" height="300" />In one of my various orders to Sparkfun, I picked up a vs1002 IC on a breakout board. Just yesterday I got round to having a good look at it, and I figured if I show my code then others will not have to do the boilerplate and just get it working. My setup is a ATMEGA88 running at 3.686MHz on a STK500 board, but it should work for most anyone with a decent clock speed. Just remember that all code is ATMEGA88 specific and may need to be changed for other devices.</p>
<p>Things that may be useful: <a href="http://www.sparkfun.com/commerce/product_info.php?products_id=519">the Sparkfun page</a>, <a href="http://www.vlsi.fi/datasheets/vs1002.pdf">the datasheet</a>.</p>
<p><strong>Communication modes</strong></p>
<p>(Note: The vs1002 has a backwards compatability mode with the vs1001. We will <em>not </em>be using it)</p>
<p>The vs1002 IC does all meaningful communication over the SPI port. It has two submodes if you will, one being SCI (Serial Command Interface) and the other being SDI (Serial Data Interface). SCI is for things like play control, reading and writing registers and small technical changes. Conversely, SDI is there for MP3 data and a few testing modes.</p>
<p>Since the AVR has only one SPI bus, we will be sharing the CS (Chip Select) line with both submodes.<br />
<span id="more-42"></span><br />
<strong>Ok, enough. Get to the code!</strong></p>
<p>Not quite yet, first we need to wire it up! Since it is a fairly simple circuit, I am going to put my wiring in list form (AVR -&gt; VS1002):</p>
<ul>
<li>SS -&gt; CS</li>
<li>MOSI -&gt; SI</li>
<li>MISO -&gt; SO</li>
<li>SCK -&gt; SCLK</li>
</ul>
<div>On top of these, you will need to</div>
<div>
<ul>
<li>Connect the GND pin to GND and the Vin pin to +3.3v</li>
<li>Wire the DREQ pin to an input on the AVR (if you intend to expand outside this tutorial)</li>
</ul>
</div>
<div><strong>Wait, what is DREQ?</strong></div>
<div>Good question. DREQ is a data control pin on the vs1002. It is essentially an active-low busy signal. It should be checked once for every 32 bits of data sent, but since we will only be using simple commands, there is no use for it now.</div>
<div><strong>Setting up SPI</strong></div>
<div>The first thing that we need to do is set up SPI. If you have ever used SPI before, most of this will look familiar. The basic idea of SPI is that the master generates a clock (that is, a period of time where the clock line is high, and then an equal period of time where the clock line is low) and just after the change of levels on the clock line (either high to low or low to high but <em>not</em> both) the values will be read. The AVR will handle all this in the background, but it is important to remember one thing: sending a byte and recieving one is a single data packet. You do not just send a byte, and then ask for a byte. When the AVR sends a bit, it changes the MOSI line. At the same time, the slave will be changing the MISO line. Thus, after we write to the SPI data register and the byte is sent, we need to check the data register for our received byte.</div>
<div>This code is fairly self explanatory, look at your AVR datasheet or the comments to see what each line does.</div>
<div>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//spi.h</span>
<span style="color: #666666; font-style: italic;">// spi functions </span>
&nbsp;
<span style="color: #666666; font-style: italic;">// pin setup</span>
<span style="color: #339933;">#define DDR_SPI 	DDRB</span>
<span style="color: #339933;">#define PORT_SPI	PORTB</span>
&nbsp;
<span style="color: #339933;">#define DD_CS	2</span>
<span style="color: #339933;">#define DD_MOSI 3</span>
<span style="color: #339933;">#define DD_MISO 4</span>
<span style="color: #339933;">#define DD_SCK	5</span>
&nbsp;
<span style="color: #993333;">void</span> spi_init<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// init the SPI subsystem</span>
&nbsp;
<span style="color: #993333;">void</span> cs_low<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// helpers</span>
<span style="color: #993333;">void</span> cs_high<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #993333;">char</span> spi_send<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> byte<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// send a byte; return rx byte</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//spi.c</span>
<span style="color: #666666; font-style: italic;">// spi helper functions</span>
&nbsp;
<span style="color: #339933;">#include &lt;avr/io.h&gt;</span>
&nbsp;
<span style="color: #339933;">#include &quot;spi.h&quot;</span>
&nbsp;
<span style="color: #993333;">void</span> spi_init<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	DDR_SPI <span style="color: #339933;">=</span> <span style="color: #208080;">0xFF</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// set the whole port to output</span>
&nbsp;
	DDR_SPI <span style="color: #339933;">&amp;=</span> ~<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span> <span style="color: #339933;">&lt;&lt;</span> DD_MISO<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// change back to input</span>
&nbsp;
	SPCR <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span> <span style="color: #339933;">&lt;&lt;</span> SPE<span style="color: #009900;">&#41;</span> <span style="color: #339933;">|</span> <span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span> <span style="color: #339933;">&lt;&lt;</span> MSTR<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// set spi clock rate to fck/4</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> cs_low<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	PORT_SPI <span style="color: #339933;">&amp;=</span> ~<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span> <span style="color: #339933;">&lt;&lt;</span> DD_CS<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> cs_high<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	PORT_SPI <span style="color: #339933;">|=</span> <span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span> <span style="color: #339933;">&lt;&lt;</span> DD_CS<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">char</span> spi_send<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> byte<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	SPDR <span style="color: #339933;">=</span> byte<span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//send byte</span>
&nbsp;
	<span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #009900;">&#40;</span>SPSR <span style="color: #339933;">&amp;</span> <span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span> <span style="color: #339933;">&lt;&lt;</span> SPIF<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//wait until its done</span>
	<span style="color: #b1b100;">return</span> SPDR<span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//return the rx byte</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

</div>
<div><strong>VS1002 Nuances</strong></div>
<div>The different command modes for the vs1002 means that there are two distinct ways of sending commands to the chip. To send an SCI byte, CS needs to be set to low. To send a SDI byte, CS needs to be set to high. The basic form that we are going to use for a SCI command is: set CS low, send read/write, send address, send data/get data, set CS high. For a SDI command, you just set CS to high and start sending bytes. Again, the code below is fairly self explanatory.</div>
<div>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//vs1002.h</span>
<span style="color: #666666; font-style: italic;">// chip control functions</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//SCI_MODE register defines (p. 26 datasheet)</span>
<span style="color: #339933;">#define SM_DIFF			0</span>
<span style="color: #339933;">#define SM_SETTOZERO		1</span>
<span style="color: #339933;">#define SM_RESET		2</span>
<span style="color: #339933;">#define SM_OUTOFWAV		3</span>
<span style="color: #339933;">#define SM_PDOWN		4</span>
<span style="color: #339933;">#define SM_TESTS		5</span>
<span style="color: #339933;">#define	SM_STREAM		6</span>
<span style="color: #339933;">#define SM_PLUSV		7</span>
<span style="color: #339933;">#define	SM_DACT			8</span>
<span style="color: #339933;">#define	SM_SDIORD		9</span>
<span style="color: #339933;">#define	SM_SDISHARE		10</span>
<span style="color: #339933;">#define	SM_SDINEW		11</span>
<span style="color: #339933;">#define	SM_ADPCM		12</span>
<span style="color: #339933;">#define	SM_ADPCM_HP		13</span>
&nbsp;
<span style="color: #993333;">int</span> sci_read<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> address<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// serial command interface read/write funcs</span>
<span style="color: #993333;">void</span> sci_write<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> address<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> data<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #993333;">void</span> send_sinewave<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> pitch<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// send the sinewave test</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//vs1002.c</span>
<span style="color: #666666; font-style: italic;">// chip control functions</span>
&nbsp;
<span style="color: #339933;">#include &lt;avr/io.h&gt;</span>
&nbsp;
<span style="color: #339933;">#include &quot;spi.h&quot;</span>
<span style="color: #339933;">#include &quot;vs1002.h&quot;</span>
&nbsp;
<span style="color: #993333;">int</span> sci_read<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> address<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> temp<span style="color: #339933;">;</span>
&nbsp;
	cs_low<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	spi_send<span style="color: #009900;">&#40;</span><span style="color: #208080;">0x03</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//send read command, don't worry about return byte</span>
	spi_send<span style="color: #009900;">&#40;</span>address<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//now send the address to read</span>
&nbsp;
	temp <span style="color: #339933;">=</span> spi_send<span style="color: #009900;">&#40;</span><span style="color: #208080;">0x00</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//dummy byte to get out data MSBs</span>
	temp <span style="color: #339933;">&lt;&lt;=</span> <span style="color: #0000dd;">8</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//shift it along so we can fit more data in</span>
&nbsp;
	temp <span style="color: #339933;">+=</span> spi_send<span style="color: #009900;">&#40;</span><span style="color: #208080;">0x00</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// get the LSB</span>
&nbsp;
	cs_high<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">return</span> temp<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> sci_write<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> address<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> data<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	cs_low<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	spi_send<span style="color: #009900;">&#40;</span><span style="color: #208080;">0x02</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//send write command</span>
	spi_send<span style="color: #009900;">&#40;</span>address<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//send address we are going to write to</span>
&nbsp;
	spi_send<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>data <span style="color: #339933;">&gt;&gt;</span> <span style="color: #0000dd;">8</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span> <span style="color: #208080;">0xFF</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//send the first 8 MSBs of the data</span>
	spi_send<span style="color: #009900;">&#40;</span>data <span style="color: #339933;">&amp;</span> <span style="color: #208080;">0xFF</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//send the LSBs</span>
&nbsp;
	cs_high<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> send_sinewave<span style="color: #009900;">&#40;</span><span style="color: #993333;">char</span> pitch<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	cs_high<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//this is different to SCI, it is data over SDI (see p.21 datasheet)</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">/* we need to send the following bytes (see p.35)
		0x53	0xEF	0x6E
		0	0	0	0
	*/</span>
&nbsp;
	spi_send<span style="color: #009900;">&#40;</span><span style="color: #208080;">0x53</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	spi_send<span style="color: #009900;">&#40;</span><span style="color: #208080;">0xEF</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	spi_send<span style="color: #009900;">&#40;</span><span style="color: #208080;">0x6E</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	spi_send<span style="color: #009900;">&#40;</span>pitch<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">4</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> spi_send<span style="color: #009900;">&#40;</span><span style="color: #208080;">0x00</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// send the filler bytes</span>
&nbsp;
	cs_low<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

</div>
<div><strong>Let&#8217;s mix it all together!</strong></div>
<div>The main code is the simplest out of the lot. It basically: sets up SPI, sets CS to high, sets the SCI_MODE register to tell the chip what we want to do and then sends the sinewave command. Without further ado, here it is:</div>
<div>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//vs1002test.c</span>
<span style="color: #666666; font-style: italic;">// this program will initialise the vs1002 ic and send it the sine wave test command</span>
&nbsp;
<span style="color: #339933;">#include &lt;avr/io.h&gt;</span>
&nbsp;
<span style="color: #339933;">#include &quot;spi.h&quot;</span>
<span style="color: #339933;">#include &quot;vs1002.h&quot;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">void</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	spi_init<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//set up SPI registers</span>
	cs_high<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// probably a good idea</span>
&nbsp;
	sci_write<span style="color: #009900;">&#40;</span><span style="color: #208080;">0x00</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #339933;">&lt;&lt;</span>SM_TESTS<span style="color: #009900;">&#41;</span><span style="color: #339933;">|</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #339933;">&lt;&lt;</span>SM_SDISHARE<span style="color: #009900;">&#41;</span><span style="color: #339933;">|</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #339933;">&lt;&lt;</span>SM_STREAM<span style="color: #009900;">&#41;</span><span style="color: #339933;">|</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #339933;">&lt;&lt;</span>SM_SDINEW<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	cs_low<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// for data interface</span>
	send_sinewave<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">170</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

</div>
<div>Now hook up an oscilloscope (mine was graciously donated) and you should get a nice sine wave! I will try to put a picture of it up soon.</div>
<div>I will probably post some more code once I have the chip working better. I can get it to play MP3s, but they are not streaming fast enough over UART so they sound off key and distorted. If you have any questions, leave me a comment and I will endeavour to help but I&#8217;m new to this chip, so no promises <img src='http://www.penjuinlabs.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> .</div>
<div><strong>Update:</strong> The code had a bug which required you to use the BSYNC and DREQ lines. This is fixed by setting the SM_SDINEW bit in the initial setup. This bit was in my original code, but it appears that wordpress didn&#8217;t like my use of &lt;&lt; so it messed the code up. Thanks to Paul and zeneslev for picking me up on it!</div>
]]></content:encoded>
			<wfw:commentRss>http://www.penjuinlabs.com/blog/?feed=rss2&amp;p=42</wfw:commentRss>
		<slash:comments>35</slash:comments>
		</item>
	</channel>
</rss>
