<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Mekonikuv blog</title>
	<atom:link href="http://mekonik.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://mekonik.wordpress.com</link>
	<description></description>
	<lastBuildDate>Mon, 19 Dec 2011 14:06:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='mekonik.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Mekonikuv blog</title>
		<link>http://mekonik.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://mekonik.wordpress.com/osd.xml" title="Mekonikuv blog" />
	<atom:link rel='hub' href='http://mekonik.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Mathematica tricks and notes</title>
		<link>http://mekonik.wordpress.com/2009/12/15/mathematica-tricks/</link>
		<comments>http://mekonik.wordpress.com/2009/12/15/mathematica-tricks/#comments</comments>
		<pubDate>Wed, 16 Dec 2009 01:14:44 +0000</pubDate>
		<dc:creator>mekonik</dc:creator>
				<category><![CDATA[Mathematica]]></category>
		<category><![CDATA[Mathematica bugs]]></category>
		<category><![CDATA[Mathematica tricks]]></category>

		<guid isPermaLink="false">http://mekonik.wordpress.com/?p=127</guid>
		<description><![CDATA[I created a page that contains my notes on Wolfram&#8217;s Mathematica 6. Mathematica notes<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mekonik.wordpress.com&amp;blog=6791281&amp;post=127&amp;subd=mekonik&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I created a <a href="http://mekonik.wordpress.com/mathematica-notes/">page</a> that contains my notes on Wolfram&#8217;s Mathematica 6.</p>
<p><a href="http://mekonik.wordpress.com/mathematica-notes/">Mathematica notes</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mekonik.wordpress.com/127/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mekonik.wordpress.com/127/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mekonik.wordpress.com/127/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mekonik.wordpress.com/127/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mekonik.wordpress.com/127/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mekonik.wordpress.com/127/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mekonik.wordpress.com/127/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mekonik.wordpress.com/127/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mekonik.wordpress.com/127/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mekonik.wordpress.com/127/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mekonik.wordpress.com/127/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mekonik.wordpress.com/127/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mekonik.wordpress.com/127/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mekonik.wordpress.com/127/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mekonik.wordpress.com&amp;blog=6791281&amp;post=127&amp;subd=mekonik&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mekonik.wordpress.com/2009/12/15/mathematica-tricks/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">mekonik</media:title>
		</media:content>
	</item>
		<item>
		<title>Variation on Dawkins&#8217; Weasel program</title>
		<link>http://mekonik.wordpress.com/2009/12/06/variation-on-dawkins-weasel-program/</link>
		<comments>http://mekonik.wordpress.com/2009/12/06/variation-on-dawkins-weasel-program/#comments</comments>
		<pubDate>Mon, 07 Dec 2009 00:38:26 +0000</pubDate>
		<dc:creator>mekonik</dc:creator>
				<category><![CDATA[Mathematica]]></category>
		<category><![CDATA[evolution]]></category>
		<category><![CDATA[natural selection]]></category>
		<category><![CDATA[Richard Dawkins]]></category>
		<category><![CDATA[weasel program]]></category>

		<guid isPermaLink="false">http://mekonik.wordpress.com/?p=97</guid>
		<description><![CDATA[Recently, I implemented a Mathematica 6 version of the Weasel program by Richard Dawkins. It is a simple demonstration of the power of the process of cumulative natural selection as compared to random process. The usual implementation starts with a random string of 28 characters. Then in each generation, it makes say 100 copies of [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mekonik.wordpress.com&amp;blog=6791281&amp;post=97&amp;subd=mekonik&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Recently, I implemented a <a href="http://www.wolfram.com/">Mathematica</a> 6 version of the <a href="http://en.wikipedia.org/wiki/Weasel_program">Weasel program</a> by <a href="http://richarddawkins.net/">Richard Dawkins</a>. It is a simple demonstration of the power of the process of cumulative natural selection as compared to random process.<span id="more-97"></span></p>
<p>The usual implementation starts with a random string of 28 characters. Then in each generation, it makes say 100 copies of the string, with a small chance (say 5%) per character of that character being replaced by a random character. Then it selects the string that is closest to the target sequence (the highest number of correct characters with correct positions)</p>
<pre>METHINKS IT IS LIKE A WEASEL
</pre>
<p>and repeats the process until one of the copies exactly matches the target sequence.</p>
<p>The program is not supposed to model any real biological system. But when one allows for insertions and deletions of random letters, this simple modification of the algorithm moves it somewhat closer to how DNA mutates. It turns out that an implementation of such modification is straightforward in Mathematica 6.</p>
<h2>Implementation</h2>
<pre>alphabet = CharacterRange["a", "z"]~Join~{" "};
source = Characters[""];
target = Characters["methinks it is like a weasel"];
numindividuals = 50;
maxgenerations = 500;
(* Mutation rates: {deletion, insertion, replacement} *)
mutationrates = {0.02, 0.02, 0.02};

With[{mr = Join[#, {1 - Total[#]}] &amp;[mutationrates]},
 mutate[l_] := Flatten[
 If[RandomReal[] &lt; mr[[2]], {RandomChoice[alphabet], #}, #] &amp;[
 RandomChoice[
 Unevaluated[
 mr -&gt; {{}, {#, RandomChoice[alphabet]},
 RandomChoice[alphabet], #}]] &amp; /@ l
 ]
 ]

 ]
Timing[res =
 NestWhileList[
 SortBy[Table[mutate[#], {numindividuals}],
 EditDistance[target, #] &amp;][[1]] &amp;,
 source, (# != target) &amp;,
 1, maxgenerations];
 ]

(* Printout *)
Column[StringJoin /@ res[[;; ;; 10]]]
ListPlot[EditDistance[target, #] &amp; /@ res, PlotRange -&gt; All,
 Filling -&gt; Axis, AxesOrigin -&gt; {0, 0}]
</pre>
<p>In this code, we start with an empty string &#8220;&#8221;. In each generation, we produce a pool of 50 individuals (copies). While creating a copy, each letter in the parent string has a 2% chance to be erased, 2% chance to be changed to a random letter and 2% chance that a random letter will be inserted next to it. Then we sort the pool with respect to the <a href="http://en.wikipedia.org/wiki/Levenshtein_distance">Levenshtein edit distance</a> from the target string. We select the string with the first string with the smallest distance and use it as the parent string for the copies in the next generation. We repeat the process until one of the copies exactly matches the target string or when we achieve the maximal number of generations, whichever comes first.</p>
<h2>Output</h2>
<p>The following is a sample output of the program:</p>
<pre>h ee
  il eal
es i lie weael
etn i s lie aweael
eth i is lie aweael
ethns i is lie a eael
ethns i is lie a eael
ethns i is lie a weael
ethns i is lie a weael
ethnk i is lie a weasel
ethnks i is lie a weasel
ethnks i is lie a weasel
ethnks i is like a weasel
ethnks i is like a weasel
ethnks i is like a weasel
ethnks i is like a weasel
ethnks i is like a weasel
ethnks i is like a weasel
methnks i is like a weasel
methnks i is like a weasel
methnks i is like a weasel
methnks i is like a weasel
methnks i is like a weasel
methiks i is like a weasel
methiks it is like a weasel
methiks it is like a weasel
methiks it is like a weasel
methiks it is like a weasel
methiks it is like a weasel
</pre>
<p>Note that the printout shows only every 10th generation. You can see that there is no locking of correct letter, for example w was removed and replaced by a space from line 5 to line 6, even though it was in the correct spot. The following figure show the evolution of the edit distance of the best string in each generation:</p>
<p><a href="http://mekonik.files.wordpress.com/2009/12/weasel.png"><img class="alignnone size-full wp-image-122" title="Sample output of a weasel program" src="http://mekonik.files.wordpress.com/2009/12/weasel.png?w=500&#038;h=320" alt="" width="500" height="320" /></a></p>
<p>And this is a sample output for an initial string &#8220;anything is possible for this weasel code&#8221;:</p>
<pre>anything is possible for this weasel code
aptaink zs fukr t wasel
taink s k  wasel
think s k  wasel
thinks is lk  easel
mhinks is ike  weasel
meinki is ike a weasel
meink i is ike a weasel
meink i is ike a weasel
meink i i like a weasel
meink i i like a weasel
meink i is like a weasel
meink i is like a weasel
meink i is like a weasel
meink i is like a weasel
meink i is like a weasel
meink i is like a weasel
meink i is like a weasel
mehnk i is like a weasel
methnk it is like a weasel
methnk it is like a weasel
methnk it is like a weasel
methink it is like a weasel
methink it is like a weasel
methink it is like a weasel
methink it is like a weasel
methink it is like a weasel
methink it is like a weasel
methink it is like a weasel
methink it is like a weasel
methink it is like a weasel
methink it is like a weasel
methink it is like a weasel
methink it is like a weasel
</pre>
<div id="_mcePaste" style="overflow:hidden;position:absolute;left:-10000px;top:54px;width:1px;height:1px;">
<h1 id="firstHeading" class="firstHeading">Levenshtein distance</h1>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mekonik.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mekonik.wordpress.com/97/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mekonik.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mekonik.wordpress.com/97/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mekonik.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mekonik.wordpress.com/97/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mekonik.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mekonik.wordpress.com/97/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mekonik.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mekonik.wordpress.com/97/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mekonik.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mekonik.wordpress.com/97/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mekonik.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mekonik.wordpress.com/97/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mekonik.wordpress.com&amp;blog=6791281&amp;post=97&amp;subd=mekonik&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mekonik.wordpress.com/2009/12/06/variation-on-dawkins-weasel-program/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">mekonik</media:title>
		</media:content>

		<media:content url="http://mekonik.files.wordpress.com/2009/12/weasel.png" medium="image">
			<media:title type="html">Sample output of a weasel program</media:title>
		</media:content>
	</item>
		<item>
		<title>Comparison of kanji learning methods</title>
		<link>http://mekonik.wordpress.com/2009/12/06/comparison-of-kanji-learning-methods/</link>
		<comments>http://mekonik.wordpress.com/2009/12/06/comparison-of-kanji-learning-methods/#comments</comments>
		<pubDate>Sun, 06 Dec 2009 20:13:29 +0000</pubDate>
		<dc:creator>mekonik</dc:creator>
				<category><![CDATA[Japanese]]></category>
		<category><![CDATA[Mathematica]]></category>
		<category><![CDATA[heisig]]></category>
		<category><![CDATA[henshall]]></category>
		<category><![CDATA[kanji]]></category>
		<category><![CDATA[KANJIDIC2]]></category>

		<guid isPermaLink="false">http://mekonik.wordpress.com/?p=103</guid>
		<description><![CDATA[I stumbled upon an interesting statistical way of comparing various kanji learning systems when I played with XML kanji data available from Jim Breen&#8216;s kick-ass KANJIDIC2 project (XML version of his KANJIDIC project). I present the findings below. Motivation During my attempt to learn Japanese, I had  to find a good way to learn the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mekonik.wordpress.com&amp;blog=6791281&amp;post=103&amp;subd=mekonik&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I stumbled upon an interesting statistical way of comparing various kanji learning systems when I played with XML kanji data available from <a href="http://www.csse.monash.edu.au/~jwb/">Jim Breen</a>&#8216;s kick-ass <a href="http://www.csse.monash.edu.au/~jwb/kanjidic2/">KANJIDIC2 </a>project (XML version of his <a href="http://www.csse.monash.edu.au/~jwb/kanjidic.html">KANJIDIC </a> project). I present the findings below.<span id="more-103"></span></p>
<h2>Motivation</h2>
<p>During my attempt to learn Japanese, I had  to find a good way to learn the <em>kanji</em> characters. Even though I learned hiragana and katakana in a day or two and I mastered reading of these characters quite automatically while reading Japanese text, kanji turned to be a quite different story. At first I just tried remembering the shapes in the hope that they will stick in my memory, but it turned to be futile for me. As somebody who grew up with the Latin alphabet, I am terrible at remembering shapes, not to mention stroke order.</p>
<p>So I tried memorizing the shapes using <em>drills</em>, pretty much the way Japanese schoolkids learn in the elementary school. It didn&#8217;t take too long for me to realize how boring this method is. Also, kanji-a-day is not exactly the speed I was aiming for.</p>
<p>I looked around a bit and found two books that offered <em>mnemonics methods</em>, somewhat similar to each other. <a href="http://www.amazon.com/Remembering-Japanese-Characters-language-library/dp/0804820384/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1260070116&amp;sr=8-1">Guide to Remembering Japanese Characters</a> by Kenneth G. Henshall and <a href="http://www.amazon.com/Remembering-Kanji-Vol-Complete-Characters/dp/0824831659/ref=sr_1_4?ie=UTF8&amp;s=books&amp;qid=1260070185&amp;sr=1-4">Remembering the Kanji</a> by James W. Heisig. Both books contain about 2000 kanji and provide mnemonics for rapid learning. I eventually chose Heisig&#8217;s book since I think it is a more systematic way of learning, and the mnemonics focus more on the meaning than on the shape of kanji.</p>
<p>I think that for me, the book did what it promised to do. I&#8217;m able to recognize most of the books kanji, I can write the kanji in the correct stroke order (I think this is the strength of Heisig&#8217;s method compared to drills). I could even impress my Japanese friends by correcting their stroke order mistakes.</p>
<p>The main criticism of the book that you&#8217;ll find online is the ordering of characters. Almost all other systems teach the most frequent characters first. Heisig chooses a different approach, he groups characters according to <em>primitive elements</em> they contain. Primitive elements are parts of the kanji that are shared among multiple characters. Many of them are characters themselves. Thus learning characters that serve as primitive elements followed by characters containing them  as primitive elements in sequence reinforces the learning process. It worked great for me.  The drawback however is that you are learning a mix of common and rare kanji. Heisig is honest about this, and he states clearly in the introduction that the book is intended for self-study for those who want to master all 2000 most common characters.</p>
<h2>Frequency analysis</h2>
<p>A neat way to compare the ordering of the characters in the two books and also the order in which the characters are learned in Japanese elementary schools is to plot the frequency of use versus the order in which they are learned. All the data is available online thanks to the awesome work of <a href="http://www.csse.monash.edu.au/~jwb/">Jim Breen</a> et al. and his <a href="http://www.csse.monash.edu.au/~jwb/kanjidic2/">KANJIDIC2 </a>project. The data can be downloaded in XML format. This makes it easy to work with. I used Wolfram&#8217;s <a href="http://www.wolfram.com/">Mathematica</a> with its built-in ability to process XML data.</p>
<p>The kanjidic2.xml file contains an entry for each Japanese kanji. When available, the kanji entry contains the information about the grade in which it is learned and the Henshall&#8217;s and Heisig&#8217;s indexes that represent the order in which the character is learned in each of these books. Moreover, 2500 most-used characters contain the frequency-of-use ranking. The kanjidic2.xml file description states:</p>
<blockquote><p>The 2,500 most-used characters have a  ranking; &#8230; The frequency is a number from 1 to 2,500 that expresses the relative frequency of occurrence of a character in modern Japanese. This is based on a survey in <em><strong>newspapers</strong></em>, so it is <strong><em>biased </em></strong>towards kanji used in newspaper articles. The discrimination between the less frequently used kanji is not strong. (emphasis mine)</p></blockquote>
<p>So even though it has limitations, the ranking can still provide an useful comparison. As for the grade information, the kanjidic2.xml description says:</p>
<blockquote><p>1 through 6 indicate the grade in which 	the kanji is taught in Japanese schools. 8 indicates it is one of the 	remaining Jouyou Kanji to be learned in junior high school, and 9  	indicates it is a Jinmeiyou (for use in names) kanji.</p></blockquote>
<p>I produced 3 plots. I plotted the dependence of frequency-of-use ranking on Heisig&#8217;s index, Henshall&#8217;s index and the grade, respectively. I also included the characters that don&#8217;t appear in those learning systems but have frequency-of-use ranking to see which &#8220;common&#8221; kanji are omitted. The plots are below. The points to the right of the dashed line represent characters that have frequency-of-use ranking but don&#8217;t appear in the learning system. I added a random noise to the horizontal position of each of these points for the frequency-of-use ranking distribution to be apparent. I also added horizontal noise to the grade plot as the grades are integer values which would again hide the ranking distribution.</p>
<p><a href="http://mekonik.files.wordpress.com/2009/12/heisig1.png"><img class="alignnone size-full wp-image-111" title="Heisig's index vs. frequency-of-use" src="http://mekonik.files.wordpress.com/2009/12/heisig1.png?w=500&#038;h=317" alt="" width="500" height="317" /></a></p>
<p><a href="http://mekonik.files.wordpress.com/2009/12/henshall.png"><img class="alignnone size-full wp-image-115" title="Henshall's index vs. frequency-of-use ranking" src="http://mekonik.files.wordpress.com/2009/12/henshall.png?w=500&#038;h=317" alt="" width="500" height="317" /></a></p>
<p><a href="http://mekonik.files.wordpress.com/2009/12/grade.png"><img class="alignnone size-full wp-image-114" title="Grade of Japanese school when the kanji is learned vs. the frequency-of-use ranking" src="http://mekonik.files.wordpress.com/2009/12/grade.png?w=500&#038;h=317" alt="" width="500" height="317" /></a></p>
<h2>Interpretation</h2>
<p>The first plot confirms that the criticism of Heisig&#8217;s book is valid. There is no obvious correlation between the order in which Heisig presents the characters in his book and frequency of use. I would recommend his book only to those who wanna learn all 2042 kanji that it contains. On the other hand, the Heisig&#8217;s order makes for a more entertaining and effective learning, and I can&#8217;t stress enough how that is important for learning success.</p>
<p>Henshall&#8217;s book shows a much better correlation. The first half obviously presents characters in the frequency-of-use order. And so does the Japanese elementary school system. It is apparent to me that Henshall based his order on the grade system, presenting the 6 grades in the first half of his book and the high school characters (grades 8 and 9 in kanjidic2 data) in the second half.</p>
<p>Interestingly, the grade 1 contains some fairly uncommon characters such as 犬, 耳, 虫, 糸 and 貝, all with frequency-of-use ranking above 1300. But this is obviously an artifact and limitation of the frequency ranking source, <em>newspapers</em>. In fact, these characters are quite useful in basic Japanese.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mekonik.wordpress.com/103/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mekonik.wordpress.com/103/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mekonik.wordpress.com/103/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mekonik.wordpress.com/103/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mekonik.wordpress.com/103/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mekonik.wordpress.com/103/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mekonik.wordpress.com/103/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mekonik.wordpress.com/103/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mekonik.wordpress.com/103/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mekonik.wordpress.com/103/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mekonik.wordpress.com/103/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mekonik.wordpress.com/103/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mekonik.wordpress.com/103/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mekonik.wordpress.com/103/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mekonik.wordpress.com&amp;blog=6791281&amp;post=103&amp;subd=mekonik&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mekonik.wordpress.com/2009/12/06/comparison-of-kanji-learning-methods/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">mekonik</media:title>
		</media:content>

		<media:content url="http://mekonik.files.wordpress.com/2009/12/heisig1.png" medium="image">
			<media:title type="html">Heisig's index vs. frequency-of-use</media:title>
		</media:content>

		<media:content url="http://mekonik.files.wordpress.com/2009/12/henshall.png" medium="image">
			<media:title type="html">Henshall's index vs. frequency-of-use ranking</media:title>
		</media:content>

		<media:content url="http://mekonik.files.wordpress.com/2009/12/grade.png" medium="image">
			<media:title type="html">Grade of Japanese school when the kanji is learned vs. the frequency-of-use ranking</media:title>
		</media:content>
	</item>
		<item>
		<title>Arduino &#8211; AVR GCC multiplication</title>
		<link>http://mekonik.wordpress.com/2009/03/18/arduino-avr-gcc-multiplication/</link>
		<comments>http://mekonik.wordpress.com/2009/03/18/arduino-avr-gcc-multiplication/#comments</comments>
		<pubDate>Wed, 18 Mar 2009 21:53:59 +0000</pubDate>
		<dc:creator>mekonik</dc:creator>
				<category><![CDATA[Arduino]]></category>
		<category><![CDATA[AVR]]></category>
		<category><![CDATA[16bit]]></category>
		<category><![CDATA[32bit]]></category>
		<category><![CDATA[AVR GCC]]></category>
		<category><![CDATA[multiplication]]></category>

		<guid isPermaLink="false">http://mekonik.wordpress.com/?p=67</guid>
		<description><![CDATA[While working on my Arduino magnet levitation (details here), I stumped upon some problems with the way the compiler, AVR GCC, handles multiplication. I had to implement optimized multibyte multiplication routines because Arduino in my project preforms some digital signal processing with 20kHz sampling frequency. Since I couldn&#8217;t find those routines online, I&#8217;m posting the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mekonik.wordpress.com&amp;blog=6791281&amp;post=67&amp;subd=mekonik&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>While working on my <a href="http://mekonik.wordpress.com/2009/03/02/my-first-arduino-project/">Arduino magnet levitation</a> (<a href="http://mekonik.wordpress.com/2009/03/17/arduino-magnet-levitation/">details here</a>), I stumped upon some problems with the way the compiler, AVR GCC, handles multiplication. I had to implement optimized multibyte multiplication routines because <a href="http://www.arduino.cc/">Arduino </a>in my project preforms some digital signal processing with 20kHz sampling frequency. Since I couldn&#8217;t find those routines online, <del>I&#8217;m posting the code of some of them here</del> I posted the code on GitHub at <a title="Source code on GitHub" href="https://github.com/rekka/avrmultiplication">https://github.com/rekka/avrmultiplication</a>.</p>
<p><span id="more-67"></span></p>
<p>Arduino uses ATmega168 or similar 8-bit RISC processor. The most serious limitation of these chips is that their instruction set contains mostly instructions working with 8-bit arguments. This limitation becomes more pronounced when one wants to multiply multibyte numbers. When multiplying two <em>k</em>-byte numbers into a 2<em>k</em>-byte result, one has to perform <em>k</em>^2 multiplications and in the order of <em>k</em>^3 additions.</p>
<p>AVR architecture offers 3 multiplication instructions, <strong>mul</strong>, <strong>muls</strong> and <strong>mulsu</strong>, see the <a href="www.atmel.com/atmel/acrobat/doc0856.pdf">AVR instruction set</a>. All of them take 2 registers as arguments, perform 8bit x 8bit -&gt; 16bit multiplication and store the result in R1:R0 register pair. <strong>mul</strong> assumes that both arguments are unsigned, <strong>muls</strong> assumes signed arguments and <strong>mulsu</strong> assumes signed and unsigned argument.</p>
<p>These distinctions are neccessary as negative numbers are stored in <a href="en.wikipedia.org/wiki/Two's_complement">two&#8217;s complement form</a>. For 8-bit numbers that means that negative number <em>-x</em> is stored as 2^8 &#8211; <em>x</em>. When multiplying 8-bit numbers we get</p>
<ul>
<li>-x * y = (2^8 &#8211; x) * y = 2^8 * y &#8211; x * y</li>
<li>-x * -y = (2^8 &#8211; x) * (2^8 -y) = 2^16 &#8211; 2^8 * x &#8211; 2^8 * y + x* y.</li>
</ul>
<p>The instruction <strong>muls</strong> and <strong>mulsu</strong> thus have to remove the terms 2^8 * x and 2^8 * y when appropriate. We don&#8217;t have to worry about the internal workings of these instruction unless we want to perform multibyte multiplication.</p>
<h3>16 bit x 16 bit -&gt; 32 bit multiplication</h3>
<p>Suppose that we have two 16 bit numbers <em>x</em> and <em>y</em>. We want to compute <em>x </em>*<em> y</em>. This operation yields a 32 bit result. To implement this operation using 8bit instructions, we have to split <em>x</em> and <em>y</em> into the high byte and low byte, <em>x</em>1, <em>x</em>0 and <em>y</em>1, <em>y</em>0. Then we have</p>
<pre>x = 256 * x1 + x0
y = 256 * y1 + y0</pre>
<p>First suppose that <em>x</em> and <em>y</em> are unsigned numbers. Multiplication then yields</p>
<pre>x * y = 65536 * x1 * y1 + 256 * x1 * y0 + 256 * x0 * y1 + x0 * y0</pre>
<p>Thus this can be implemented using 4 <strong>mul</strong> instructions and some additions with appropriate shifts. When <em>x</em> and <em>y</em> are signed numbers in two&#8217;s complement notation, the result becomes more complicated:</p>
<pre>-x * y  = (2^16 - 2^8 * x1 - x0) * (2^8 * y1 + y0)
        = -x0*y0 - x1*y0*2^8 - x0*y1*2^8 + y0*2^16 - x1*y1*2^16 + y1*2^24
-x * -y = (2^16 - 2^8 * x1 - x0) * (2^16 - 2^8 * y1 - y0)
        = x0*y0 + x1*y0*2^8 + x0*y1*2^8 - x0*2^16 - y0*2^16 +
          -  x1*y1*2^16 - x1*2^24 - y1*2^24 + 2^32</pre>
<div id="attachment_83" class="wp-caption alignright" style="width: 190px"><img class="size-full wp-image-83" title="multiplication1" src="http://mekonik.files.wordpress.com/2009/03/multiplication1.png?w=500" alt="Signed 16bit mult."   /><p class="wp-caption-text">Signed 16bit mult.</p></div>
<p>As you can see, there are extra terms that have to be removed. 2^32 is removed automatically as we store only 32 bits of the result. The rest can be removed by a proper combination of mul, muls and mulsu instructions. There are 4 multiplications and their signature turns out to be quite simple, see the figure on the right. The arrows signify a single 8-bit multiplication, the red byte is to be treated as unsigned, the blue one as signed. The results then have to be added together with appropriate shifts. For instance, the result of multiplication of x1 and y0 must be shifted by 1 + 0 = 1 byte to the left.</p>
<div id="attachment_84" class="wp-caption alignright" style="width: 190px"><img class="size-full wp-image-84" title="multiplicationsu" src="http://mekonik.files.wordpress.com/2009/03/multiplicationsu.png?w=500" alt="Sign 16bit X unsign 16bit"   /><p class="wp-caption-text">Sign 16bit X unsign 16bit</p></div>
<p>This scheme can be also extended to, for example, signed 32bit x 32bit -&gt; 64bit. In this case, we can simply treat x1, x0, y1 and y0 as the 16bit words of the 32bit operands. In the case of signed 16bit x unsigned 16bit multiplication, one simply changes blue color of  the unsigned operand to red, see the figure below.</p>
<p>You can find more on<a href="http://www.avr-asm-tutorial.net/avr_en/calc/HARDMULT.html"> unsigned multiplication in AVR assembler here</a>.</p>
<h3>Rounding</h3>
<p>Right shifts are often necessary when one is using fixed-point integer math. They are essentially divisions by powers of 2. For example, when we want to multiply <em>x</em> by number <em>y</em> between 0 and 1, we first multiply <em>y</em> by a power of 2, preferably 2^8 or 2^16 depending on the desired precision, so that <em>y</em> is an integer. Then we multiply <em>x</em> and <em>y</em> and divide the result by the same power of 2. This is done as a right shift. And as with the ordinary division, rounding of the result gives a better precision. It is quite clear that 0.9 is better to round to 1 and not to 0. Unfortunately, regular right shift rounds everything down to the closest integer.</p>
<div id="attachment_86" class="wp-caption alignright" style="width: 248px"><img class="size-full wp-image-86" title="rounding" src="http://mekonik.files.wordpress.com/2009/03/rounding.png?w=500" alt="Rounding"   /><p class="wp-caption-text">Rounding</p></div>
<p>There is a simple solution to this. We can test the most significant bit (MSB) of the part that is shifted out of the result. If this bit is set, we simply add 1 to the result. If it is cleared, we don&#8217;t have to anything. This adds more accuracy to multiplications, especially when the result is an operand for another multiplication.</p>
<h2>AVR GCC issues</h2>
<h3>AVR GCC handling of multibyte multiplication</h3>
<p>Let&#8217;s have a look at how AVR GCC handles multiplication.  First suppose that we want to multiply two signed 8-bit numbers and get a 16-bit result. We would write something like:</p>
<pre>char a = -10;
char b = 10;
int x;

void setup() {
  x = a * b;
}</pre>
<p>This produces the following code:</p>
<pre>  x = a * b;
  c2:	80 91 01 01 	lds	r24, 0x0101 // load a
  c6:	20 91 00 01 	lds	r18, 0x0100 // load b
  ca:	82 02       	muls	r24, r18
  cc:	c0 01       	movw	r24, r0
  ce:	11 24       	eor	r1, r1
  d0:	90 93 09 01 	sts	0x0109, r25 // store x high byte
  d4:	80 93 08 01 	sts	0x0108, r24 // store x low byte</pre>
<p>As you can see, the compiler produces the corect 16-bit result, using only one <strong>muls</strong> instruction. No need for typecasting. The instruction <strong>eor r1, r1</strong> clears the register R1, that is supposed to be 0 by AVR GCC convention. But you can notice that the <strong>movw</strong> instruction is unnecessary.</p>
<p>Now let&#8217;s see what happens when we want to multiply two 16-bit signed numbers and get a 32-bit result. When we write:</p>
<pre>int a = -10;
int b = 10;
long x;

void setup() {
  x = a * b;
}</pre>
<p>we get the following code:</p>
<pre>x = a * b;
  c2:	20 91 02 01 	lds	r18, 0x0102
...
  d2:	ac 01       	movw	r20, r24
  d4:	24 9f       	mul	r18, r20
  d6:	c0 01       	movw	r24, r0
  d8:	25 9f       	mul	r18, r21
  da:	90 0d       	add	r25, r0
  dc:	34 9f       	mul	r19, r20
  de:	90 0d       	add	r25, r0
  e0:	11 24       	eor	r1, r1
  e2:	aa 27       	eor	r26, r26
  e4:	97 fd       	sbrc	r25, 7
  e6:	a0 95       	com	r26
  e8:	ba 2f       	mov	r27, r26
  ea:	80 93 0a 01 	sts	0x010A, r24
...</pre>
<p>As you can see, it performs only 3 multiplications, doing 16bit x 16bit -&gt; 16bit and then extending the result to 32 bits. That&#8217;s not what we want since we lose the 2 highes bytes of the multiplication. We have to typecast ints into longs, writing</p>
<pre> x = (long) a * b;</pre>
<p>But this produces:</p>
<pre>  x = (long) a * b;
  c2:	60 91 02 01 	lds	r22, 0x0102
  c6:	70 91 03 01 	lds	r23, 0x0103
  ca:	88 27       	eor	r24, r24     // extension to 32 bit
  cc:	77 fd       	sbrc	r23, 7
  ce:	80 95       	com	r24
  d0:	98 2f       	mov	r25, r24
  d2:	20 91 00 01 	lds	r18, 0x0100
  d6:	30 91 01 01 	lds	r19, 0x0101
  da:	44 27       	eor	r20, r20     // extension to 32 bit
  dc:	37 fd       	sbrc	r19, 7
  de:	40 95       	com	r20
  e0:	54 2f       	mov	r21, r20
  e2:	0e 94 fd 01 	call	0x3fa	; 0x3fa &lt;__mulsi3&gt;
  e6:	60 93 0a 01 	sts	0x010A, r22
...</pre>
<p>In this case, the compiler extends the operants to 32bit first, and then calls a 32bit x 32bit -&gt; 32bit multiplication routine. But this is very wastful as the routine performs 10 multiplications instead of the necessary 4 and other overhead that is required for full long multiplication. The whole multiplication (together with the memory access) takes <strong>72</strong> cycles, instead of the optimized <strong>38</strong> cycles. That makes a difference of more than <strong>2μs</strong> on a single multiplication instruction. It is even a bigger difference when no memory access is neccessary, for example when multiplying local variables. Then it is 56 versus 22 cycles. Which saves 2μs out of 3,5μs.</p>
<h3>AVR GCC handling of a multiplication by a constant</h3>
<p>The way AVR GCC handles multibyte multiplication is caused by writing the code in C that doesn&#8217;t allow for exact specifications of the operand and result sizes and as such it is not a bug, it&#8217;s a feature that we have to be aware of. But there is a bug in AVR GCC that causes the compiler to produce a suboptimal code for multiplications by a constant, see <a href="http://www.avrfreaks.net/index.php?name=PNphpBB2&amp;file=viewtopic&amp;t=75909">forum post at AVR Freaks forum</a>. The problem is that multiplication by a power of 2 is interpreted as shifts even when it is worse than actual multiplication. Shifts are sometimes worse because AVR offers only 1-bit shifts of 8-bit operands. For instance, the simple code</p>
<pre>int a = -10;
int x;

void setup() {
  x = a * 64;
}</pre>
<p>gets compiled as</p>
<pre>  ca:	36 e0       	ldi	r19, 0x06	; 6
  cc:	88 0f       	add	r24, r24
  ce:	99 1f       	adc	r25, r25
  d0:	3a 95       	dec	r19
  d2:	e1 f7       	brne	.-8</pre>
<p>This takes more then 30 cycles, while writing this as a multiplication would take 8. That&#8217;s a huge difference.</p>
<h2>Code</h2>
<p>The header files ready to include in your sketch can be downloaded here:</p>
<p><a title="Source code on GitHub" href="https://github.com/rekka/avrmultiplication">https://github.com/rekka/avrmultiplication</a></p>
<p>The functions are implemented as macros. This means that you have to call them in a little bit different manner than regular C functions. For example, using signed 16bit x 16bit -&gt; 32bit multiplication is performed by:</p>
<pre>int x = 12;
int y = -32;
long result32;
MultiS16X16to32(result32, x, y);</pre>
<p>Also, this means that the whole multiplication code is included at every place that you use a macro. This can be undesirable if you are using one macro many times. Of course, you can write your own stub function, for example:</p>
<pre>long FuncMultiS16X16to32(int x, int y) {
     long result32;
     MultiS16X16to32(result32, x, y);
     return result32;
}</pre>
<p>The notation of macros is simple. It starts with Multi, followed by U, SU or S, depending on the signature of arguments and 16X16, 32X16 or 16X8 depending on the size of arguments. It is finished by to16, to H16, toL16 or toH32 with or without rounding (Round), indicating what part of the result is stored (whole, L for Low or H for High).</p>
<p>The library is not complete, it contains only the methods that I needed so far. But it contains all 16&#215;16 methods I hope. I&#8217;m gonna try to expand it as soon as I need another version of the methods. Also, I can include additional versions if there is interest. Let me know.</p>
<p>Here are the 16X16 codes:</p>
<pre>// longRes = intIn1 * intIn2
#define MultiU16X16to32(longRes, intIn1, intIn2) \
asm volatile ( \
"clr r26 \n\t" \
"mul %A1, %A2 \n\t" \
"movw %A0, r0 \n\t" \
"mul %B1, %B2 \n\t" \
"movw %C0, r0 \n\t" \
"mul %B2, %A1 \n\t" \
"add %B0, r0 \n\t" \
"adc %C0, r1 \n\t" \
"adc %D0, r26 \n\t" \
"mul %B1, %A2 \n\t" \
"add %B0, r0 \n\t" \
"adc %C0, r1 \n\t" \
"adc %D0, r26 \n\t" \
"clr r1 \n\t" \
: \
"=&amp;r" (longRes) \
: \
"a" (intIn1), \
"a" (intIn2) \
: \
"r26" \
) 

// intRes = intIn1 * intIn2 &gt;&gt; 16
// uses:
// r26 to store 0
// r27 to store the byte 1 of the 32bit result
#define MultiU16X16toH16(intRes, intIn1, intIn2) \
asm volatile ( \
"clr r26 \n\t" \
"mul %A1, %A2 \n\t" \
"mov r27, r1 \n\t" \
"mul %B1, %B2 \n\t" \
"movw %A0, r0 \n\t" \
"mul %B2, %A1 \n\t" \
"add r27, r0 \n\t" \
"adc %A0, r1 \n\t" \
"adc %B0, r26 \n\t" \
"mul %B1, %A2 \n\t" \
"add r27, r0 \n\t" \
"adc %A0, r1 \n\t" \
"adc %B0, r26 \n\t" \
"clr r1 \n\t" \
: \
"=&amp;r" (intRes) \
: \
"a" (intIn1), \
"a" (intIn2) \
: \
"r26" , "r27" \
) 

// intRes = intIn1 * intIn2 &gt;&gt; 16 + round
// uses:
// r26 to store 0
// r27 to store the byte 1 of the 32bit result
// 21 cycles
#define MultiU16X16toH16Round(intRes, intIn1, intIn2) \
asm volatile ( \
"clr r26 \n\t" \
"mul %A1, %A2 \n\t" \
"mov r27, r1 \n\t" \
"mul %B1, %B2 \n\t" \
"movw %A0, r0 \n\t" \
"mul %B2, %A1 \n\t" \
"add r27, r0 \n\t" \
"adc %A0, r1 \n\t" \
"adc %B0, r26 \n\t" \
"mul %B1, %A2 \n\t" \
"add r27, r0 \n\t" \
"adc %A0, r1 \n\t" \
"adc %B0, r26 \n\t" \
"lsl r27 \n\t" \
"adc %A0, r26 \n\t" \
"adc %B0, r26 \n\t" \
"clr r1 \n\t" \
: \
"=&amp;r" (intRes) \
: \
"a" (intIn1), \
"a" (intIn2) \
: \
"r26" , "r27" \
) 

// signed16 * signed16
// 22 cycles
#define MultiS16X16to32(longRes, intIn1, intIn2) \
asm volatile ( \
"clr r26 \n\t" \
"mul %A1, %A2 \n\t" \
"movw %A0, r0 \n\t" \
"muls %B1, %B2 \n\t" \
"movw %C0, r0 \n\t" \
"mulsu %B2, %A1 \n\t" \
"sbc %D0, r26 \n\t" \
"add %B0, r0 \n\t" \
"adc %C0, r1 \n\t" \
"adc %D0, r26 \n\t" \
"mulsu %B1, %A2 \n\t" \
"sbc %D0, r26 \n\t" \
"add %B0, r0 \n\t" \
"adc %C0, r1 \n\t" \
"adc %D0, r26 \n\t" \
"clr r1 \n\t" \
: \
"=&amp;r" (longRes) \
: \
"a" (intIn1), \
"a" (intIn2) \
: \
"r26" \
)

// signed16 * signed 16 &gt;&gt; 16
#define MultiS16X16toH16(intRes, intIn1, intIn2) \
asm volatile ( \
"clr r26 \n\t" \
"mul %A1, %A2 \n\t" \
"mov r27, r1 \n\t" \
"muls %B1, %B2 \n\t" \
"movw %A0, r0 \n\t" \
"mulsu %B2, %A1 \n\t" \
"sbc %B0, r26 \n\t" \
"add r27, r0 \n\t" \
"adc %A0, r1 \n\t" \
"adc %B0, r26 \n\t" \
"mulsu %B1, %A2 \n\t" \
"sbc %B0, r26 \n\t" \
"add r27, r0 \n\t" \
"adc %A0, r1 \n\t" \
"adc %B0, r26 \n\t" \
"clr r1 \n\t" \
: \
"=&amp;r" (intRes) \
: \
"a" (intIn1), \
"a" (intIn2) \
: \
"r26", "r27" \
)

// multiplies a signed and unsigned 16 bit ints with a 32 bit result
#define MultiSU16X16to32(longRes, intIn1, intIn2) \
asm volatile ( \
"clr r26 \n\t" \
"mul %A1, %A2 \n\t" \
"movw %A0, r0 \n\t" \
"mulsu %B1, %B2 \n\t" \
"movw %C0, r0 \n\t" \
"mul %B2, %A1 \n\t" \
"add %B0, r0 \n\t" \
"adc %C0, r1 \n\t" \
"adc %D0, r26 \n\t" \
"mulsu %B1, %A2 \n\t" \
"sbc %D0, r26 \n\t" \
"add %B0, r0 \n\t" \
"adc %C0, r1 \n\t" \
"adc %D0, r26 \n\t" \
"clr r1 \n\t" \
: \
"=&amp;r" (longRes) \
: \
"a" (intIn1), \
"a" (intIn2) \
: \
"r26" \
)

// multiplies signed x unsigned int and returns the highest 16 bits of the result
#define MultiSU16X16toH16(intRes, intIn1, intIn2) \
asm volatile ( \
"clr r26 \n\t" \
"mul %A1, %A2 \n\t" \
"mov r27, r1 \n\t" \
"mulsu %B1, %B2 \n\t" \
"movw %A0, r0 \n\t" \
"mul %B2, %A1 \n\t" \
"add r27, r0 \n\t" \
"adc %A0, r1 \n\t" \
"adc %B0, r26 \n\t" \
"mulsu %B1, %A2 \n\t" \
"sbc %B0, r26 \n\t" \
"add r27, r0 \n\t" \
"adc %A0, r1 \n\t" \
"adc %B0, r26 \n\t" \
"clr r1 \n\t" \
: \
"=&amp;r" (intRes) \
: \
"a" (intIn1), \
"a" (intIn2) \
: \
"r26", "r27" \
)

// multiplies signed x unsigned int and returns the highest 16 bits of the result
// rounds the result based on the MSB of the lower 16 bits
// 22 cycles
#define MultiSU16X16toH16Round(intRes, intIn1, intIn2) \
asm volatile ( \
"clr r26 \n\t" \
"mul %A1, %A2 \n\t" \
"mov r27, r1 \n\t" \
"mulsu %B1, %B2 \n\t" \
"movw %A0, r0 \n\t" \
"mul %A1, %B2 \n\t" \
"add r27, r0 \n\t" \
"adc %A0, r1 \n\t" \
"adc %B0, r26 \n\t" \
"mulsu %B1, %A2 \n\t" \
"sbc %B0, r26 \n\t" \
"add r27, r0 \n\t" \
"adc %A0, r1 \n\t" \
"adc %B0, r26 \n\t" \
"lsl r27 \n\t" \
"adc %A0, r26 \n\t" \
"adc %B0, r26 \n\t" \
"clr r1 \n\t" \
: \
"=&amp;r" (intRes) \
: \
"a" (intIn1), \
"a" (intIn2) \
: \
"r26", "r27" \
)</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mekonik.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mekonik.wordpress.com/67/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mekonik.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mekonik.wordpress.com/67/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mekonik.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mekonik.wordpress.com/67/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mekonik.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mekonik.wordpress.com/67/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mekonik.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mekonik.wordpress.com/67/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mekonik.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mekonik.wordpress.com/67/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mekonik.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mekonik.wordpress.com/67/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mekonik.wordpress.com&amp;blog=6791281&amp;post=67&amp;subd=mekonik&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mekonik.wordpress.com/2009/03/18/arduino-avr-gcc-multiplication/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">mekonik</media:title>
		</media:content>

		<media:content url="http://mekonik.files.wordpress.com/2009/03/multiplication1.png" medium="image">
			<media:title type="html">multiplication1</media:title>
		</media:content>

		<media:content url="http://mekonik.files.wordpress.com/2009/03/multiplicationsu.png" medium="image">
			<media:title type="html">multiplicationsu</media:title>
		</media:content>

		<media:content url="http://mekonik.files.wordpress.com/2009/03/rounding.png" medium="image">
			<media:title type="html">rounding</media:title>
		</media:content>
	</item>
		<item>
		<title>Arduino Magnet Levitation &#8211; detailed tutorial</title>
		<link>http://mekonik.wordpress.com/2009/03/17/arduino-magnet-levitation/</link>
		<comments>http://mekonik.wordpress.com/2009/03/17/arduino-magnet-levitation/#comments</comments>
		<pubDate>Wed, 18 Mar 2009 04:11:34 +0000</pubDate>
		<dc:creator>mekonik</dc:creator>
				<category><![CDATA[Arduino]]></category>
		<category><![CDATA[electromagnet]]></category>
		<category><![CDATA[Hall effect sensor]]></category>
		<category><![CDATA[levitation]]></category>
		<category><![CDATA[magnet]]></category>

		<guid isPermaLink="false">http://mekonik.wordpress.com/?p=48</guid>
		<description><![CDATA[Recently, I finished my first Arduino project, a magnet levitation device. It levitates a magnetic object under an electromagnet. What makes it different from similar projects is the position sensor for the feedback loop. I use a single Hall effect sensor placed directly on the bottom of the core of the electromagnet. This creates a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mekonik.wordpress.com&amp;blog=6791281&amp;post=48&amp;subd=mekonik&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Recently, I finished my<a href="http://mekonik.wordpress.com/2009/03/02/my-first-arduino-project/"> first Arduino project, a magnet levitation device</a>. It levitates a magnetic object under an electromagnet. What makes it different from <a href="http://mekonik.wordpress.com/2009/03/04/magnetic-levitation-projects/">similar projects</a> is the position sensor for the feedback loop. I use a single Hall effect sensor placed directly on the bottom of the core of the electromagnet. This creates a problem of separating the electromagnet&#8217;s field from the levitating magnet&#8217;s field. Fortunately, this can be done in software by the microcontroller ATmega168 that is the heart of <a href="http://www.arduino.cc/en/Main/ArduinoBoardDuemilanove">Arduino Duemilanove</a>, the board that I use to control the levitation. This article gives a detailed description of the project together with source code at <a title="Source code on GitHub" href="https://github.com/rekka/levitation">https://github.com/rekka/levitation</a>, as I promised.</p>
<h3><span id="more-48"></span></h3>
<p><em>This is my first attempt to describe something that I don&#8217;t have much experience with. If you find an error, if there is something that is not clear or if there is something I could improve, please, leave a comment.</em></p>
<h2>Setup</h2>
<div id="attachment_50" class="wp-caption alignright" style="width: 135px"><img class="size-full wp-image-50" title="maglev1Setup" src="http://mekonik.files.wordpress.com/2009/03/setup.png?w=500" alt="Setup"   /><p class="wp-caption-text">Setup</p></div>
<p>The general setup is quite straightforward. The main part is an electromagnet consisting of a coil on an iron core. The current through my coil from a push-type solenoid is 300mA at 12V. At the bottom of the electromagnet, there is a Hall effect sensor directly on the iron core, positioned in such a way that the sensor detection axis is aligned with the core axis (figure on the right).</p>
<h4>Components</h4>
<ul>
<li>Arduino Duemilanove</li>
<li>Switched power supply 12V</li>
<li>Linear Hall effect sensor Honeywell SS19</li>
<li>Norton operational amplifier MC3401P</li>
<li>NPN transistor MPSA06</li>
<li>Rectifier 1N4001</li>
<li>Electromagnet (I used a coil from a 12V push-type solenoid)</li>
<li>Resistors 2x 1k, 5k6, 47k, 68k, 330k, 4x 1M</li>
<li>Capacitors 2x 1μ</li>
</ul>
<p>Since I don&#8217;t have much experience, I tried to keep the circuit as simple as possible. The project consists of two quite independent parts.</p>
<div id="attachment_68" class="wp-caption alignleft" style="width: 237px"><img class="size-full wp-image-68" title="driverscheme" src="http://mekonik.files.wordpress.com/2009/03/driverscheme.png?w=500" alt="The coil driver"   /><p class="wp-caption-text">The coil driver</p></div>
<p>The first part is the coil driver. I used a small transistor to turn the coil on or off, added a reverse-biased diode across the coil for protection of the transistor against fly-back currents, and put a capacitor across the supply for noise reduction. The base of the transistor is connected to a Arduino digital output through a 1k resistor, with an extra LED to indicate the pin state.</p>
<p>The second part is a bit more involved. I used linear Hall effect sensor SS19 from Honeywell. It is a tiny black box that has 3 pins, 2 of which are connected to GND and +5V, the 3rd one is the output. The sensor translates the perpendicular (to the two largest faces of the sensor) component of a magnetic field into voltage on the output. In my case, it was 2.15V with no field and 3.0 V with the maximal field (coil on and magnet nearby). Thus I attached 2 Norton operational amplifiers (out of 4 in MC3401). The first stage subtracts ~1.5V while the second amplifies it by a factor of ~3. That gives a signal in the range 1.8 &#8212; 4.5V, in the working range of the amplifier. This amplified signal then connects to an Arduino analog input pin. Note that I used a <em>Norton </em>op amp. It amplifies current difference, unlike the usual op amp that amplifies voltage difference. That&#8217;s why the wiring is slightly different. I also had to add a load resistor 5k6 on the sensor output to make it work properly.</p>
<div id="attachment_69" class="wp-caption aligncenter" style="width: 460px"><img class="size-full wp-image-69" title="sensorscheme" src="http://mekonik.files.wordpress.com/2009/03/sensorscheme.png?w=500" alt="Sensor with amplifier circuit"   /><p class="wp-caption-text">Sensor with amplifier circuit</p></div>
<h2>A bit of theory</h2>
<p>The magnetic field needed to keep a magnet from falling changes with the distance from the electromagnet. In our case, the position of the magnet is monitored by the Hall effect sensor. The closer the magnet is to the sensor the higher voltage is on the output. And the closer the magnet is the smaller field is required to keep it from falling. The situation is shown in the following figure:</p>
<div id="attachment_71" class="wp-caption aligncenter" style="width: 460px"><img class="size-full wp-image-71" title="coilpower" src="http://mekonik.files.wordpress.com/2009/03/coilpower.png?w=500" alt="The general idea of how to keep magnet levitating"   /><p class="wp-caption-text">General idea of how to keep magnet levitating</p></div>
<p>The purple straight line represents the magnetic field required to keep a magnet from falling with respect to the reading on the sensor. In reality, it is nonlinear curve but that&#8217;s not important for us. We need to produce a field that will keep a magnet at a specific position. For that we will modulate the coil&#8217;s power so that the field produced is given by the blue line in the previous plot.  The two extreme values are the maximal field of the coil and the field when the coil is off. If we are successful, the magnet should be stable at the intersection of the two curves in the middle of the plot. If the magnet gets too close to the iron core the shear attractive force of these two is enough to attract it. That is represented by the rightmost intersection. We need to prevent this situation.</p>
<p>That sounds quite easy, doesn&#8217;t it? But there is a small complication. The reading on the sensor includes the magnetic field of the coil. In fact, because the sensor is right on the core this component will probably be bigger than the component we are interested in, the field of the magnet itself. Fortunately for us, we know what signal we use to drive the coil. However, if we plot the driving signal and the magnetic field of the coil, we get the following plot:</p>
<div id="attachment_72" class="wp-caption aligncenter" style="width: 460px"><img class="size-full wp-image-72" title="coilfield" src="http://mekonik.files.wordpress.com/2009/03/coilfield.png?w=500" alt="Coil field"   /><p class="wp-caption-text">Coil field</p></div>
<p>This behavior is caused by the large inductance of the coil. When the transistor is open, the there is +12V on the coil. But the change in current induced magnetic field that resist this change and it takes more time for the full current to flow. When the transistor is closed, the current continues to flow through the diode in parallel. The resistance of the coil and the diode disipates the energy and the current decreases to zero. In my case, it takes around <strong>5ms</strong> for the coil to energize or deenergize. That is way too long for us to ignore. But we can model this behavior. A coil can be approximated as a resistance <em>R</em> and inductance <em>L</em> in series. The circuit can be simplified like this:</p>
<div id="attachment_73" class="wp-caption aligncenter" style="width: 208px"><img class="size-full wp-image-73" title="inductor" src="http://mekonik.files.wordpress.com/2009/03/inductor.png?w=500" alt="Coil model"   /><p class="wp-caption-text">Coil model</p></div>
<p>The differential equation for the current <em>I </em>through the coil then reads</p>
<p><img src='http://s0.wp.com/latex.php?latex=%5Cfrac%7Bd+I%7D%7Bdt%7D+%3D+V+-+R+I%2C&amp;bg=ffffff&amp;fg=333333&amp;s=0' alt='&#92;frac{d I}{dt} = V - R I,' title='&#92;frac{d I}{dt} = V - R I,' class='latex' /></p>
<p>where <em>V</em> is the voltage on the coil. In our case, it is +12V when the driving signal is 1 and -0.6V (the diode voltage) when the signal is 0. The magnetic field is proportional to the current. For simplicity, we rewrite the equation for dimensionless field power <em>y</em> and applied voltage <em>x</em>, <em>x</em> being -0.05 = -0.6/12 or 1 and <em>y</em> being in the range 0 &#8212; 1. That yields the equation</p>
<p><img src='http://s0.wp.com/latex.php?latex=%5Cfrac%7Bdy%7D%7Bdt%7D+%3D+%5Clambda+%28x+-+y%29.&amp;bg=ffffff&amp;fg=333333&amp;s=0' alt='&#92;frac{dy}{dt} = &#92;lambda (x - y).' title='&#92;frac{dy}{dt} = &#92;lambda (x - y).' class='latex' /></p>
<p><em>λ</em> is a parameter depending on the coil. But this is a equation for a low-pass filter. This continuous form can be discretized, see <a href="http://en.wikipedia.org/wiki/Low-pass_filter">Low-pass filter</a> on wikipedia. Assuming constant timesteps, <em> </em>Δ<em>t</em> = 1, we get the final formula</p>
<p><img src='http://s0.wp.com/latex.php?latex=y_n+%3D+y_%7Bn-1%7D+%2B+%5Calpha+%28x_n+-+y_%7Bn-1%7D%29.&amp;bg=ffffff&amp;fg=333333&amp;s=0' alt='y_n = y_{n-1} + &#92;alpha (x_n - y_{n-1}).' title='y_n = y_{n-1} + &#92;alpha (x_n - y_{n-1}).' class='latex' /></p>
<p>The parameter <em>α</em> depends on the coil and on the timestep. It can be found using</p>
<p><img src='http://s0.wp.com/latex.php?latex=%5Calpha+%3D+%5Cfrac%7B1%7D%7BT+%2B+1%7D%2C&amp;bg=ffffff&amp;fg=333333&amp;s=0' alt='&#92;alpha = &#92;frac{1}{T + 1},' title='&#92;alpha = &#92;frac{1}{T + 1},' class='latex' /></p>
<p>where <em>T</em> is the number of timesteps it take for the coil to energize from 0 to 0.632 of its maximal field. This has to be found by some experimentation. Generally, <em>α</em> is different for the energization and deenergization phase since the diode gives rise to extra resistance in the circuit.</p>
<h2>Control algorithm</h2>
<p>Now with some theoretical background, we can proceed to describe the algorithm that controls the output signal. First, we have to find the following parameters (<strong>field</strong> shall denote the reading on the sensor):</p>
<ul>
<li><strong>sample frequency</strong> = how often to sample <strong>field</strong> and adjust the output signal, I use 10kHz</li>
<li><strong>baseline </strong>= <strong>field</strong> with no magnetic fields</li>
<li><strong>coilMag</strong> = the maximal strength of the coil, i.e. the difference of <strong>field</strong> with the coil on and <strong>baseline</strong></li>
<li><strong>alphaInc</strong> = the constant <em>α</em> from above for energization of the coil</li>
<li><strong>alphaDec = </strong>the constant <em>α</em> from above for deenergization</li>
</ul>
<p>We have to keep track of the following variables:</p>
<ul>
<li><strong>signal </strong>= last signal ouput, 0 or 1</li>
<li><strong>filter</strong> = value in the range 0 to 1, this is the field of the coil in the last step, the result of the discretized formula.</li>
</ul>
<p>With these parameters, we perform the following steps with the <strong>sample frequency</strong>:</p>
<ol>
<li>Update the <strong>filter</strong>
<ul>
<li>If <strong>ouput == 1</strong>, use <strong>filter += alphaInc(1 &#8211; filter)</strong>,</li>
<li>else <strong>filter -= alphaDec(filter + 0.05).</strong></li>
</ul>
</li>
<li>Read the sensor input, <strong>field</strong>. Based on this value, find the value of the permanent magnet&#8217;s field alone, <strong>mag = field &#8211; coilMag * filter &#8211; baseline</strong>.</li>
<li>Using the value <strong>mag</strong> that represents the distance of the magnet from the sensor, estimate the required coil power required to keep the magnet from falling, <strong>power</strong>. This is estimated based on the simple model shown in Figure 1.</li>
<li>Produce new <strong>signal</strong>.
<ul>
<li>If <strong>power &gt; filter</strong>, set <strong>signal = 1 </strong>(need to energize)</li>
<li>else set <strong>signal = 0</strong> (need to deenergize)</li>
</ul>
</li>
</ol>
<h2>Implementation</h2>
<p>I should make some remarks on my software implementation:</p>
<h4>Constant timestep</h4>
<p>To achieve a constant sampling and output rate, some constant time-base is necessary. The standard millis() method doesn&#8217;t allow for the desired precision. One option is to use the build-in timers, like millis() is using, and change their resolution. But the simplest way is to use the A/D converter itself for timing purposes. The time it takes for ADC to perform a reading is constant and can be changed by changing the ADC prescaler settings. It is given by the formula</p>
<pre>clock = 16,000,000
prescaler = 2, 4, 8, 16, 32, 64 or 128
conversionCycles = 13 * clock / prescaler;</pre>
<p>The default prescaler value is 128, which gives the maximal conversion rate to be ~~9.6kHz. I&#8217;m using 64 which leads to 19230.8Hz sampling rate.  The ADC clock value, clock/prescaler, affects the ADC accuracy. ATMEL recommends the range 50-200kHz for maximal accuracy, with rates up to 1MHz if less accuracy is needed. My choice gives 250kHz ADC clock, that&#8217;s quite close to the recommendation.</p>
<p>Now for the synchronization. When a conversion is finished, an interrupt flag in the ADC registers is set. Waiting for this flag provides the necessary synchronization. To ensure that the next conversion is started as soon as one is finished, the ADC is configured to work in a free running mode with an auto-trigger enabled. The functions <strong>analogSetup</strong> and <strong>analogStart</strong> configure the ADC and start the first conversion while <strong>analogNext</strong> waits for a conversion to finish and thus provides the synchronization for the program.</p>
<h4>Multiplication code</h4>
<p>The coil simulation is done by fixed-point integer math. That means that values of <strong>filter</strong>, <strong>alphaDec</strong> and <strong>alphaInc</strong> in the range 0 &#8212; 1 are multiplied by 2^16 = 65536. When a multiplication such as <strong>coilMag * filter</strong> is performed, the actual code is</p>
<pre>result = coilMag * filter &gt;&gt; 16;</pre>
<p>Since AVG GCC is adding extra unnecessary instructions for multibyte multiplications like this, I implemented <a href="http://mekonik.wordpress.com/2009/03/18/arduino-avr-gcc-multiplicationarduino-avr-gcc-multiplication/">my own assembler routines</a>. This is not really required for this simple code, but I also experiment with additional digital signal processing to achieve greater stability of the magnet, and this processing is quite costly in terms of multiplications. Also, my own multiplication routine allows me to perform rounding of the result of &gt;&gt; 16 and that adds extra precision to the computation.</p>
<h4>Computer interface</h4>
<p>The Arduino performs all computations but the code is written in such a way that it is necessary for it to be connected to the computer. The levitation routine is initiated when Arduino receives 32 bytes from the computer. These 32 bytes must contain 16 integers and are written in the array <strong>ap</strong>. The significance of the individual fields is</p>
<pre>ap[0] = alphaInc * 2^16
ap[2] = alphaDec * 2^16
ap[3] = 0.05 * 2^16
ap[4] = lowestMag
ap[5] = powerDecay
ap[15] = counter</pre>
<p><strong>alphaInc </strong>and <strong>alphaDec </strong>are the constants from above, <strong>0.05 </strong>= 0.6/12 is the diode voltage. <strong>lowestMag </strong>and <strong>powerDecay </strong>are two parameters of the linear function used to compute the power of the coil magnetic field using the formula</p>
<pre>power = 255 + (ap[4] - (mag)) * ap[5];</pre>
<p>The levitation routine is stopped when a byte 0 is received by Arduino.</p>
<h4>Finding the constants</h4>
<p>Since the constants alphaInc, alphaDec and diode voltage seem fixed, I enter them by hand. To find their value, I simply guess, it is not that hard. To control the Arduino code and to monitor the performance, I use a simple <a href="http://www.wolfram.com/">Mathematica </a>program. It looks like this:</p>
<div id="attachment_74" class="wp-caption aligncenter" style="width: 428px"><img class="size-full wp-image-74" title="mathematicainterface" src="http://mekonik.files.wordpress.com/2009/03/mathematicainterface.png?w=500" alt="Mathematica 6 interface"   /><p class="wp-caption-text">Mathematica 6 interface</p></div>
<p>The plots allow me to see the sensor reading, the signal output and the computed field of the permanent magnet (the three lines from top to bottom). To find a value <strong>alphaDec</strong>, for example, I guess some value and use the counter setting (ap[15]) to be 10.  This causes the signal to be a simple square wave. Then I take a look at the computed magnet&#8217;s field. With no permanent magnet around, it should be constant and the plots should look like this:</p>
<div id="attachment_75" class="wp-caption aligncenter" style="width: 288px"><img class="size-full wp-image-75" title="inductorcorrectsetting" src="http://mekonik.files.wordpress.com/2009/03/inductorcorrectsetting.png?w=500" alt="Correct value of alphaDec"   /><p class="wp-caption-text">Correct value of alphaDec</p></div>
<p>If I guess the value too low or too high, I see some bumps like:</p>
<div id="attachment_77" class="wp-caption aligncenter" style="width: 373px"><img class="size-full wp-image-77" title="inductorincorrectlow" src="http://mekonik.files.wordpress.com/2009/03/inductorincorrectlow.png?w=500" alt="alphaDec too low"   /><p class="wp-caption-text">alphaDec too low</p></div>
<div id="attachment_76" class="wp-caption aligncenter" style="width: 299px"><img class="size-full wp-image-76" title="inductorincorrecthigh" src="http://mekonik.files.wordpress.com/2009/03/inductorincorrecthigh.png?w=500" alt="alphaDec too high"   /><p class="wp-caption-text">alphaDec too high</p></div>
<h2>Code</h2>
<p>Finally, here is the code:</p>
<p><a title="Source code on GitHub" href="https://github.com/rekka/levitation">https://github.com/rekka/levitation</a></p>
<p>To make it work with the 1Mbaud communication, you will also have to<del> download</del> check <a href="http://mekonik.wordpress.com/2009/03/02/modified-arduino-library-serial/">my optimized Serial library</a>,</p>
<p><del>wiring_serial.c</del> (the library is too outdated now. Fortunately, the official Arduino libraries have been updated and the issue has been fixed, it seems.)</p>
<h2>Final thoughts</h2>
<p>With the current implementation, the project faces a serious problem, instability. It works well for levitating a magnet for short time, minutes at most. After a while, oscillations develop and a magnet eventually falls. The reason for this is the lack of energy dissipation, or damping. The magnet under an electromagnet can be approximated by the equation</p>
<p><img src='http://s0.wp.com/latex.php?latex=%5Cfrac%7Bd%5E2y%7D%7Bdt%5E2%7D+%3D+y%2C&amp;bg=ffffff&amp;fg=333333&amp;s=0' alt='&#92;frac{d^2y}{dt^2} = y,' title='&#92;frac{d^2y}{dt^2} = y,' class='latex' /></p>
<p>where <em>y</em> is the distance from an equilibrium. In words, the higher the magnet is, the closer it is to the electromagnet&#8217;s core and the stronger it is attracted. The lower it is, the further from the core, the less attraction there is. This system is unstable, the solutions of the equation diverge. By applying power to the electromagnet, we are trying to modify the equation to have the form</p>
<p><img src='http://s0.wp.com/latex.php?latex=%5Cfrac%7Bd%5E2y%7D%7Bdt%5E2%7D+%3D+-c+y%2C+&amp;bg=ffffff&amp;fg=333333&amp;s=0' alt='&#92;frac{d^2y}{dt^2} = -c y, ' title='&#92;frac{d^2y}{dt^2} = -c y, ' class='latex' /></p>
<p>where <em>c</em> is some positive constant. Now this equation is stable, it is a harmonic oscillator. If there is a oscillation, it will be preserved, but it won&#8217;t grow. The problem appears when there is  a delay between reading of the sensor and producing new output. And this will be there in every real system. This translates into appearance of a new term in the equation</p>
<p><img src='http://s0.wp.com/latex.php?latex=%5Cfrac%7Bd%5E2y%7D%7Bdt%5E2%7D+%3D+-c+y+%2B+a+%5Cfrac%7Bdy%7D%7Bdt%7D.&amp;bg=ffffff&amp;fg=333333&amp;s=0' alt='&#92;frac{d^2y}{dt^2} = -c y + a &#92;frac{dy}{dt}.' title='&#92;frac{d^2y}{dt^2} = -c y + a &#92;frac{dy}{dt}.' class='latex' /></p>
<p>Again, <em>a</em> is a positive constant. Since -<em>a</em> indicates how much oscillations are damped, this term will increase the osciallations. The question is how to fight this term. I experimented with a couple ideas that I had, like diferentiation or integration of the signal, or using some other more involved filters. So far, I wasn&#8217;t able to produce a consistent oscillation damping. But research continues.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mekonik.wordpress.com/48/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mekonik.wordpress.com/48/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mekonik.wordpress.com/48/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mekonik.wordpress.com/48/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mekonik.wordpress.com/48/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mekonik.wordpress.com/48/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mekonik.wordpress.com/48/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mekonik.wordpress.com/48/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mekonik.wordpress.com/48/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mekonik.wordpress.com/48/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mekonik.wordpress.com/48/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mekonik.wordpress.com/48/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mekonik.wordpress.com/48/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mekonik.wordpress.com/48/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mekonik.wordpress.com&amp;blog=6791281&amp;post=48&amp;subd=mekonik&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mekonik.wordpress.com/2009/03/17/arduino-magnet-levitation/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">mekonik</media:title>
		</media:content>

		<media:content url="http://mekonik.files.wordpress.com/2009/03/setup.png" medium="image">
			<media:title type="html">maglev1Setup</media:title>
		</media:content>

		<media:content url="http://mekonik.files.wordpress.com/2009/03/driverscheme.png" medium="image">
			<media:title type="html">driverscheme</media:title>
		</media:content>

		<media:content url="http://mekonik.files.wordpress.com/2009/03/sensorscheme.png" medium="image">
			<media:title type="html">sensorscheme</media:title>
		</media:content>

		<media:content url="http://mekonik.files.wordpress.com/2009/03/coilpower.png" medium="image">
			<media:title type="html">coilpower</media:title>
		</media:content>

		<media:content url="http://mekonik.files.wordpress.com/2009/03/coilfield.png" medium="image">
			<media:title type="html">coilfield</media:title>
		</media:content>

		<media:content url="http://mekonik.files.wordpress.com/2009/03/inductor.png" medium="image">
			<media:title type="html">inductor</media:title>
		</media:content>

		<media:content url="http://mekonik.files.wordpress.com/2009/03/mathematicainterface.png" medium="image">
			<media:title type="html">mathematicainterface</media:title>
		</media:content>

		<media:content url="http://mekonik.files.wordpress.com/2009/03/inductorcorrectsetting.png" medium="image">
			<media:title type="html">inductorcorrectsetting</media:title>
		</media:content>

		<media:content url="http://mekonik.files.wordpress.com/2009/03/inductorincorrectlow.png" medium="image">
			<media:title type="html">inductorincorrectlow</media:title>
		</media:content>

		<media:content url="http://mekonik.files.wordpress.com/2009/03/inductorincorrecthigh.png" medium="image">
			<media:title type="html">inductorincorrecthigh</media:title>
		</media:content>
	</item>
		<item>
		<title>Magnetic levitation projects</title>
		<link>http://mekonik.wordpress.com/2009/03/04/magnetic-levitation-projects/</link>
		<comments>http://mekonik.wordpress.com/2009/03/04/magnetic-levitation-projects/#comments</comments>
		<pubDate>Wed, 04 Mar 2009 18:26:36 +0000</pubDate>
		<dc:creator>mekonik</dc:creator>
				<category><![CDATA[Links]]></category>
		<category><![CDATA[levitation]]></category>
		<category><![CDATA[magnet]]></category>

		<guid isPermaLink="false">http://mekonik.wordpress.com/?p=41</guid>
		<description><![CDATA[I found a couple of interesting magnetic levitation projects online when I was doing research for my Arduino magnet levitation project. I was also pointed out some really cool projects that I didn&#8217;t know about by  visitors of my blog and of my Arduino forum thread. Here&#8217;s the list: http://de.sevenload.com/sendungen/Computerclub2/folgen/N7wXqna-Folge-20-Computer-club2 &#8211; video from a German [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mekonik.wordpress.com&amp;blog=6791281&amp;post=41&amp;subd=mekonik&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I found a couple of interesting magnetic levitation projects online when I was doing research for my <a href="http://mekonik.wordpress.com/2009/03/02/my-first-arduino-project/">Arduino magnet levitation project</a>. I was also pointed out some really cool projects that I didn&#8217;t know about by  visitors of my blog and of my Arduino forum thread. Here&#8217;s the list:</p>
<ul>
<li><a href="http://de.sevenload.com/sendungen/Computerclub2/folgen/N7wXqna-Folge-20-Computer-club2">http://de.sevenload.com/sendungen/Computerclub2/folgen/N7wXqna-Folge-20-Computer-club2</a> &#8211; video from a German podcast (in German), levitation starts at 16:25, they use ATmega8 and a Hall effect sensor in the base</li>
<li><a href="http://bea.st/sight/levitation/" target="_blank">http://bea.st/sight/levitation/</a> &#8211; combined with a wireless energy transfer, uses ATtiny26, two Hall sensors on the coil, one on each side to compensate for the coil&#8217;s field. Also, check out his <a href="http://bea.st/sight/levitation/" target="_blank">wirelessly powered levitating bulb.<br />
</a></li>
<li><a href="http://amasci.com/maglev/maglev.html">http://amasci.com/maglev/maglev.html</a> &#8211; magnetic cradle, this is a levitation <em>above</em> electromagnets. Uses an array of coils with hall effect sensors to mimic a superconductor.</li>
<li><a href="http://sites.google.com/site/simerlab/levitating-globe">http://sites.google.com/site/simerlab/</a> &#8211; professional magnetic levitation devices, above electromagnets.</li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mekonik.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mekonik.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mekonik.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mekonik.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mekonik.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mekonik.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mekonik.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mekonik.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mekonik.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mekonik.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mekonik.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mekonik.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mekonik.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mekonik.wordpress.com/41/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mekonik.wordpress.com&amp;blog=6791281&amp;post=41&amp;subd=mekonik&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mekonik.wordpress.com/2009/03/04/magnetic-levitation-projects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">mekonik</media:title>
		</media:content>
	</item>
		<item>
		<title>My first Arduino project</title>
		<link>http://mekonik.wordpress.com/2009/03/02/my-first-arduino-project/</link>
		<comments>http://mekonik.wordpress.com/2009/03/02/my-first-arduino-project/#comments</comments>
		<pubDate>Mon, 02 Mar 2009 09:27:11 +0000</pubDate>
		<dc:creator>mekonik</dc:creator>
				<category><![CDATA[Arduino]]></category>
		<category><![CDATA[electromagnet]]></category>
		<category><![CDATA[Hall effect sensor]]></category>
		<category><![CDATA[levitation]]></category>
		<category><![CDATA[magnet]]></category>

		<guid isPermaLink="false">http://mekonik.wordpress.com/?p=16</guid>
		<description><![CDATA[It&#8217;s been only a couple weeks since I discovered Arduino, an open source microcontroller platform. I was looking for a cheap interface between my laptop and electronic circuits. Arduino with its price $35 and easy to use development environment was the best choice. So after getting my Arduino Duemilanove board and ordering some cheap components [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mekonik.wordpress.com&amp;blog=6791281&amp;post=16&amp;subd=mekonik&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been only a couple weeks since I discovered <a href="http://www.arduino.cc/">Arduino</a>, an open source microcontroller platform. I was looking for a cheap interface between my laptop and electronic circuits. Arduino with its price $35 and easy to use development environment was the best choice. So after getting my Arduino <a href="http://www.arduino.cc/en/Main/ArduinoBoardDuemilanove/">Duemilanove </a>board and ordering some cheap components from <a href="http://www.allelectronics.com/">AllElectronics</a>, I had everything to start working on my old dream, making a magnet fly. Well, float.</p>
<p><strong>Update: <a href="http://mekonik.wordpress.com/2009/03/17/arduino-magnet-levitation/">detailed description here</a></strong></p>
<p>It took only a few days to figure out all the problems and my magnet floating device was born:</p>
<div id="attachment_6" class="wp-caption aligncenter" style="width: 460px"><img class="size-full wp-image-6" title="Floating a dart with Arduino" src="http://mekonik.files.wordpress.com/2009/03/snv32105.jpg?w=500" alt="Floating a dart with Arduino"   /><p class="wp-caption-text">Floating a dart with Arduino</p></div>
<p>Here&#8217;s a video:</p>
<p><span id="more-16"></span></p>
<span style="text-align:center; display: block;"><a href="http://mekonik.wordpress.com/2009/03/02/my-first-arduino-project/"><img src="http://img.youtube.com/vi/QunBD_fD04k/2.jpg" alt="" /></a></span>
<p>And another, shorter one:</p>
<span style="text-align:center; display: block;"><a href="http://mekonik.wordpress.com/2009/03/02/my-first-arduino-project/"><img src="http://img.youtube.com/vi/LDcBqwRJCyg/2.jpg" alt="" /></a></span>
<p>A small cylindrical magnet can float as well:</p>
<p style="text-align:left;">
<div id="attachment_7" class="wp-caption aligncenter" style="width: 370px"><img class="size-full wp-image-7" title="Floating magnet" src="http://mekonik.files.wordpress.com/2009/03/picture-76.jpg?w=500" alt="A small magnet floating"   /><p class="wp-caption-text">A small magnet floating</p></div>
<p style="text-align:left;">As you can see by the blurred edges, the tiny magnet oscillates a bit. After a good calibration, the oscillations can be kept very small and the magnet can keep hovering for minutes. The big dart is much more stable and can float pretty much indefinitely. The device uses a small Hall effect sensor (<a href="http://www.datasheetarchive.com/pdf-datasheets/Datasheets-13/DSA-253505.pdf">SS19 </a>from Honeywell, available for $0.50 from <a href="http://www.allelectronics.com/make-a-store/item/SS-19T/HALL-EFFECT-MAGNETIC-POSITION-SENSOR/-/1.html">AllElectronics</a>) to sense the field of the permanent magnet and uses that information to modulate the magnetic field of the electromagnet. Since the sensor is on the electromagnet,</p>
<p style="text-align:left;">
<div id="attachment_8" class="wp-caption aligncenter" style="width: 309px"><img class="size-medium wp-image-8" title="Hall effect sensor" src="http://mekonik.files.wordpress.com/2009/03/snv32110.jpg?w=299&#038;h=225" alt="Hall effect sensor on the electromagnet" width="299" height="225" /><p class="wp-caption-text">Hall effect sensor on the electromagnet</p></div>
<p style="text-align:left;">the reading on it is the sum of the fields of the floating magnet as well as the electromagnet. The greatest challenge was separating these two and getting the floating magnet&#8217;s field only. After some theoretical research into inductors and the Amper&#8217;s law and experimentation, I achieved pretty good stability of a hovering magnet or a magnetic dart or whatever. The result is not completely perfect, some small oscillations are still noticeable. I think that I achieved the limitations given by the Arduino A/D converter. There is always some noise to be expected. I will post more details together with the source codes for both Arduino and my <a href="http://www.wolfram.com/">Mathematica 6</a> control center when I find just a little more time. I even created this blog because I wanted to share this beauty with the world <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p style="text-align:left;">I also made some discoveries:</p>
<ul>
<li>It is really hard to buy a small, cheap electromagnet. I simply couldn&#8217;t find any. If you know how to buy one for say $4, let me know. I had to do a terrible thing, buy a solenoid from AllElectronics for $3.85 and tear it apart to get the coil from it. It works pretty well for me.</li>
<li>The Arduino core library, Serial, for communication through the serial interface, is very slow because it is not optimized for the microcontroller it runs on, ATmega168. These are 8-bit RISC processors without an instruction for division, but the library uses 16-bit variables and division for no reason. The library also doesn&#8217;t offer an output buffer and thus the Serial.print methods lock the program waiting for one byte to be sent before they can send the next one. That can take precious time that is needed when a fast loop is being executed. Therefore I modified the wiring_serial.c file to optimize it for 8-bit RISC and added the output buffer (that can be completely disabled as well). <a href="http://mekonik.wordpress.com/2009/03/02/modified-arduino-library-serial/">See my other blog post for the file download</a>.</li>
</ul>
<p style="text-align:left;">The result looks pretty cool. Actually, it looks awesome. It is, however, only a device that keeps the magnet flying by <em>pulling</em> it up. My ultimate goal it the real &#8220;antigravity&#8221; device, a magnet flying<em> above</em> electromagnets. That is gonna take much more time but is hopefully feasible with this kind of simple circuitry, as was demonstrated by the <a href="http://amasci.com/maglev/maglev.html">maglev craddle</a> or some neat <a href="http://sites.google.com/site/simerlab/levitating-globe">levitating contraptions from SimerLab</a>.</p>
<p style="text-align:left;">A couple more pics at the end. I will post a video too if I feel like it. But it seems that YouTube is full of crappy videos anyway.</p>
<div id="attachment_10" class="wp-caption aligncenter" style="width: 460px"><img class="size-full wp-image-10" title="Arduino floating device" src="http://mekonik.files.wordpress.com/2009/03/snv32107.jpg?w=500" alt="Arduino floating device"   /><p class="wp-caption-text">Arduino floating device</p></div>
<div id="attachment_11" class="wp-caption aligncenter" style="width: 370px"><img class="size-full wp-image-11" title="Floating dart" src="http://mekonik.files.wordpress.com/2009/03/snv32112.jpg?w=500" alt="Floating dart"   /><p class="wp-caption-text">Floating dart</p></div>
<p style="text-align:center;">
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mekonik.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mekonik.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mekonik.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mekonik.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mekonik.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mekonik.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mekonik.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mekonik.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mekonik.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mekonik.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mekonik.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mekonik.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mekonik.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mekonik.wordpress.com/16/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mekonik.wordpress.com&amp;blog=6791281&amp;post=16&amp;subd=mekonik&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mekonik.wordpress.com/2009/03/02/my-first-arduino-project/feed/</wfw:commentRss>
		<slash:comments>53</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">mekonik</media:title>
		</media:content>

		<media:content url="http://mekonik.files.wordpress.com/2009/03/snv32105.jpg" medium="image">
			<media:title type="html">Floating a dart with Arduino</media:title>
		</media:content>

		<media:content url="http://mekonik.files.wordpress.com/2009/03/picture-76.jpg" medium="image">
			<media:title type="html">Floating magnet</media:title>
		</media:content>

		<media:content url="http://mekonik.files.wordpress.com/2009/03/snv32110.jpg?w=299" medium="image">
			<media:title type="html">Hall effect sensor</media:title>
		</media:content>

		<media:content url="http://mekonik.files.wordpress.com/2009/03/snv32107.jpg" medium="image">
			<media:title type="html">Arduino floating device</media:title>
		</media:content>

		<media:content url="http://mekonik.files.wordpress.com/2009/03/snv32112.jpg" medium="image">
			<media:title type="html">Floating dart</media:title>
		</media:content>
	</item>
		<item>
		<title>Modified Arduino library, Serial</title>
		<link>http://mekonik.wordpress.com/2009/03/02/modified-arduino-library-serial/</link>
		<comments>http://mekonik.wordpress.com/2009/03/02/modified-arduino-library-serial/#comments</comments>
		<pubDate>Mon, 02 Mar 2009 09:24:26 +0000</pubDate>
		<dc:creator>mekonik</dc:creator>
				<category><![CDATA[Arduino]]></category>
		<category><![CDATA[Serial]]></category>

		<guid isPermaLink="false">http://mekonik.wordpress.com/?p=19</guid>
		<description><![CDATA[I needed a fast communication between Arduino board and my laptop while working on my first Arduino project. I was monitoring an analog input, the reading on a Hall effect sensor, and some other variables that my Arduino program was using, and that all at a high frequency, 10 kHz. That was producing around 50 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mekonik.wordpress.com&amp;blog=6791281&amp;post=19&amp;subd=mekonik&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I needed a fast communication between <a href="http://www.arduino.cc/">Arduino </a>board and my laptop while working on <a href="http://mekonik.wordpress.com/2009/03/02/my-first-arduino-project/">my first Arduino project</a>. I was monitoring an analog input, the reading on a Hall effect sensor, and some other variables that my Arduino program was using, and that all at a high frequency, 10 kHz. That was producing around 50 kB/s of data that I had to push through the serial connection. I accomplished this finally by modifying the wiring_serial.c file in the Arduino library. <del>You can dowload the modified here.</del>(See below) See the instructions on how to use the file below.</p>
<p><span id="more-19"></span>I first started interfacing Arduino from Java, but soon ran into the problem with standard vs. nonstandard baud rates. The standard baud rates 57600 baud or 115200 baud are not good for the Arduino clock, 16MHz. While 57600 is quite reliable, there are many errors in the data stream from PC to Arduino at 115200. And 57600 was just too slow for my purposes. The solution would be using the baud rates that can be derived from the 16MHz clock using the formula</p>
<pre>baud = 16,000,000/(16 * n);</pre>
<p>where n = 0, 1, &#8230; is an integer. So I thought I would use 250, 500 or 1000 kilobaud. I was relieved when I found that the FT232RL chip, the USB/serial interface for the Arduino board, supports all of these. The <a href="http://www.rxtx.org/">RXTX </a>Java library, however, does not support nonstandard baud rates. Since this is the only Java serial library for Windows I know of, I had to move on and use a different tool.</p>
<p><a href="http://www.wolfram.com/">Mathematica 6</a> with the new dynamic functionality and the handy NETLink package was the perfect alternative. Also the built-in plotting functions came in handy.</p>
<div id="attachment_25" class="wp-caption aligncenter" style="width: 460px"><img class="size-full wp-image-25" title="arduinofrontend" src="http://mekonik.files.wordpress.com/2009/03/arduinofrontend.png?w=500" alt="Arduino controls in mathematica"   /><p class="wp-caption-text">Arduino controls in Mathematica (4 signals with 10000 samples/s)</p></div>
<p>Soon I had a 1 Mbaud link up and running. Everything worked fine when sending data from Arduino to PC. But bytes were missed and dropped when sending even short commands to Arduino. I thought that it was the limitation of ATmega168 microcontroller that was not capable of processing the incoming bytes. But looking at the Serial library, the file wiring_serial.c, I found that the library was simply not optimized.</p>
<p>The biggest problem was the use of division in the interrupt routine that reads bytes from the USART controller and stores them into a buffer. Since the ATmega168 doesn&#8217;t have an instruction for division, the division takes around 200 clock cycles. That makes the whole routine run for around 15μs (microseconds). But with 1Mbaud serial communication, there is only 10μs to process one byte. With the help of westfw on the <a href="http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1235799875/13#13">Arduino forum</a>, we found that there is a simple fix for this.</p>
<p>The library uses a ring buffer that is defined in the wiring_serial.c file as</p>
<pre>#define RX_BUFFER_SIZE 128

unsigned char rx_buffer[RX_BUFFER_SIZE];

int rx_buffer_head = 0;
int rx_buffer_tail = 0;</pre>
<p>The head and tail locations of the first and the last byte of the data in the buffer. When the data is inserted or removed, the head or tail is incremented, respectively. To make sure that they wrap around and stay in the range 0 to RX_BUFFER_SIZE, the following code is used</p>
<pre>rx_buffer_tail = (rx_buffer_tail + 1) % RX_BUFFER_SIZE;</pre>
<p>The problem is that % gets compiled as the modulo operation, instead of the much faster bitwise and, &amp; 127.  The difference is around 200 clock cycles, or some 13μs, compared to 1 cycle. Also, int is not necessary since I don&#8217;t expect anyone use buffer sizes above 256 when there&#8217;s only 1kB of SRAM on ATmega168. The solution has two steps:</p>
<ol>
<li>define the variables as unsigned char
<pre>unsigned char rx_buffer_head = 0;
unsigned char rx_buffer_tail = 0;</pre>
</li>
<li>use the following code to wrap the values
<pre>rx_buffer_tail = rx_buffer_tail + 1;
rx_buffer_tail %= RX_BUFFER_SIZE;</pre>
</li>
</ol>
<p>Modifying all places with the % operation in the wiring_serial.c file results in a much improved function. I did some tests and found:</p>
<ul>
<li>An empty sketch (empty setup() and loop()) with the standard library takes 976 bytes. With the optimization it is only 852 bytes. That&#8217;s a difference <strong>124 bytes</strong> for everybody, no matter if they&#8217;re using Serial. (The reason for that is the interrupt routine that is always linked). Also the other functions in Serial are somewhat shorter.</li>
<li>The interrupt routine is heavily utilized when receiving data and with the current library it takes around 250 cycles only to read one byte. That&#8217;s 15μs. When reading 10 kB/s, 15% of the processor power is spend on that. With 1Mbaud, the routine is not fast enough to read the incoming bytes and they are dropped. Also the standard practice is to have <strong>if (Serial.available() &gt;0)</strong> in the loop(), which takes as much as the interrupt. The modified routine happily works with <strong>1 Mbaud (1,000,000 baud) speeds</strong>. The interrupt routine takes only 4μs to execute and that gives plenty time to process incoming bytes that come every 10μs. Also Serial.available() (14 cycles) and Serial.read() (18 cycles) run much faster, taking only a few cycles.</li>
</ul>
<p>Since those optimization don&#8217;t change anything except they substantially improve the speed and code size, it would be nice to modify the wiring_serial.c file accordingly in the core Arduino library.</p>
<p>The other nice feature would be a buffer for outgoing data. The functions Serial.print and Serial.println send all bytes all at once and lock the program until all bytes are send. It can take a couple millisecond to send just a few bytes on the slower connections like 9600 or 19200. But it makes a lot of difference for faster connections as well. This can be avoided with buffering of  sent data.</p>
<p><del>Until those features are included in the Arduino libraries, I posted the modified version of wiring_serial.c here. Just download the file wiring_serial.c and overwrite the old version in the directory ARDUINODIR\hardware\cores\arduino.</del> Unfortunately, I lost the file while moving to a different server. Also, it is very outdated, so you are safer to download the updated official version.</p>
<p>The size of the outgoing buffer can be set by modifying the code</p>
<pre>#define TX_BUFFER_SIZE 32</pre>
<p>at the beginning of the file. Just replace 32 by your desired buffer size. But make sure to use a power of 2, i.e. one of the values 4, 8, 16, 32, 64, 128 or 256. With other values, the compiler can&#8217;t optimize the % statements and you have the old speeds&#8230; Setting buffer size 0 will use the original unbuffered output. That saves memory and some code that would be used by the buffered write routines, in case you don&#8217;t need buffered output.</p>
<p>I tested and use this version on my ATmega168. The file <em>should</em> work on ATmega8 as well. It compiles, but I couldn&#8217;t test it. If you find any problems or have a suggestion, drop a comment.</p>
<p>Enjoy.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mekonik.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mekonik.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mekonik.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mekonik.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mekonik.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mekonik.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mekonik.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mekonik.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mekonik.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mekonik.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mekonik.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mekonik.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mekonik.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mekonik.wordpress.com/19/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mekonik.wordpress.com&amp;blog=6791281&amp;post=19&amp;subd=mekonik&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mekonik.wordpress.com/2009/03/02/modified-arduino-library-serial/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">mekonik</media:title>
		</media:content>

		<media:content url="http://mekonik.files.wordpress.com/2009/03/arduinofrontend.png" medium="image">
			<media:title type="html">arduinofrontend</media:title>
		</media:content>
	</item>
	</channel>
</rss>
