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

<channel>
	<title>Brain Dump</title>
	<atom:link href="http://cheshirekow.com/blog/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://cheshirekow.com/blog</link>
	<description>A place to note and share things</description>
	<lastBuildDate>Thu, 22 Apr 2010 19:50:01 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Getting Inkscape to Use Latex Fonts (in Windows)</title>
		<link>http://cheshirekow.com/blog/?p=371</link>
		<comments>http://cheshirekow.com/blog/?p=371#comments</comments>
		<pubDate>Thu, 22 Apr 2010 19:50:01 +0000</pubDate>
		<dc:creator>cheshirekow</dc:creator>
				<category><![CDATA[LaTeX]]></category>

		<guid isPermaLink="false">http://cheshirekow.com/blog/?p=371</guid>
		<description><![CDATA[Introduction
Creating graphics for latex can be a real pain. There are a number of different options for doing this, though none of them is completely ideal. If you&#8217;re comfortable using regular latex and generating DVI&#8217;s, then the pstricks package is a very powerful tool. If you prefer generating PDF (now an open standard) files (as [...]]]></description>
			<content:encoded><![CDATA[<img style='float: left; margin-right: 10px; border: none;' src='http://www.gravatar.com/avatar.php?gravatar_id=b30a23a04ca0f61ac513426b4d50907f&amp;default=http://use.perl.org/images/pix.gif' alt='No Gravatar' width=40 height=40/><h3>Introduction</h3>
<p>Creating graphics for latex can be a real pain. There are a number of different options for doing this, though none of them is completely <em>ideal</em>. If you&#8217;re comfortable using regular latex and generating DVI&#8217;s, then the <a href="http://tug.org/PSTricks/main.cgi/">pstricks</a> package is a very powerful tool. If you prefer generating PDF (now an open standard) files (as I do) then the <a href="http://ctan.tug.org/tex-archive/help/Catalogue/entries/pgf.html">PGF/TikZ</a> latex packages are a very powerful and can do just about everything&#8230; except that you have to <em>code</em> your graphics&#8230; which is a very slow iterative process. The GNU Diagramming tool <a href="http://projects.gnome.org/dia/">Dia</a> can create block diagrams and flow charts and can export either <code>pstricks</code> or <code>tikz</code> code. Inkscape is a much nicer user-oriented graphical vector drawing tool, but doesn&#8217;t have native support for for LaTex, and creating graphics including LaTeX math-mode is a real pain. In any case, I&#8217;ve found a number of situations where a figure like the following was pretty easy to do create in Inkscape. </p>
<div id="attachment_373" class="wp-caption aligncenter" style="width: 361px"><a href="http://cheshirekow.com/blog/wp-content/uploads/2010/04/vortexElement.png"><img src="http://cheshirekow.com/blog/wp-content/uploads/2010/04/vortexElement.png" alt="Inkscape Figure for LaTeX" title="vortexElement" width="351" height="77" class="size-full wp-image-373" /></a><p class="wp-caption-text">Inkscape Figure for LaTeX</p></div>
<h3> Getting the Fonts </h3>
<p>In order to get the math font&#8217;s to look like they do in LaTeX, though, you need to have the font&#8217;s installed where Inkscape can find them. Unfortunately, LaTex uses <code>type1</code> postscript fonts, while Inkscape can only find font&#8217;s that windows has installed in the system, which includes true-type or open-type fonts. Fortunately you can <a href="http://www.ctan.org/tex-archive/fonts/cm/ps-type1/bakoma/otf/">get the fonts</a> for &#8220;Computer Modern&#8221; (Knuth&#8217;s Font uses as the default in LaTeX) from the TeX archives in these formats. Simply download these fonts, and install them in windows (drag them to C:/Windows/Fonts). The next time you run Inkscape, it will have these font&#8217;s available and you can use them in your pretty graphics. </p>
<h3> Other Fonts </h3>
<p>There are some other font&#8217;s that you&#8217;ll find used by latex that aren&#8217;t in OTF or TTF format though. The only (open-source) way I&#8217;ve found to convert type-1 font&#8217;s to OTF is through an ancient tool called <a href="http://fontforge.sourceforge.net/">Font-Forge</a>. It&#8217;s an X-Windows program so you&#8217;ll have to install the <a href="http://www.cygwin.com/">Cygwin</a> x-server, or, luckily, someone has <a href="http://www.geocities.jp/meir000/fontforge/">ported</a> it to MinGW (native Win32). </p>
]]></content:encoded>
			<wfw:commentRss>http://cheshirekow.com/blog/?feed=rss2&amp;p=371</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>HTML Documentation with Equation Numbers (Referencing an External PDF Document with Doxygen&#8217;s HTML Documentation)</title>
		<link>http://cheshirekow.com/blog/?p=335</link>
		<comments>http://cheshirekow.com/blog/?p=335#comments</comments>
		<pubDate>Sun, 18 Apr 2010 01:17:44 +0000</pubDate>
		<dc:creator>cheshirekow</dc:creator>
				<category><![CDATA[C++ Discoveries and Notes]]></category>
		<category><![CDATA[Java Discoveries and Notes]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://cheshirekow.com/blog/?p=335</guid>
		<description><![CDATA[So, anyone who uses Doxygen to document their code knows that it&#8217;s pretty much the most amazing thing ever. Seriously, it&#8217;s awesome. One cool thing about it is the ability to reference external documentation. For instance, if you use a library in your code and you want to include the library&#8217;s documentation with your own. [...]]]></description>
			<content:encoded><![CDATA[<img style='float: left; margin-right: 10px; border: none;' src='http://www.gravatar.com/avatar.php?gravatar_id=b30a23a04ca0f61ac513426b4d50907f&amp;default=http://use.perl.org/images/pix.gif' alt='No Gravatar' width=40 height=40/><p>So, anyone who uses Doxygen to document their code knows that it&#8217;s pretty much the most amazing thing ever. Seriously, it&#8217;s awesome. One cool thing about it is the ability to reference external documentation. For instance, if you use a library in your code and you want to include the library&#8217;s documentation with your own. However, let&#8217;s say that (hypothetically of course) you&#8217;re an academic&#8230; and the code you write implements some theoretical design or model. In that case, you may actually want your documentation to reference a paper, or a report that you&#8217;ve written. Perhaps, even many such papers or reports. </p>
<h3>The Problem</h3>
<p>In particular, let&#8217;s say that you&#8217;re a grad student, in the process of writing a paper (and of course, you used LaTex&#8230; because, well, why wouldn&#8217;t you?) and you go and write some code to simulate or demonstrate some elements of that paper. In that case, some of your functions may implement certain equations. Some of your classes (if it&#8217;s object oriented) may implement certain models. For an example, lets say this is your paper:</p>
<p><br/></p>
<div style="overflow:auto;height:4in">
    <img src="wp-content/manual/01/dummy.png"/>
</div>
<p><br/></p>
<p>  Let&#8217;s also assume that you&#8217;ve been good, and have been documenting your code with Doxygen. Let&#8217;s say you had some c++ class that implemented your model and it&#8217;s definition looks something like this:</p>
<p><br/></p>
<div style="overflow:auto;height:4in">

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #ff0000; font-style: italic;">/**
 *  \file       CTheoreticalModel.h
 *  \author     Joe Author (jauthor@institute.edu)
 *  \date       Apr 17, 2010
 *  \brief      Definition file for CTheoreticalModel class
 */</span>
&nbsp;
<span style="color: #339900;">#ifndef CTHEORETICALMODEL_H_</span>
<span style="color: #339900;">#define CTHEORETICALMODEL_H_</span>
&nbsp;
&nbsp;
<span style="color: #ff0000; font-style: italic;">/**
 *  \brief  Theoretical Model derived in section 2, on page 1
 *
 *  This is a detailed description of the model
 */</span>
<span style="color: #0000ff;">class</span> CTheoreticalModel
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">private</span><span style="color: #008080;">:</span>
        <span style="color: #0000ff;">double</span>    m_alpha<span style="color: #008080;">;</span>    <span style="color: #666666;">///&lt; [parameter] defined in equation 2.1</span>
        <span style="color: #0000ff;">double</span>    m_beta<span style="color: #008080;">;</span>     <span style="color: #666666;">///&lt; [parameter] defined in equation 2.2</span>
&nbsp;
    <span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
        <span style="color: #ff0000; font-style: italic;">/**
         *  \brief      Construct a new model using the given parameters
         *  \param[in]  alpha   [parameter] defined in equation 2.1
         *  \param[in]  beta    [parameter] defined in equation 2.2
         */</span>
        CTheoreticalModel<span style="color: #008000;">&#40;</span> <span style="color: #0000ff;">double</span> alpha, <span style="color: #0000ff;">double</span> beta <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
        <span style="color: #ff0000; font-style: italic;">/**
         *  \brief      calculates [some property] by implementing algorithm 2.1
         *              on page 1
         *  \return     [some property]
         */</span>
        <span style="color: #0000ff;">double</span> algorithmA<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
        <span style="color: #ff0000; font-style: italic;">/**
         *  \brief      updates the model by [some parameter] according to the
         *              dynamics of equation 2.4
         *  \param[in]  gamma   [parameter] defined in equation 2.3
         */</span>
        <span style="color: #0000ff;">void</span> equationB<span style="color: #008000;">&#40;</span> <span style="color: #0000ff;">double</span> gamma <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
        <span style="color: #ff0000; font-style: italic;">/**
         *  \brief      tests [some parameter] against the model; implements
         *              equation 2.6
         *  \param[in]  theta   [some parameter] defined by equation 2.5
         */</span>
        <span style="color: #0000ff;">bool</span> testC<span style="color: #008000;">&#40;</span> <span style="color: #0000ff;">double</span> theta <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #339900;">#endif /* CTHEORETICALMODEL_H_ */</span></pre></td></tr></table></div>

</div>
<p><br/></p>
<p>Then the html documentation that doxygen will generate will look like this:</p>
<p><br/><br />
<iframe src="wp-content/manual/01/doxyA/class_c_theoretical_model.html" style="width:100%;height:4in"><br />
</iframe><br />
<br/></p>
<p>Now let&#8217;s say that you talk to your advisor and he suggests that maybe section 2 should come after section 3. Moreover, you add a bunch of content to section 1 so now all of the code for this model is on page five. So then you end up with this:</p>
<p><br/></p>
<div style="overflow:auto;height:4in">
    <img src="wp-content/manual/01/dummy2.png"/>
</div>
<p><br/></p>
<p>So now you have to go back and change all of the equation numbers and page references in your code. But wait, when we wrote our document we &#8220;<code>\label{}</code>&#8220;ed all of our equations, algorithms, and sections. Wouldn&#8217;t it be cool if we could just reference those in the comments? Doxygen exposes latex&#8217;s math mode for us to document inline equations. It uses latex to render the equations, and then uses dvipng to turn those into png images. Moreover, latex has the <code>xr</code> package, which allows us to reference labels from other documents. Lastly, the &#8220;<code>\ref{}</code>&#8221; command is valid inside math-mode. So we have all the tools we need, but there is one slight problem. In order to use the <code>xr</code> latex package, we need to include the &#8220;<code>\externaldocument</code>&#8221; command in the header of the document. </p>
<h3> The solution </h3>
<p>Now here&#8217;s the fun part. When Doxygen renders all of the equations, it does so by generating a single latex source file called &#8220;<code>_formulas.tex</code>&#8220;. We don&#8217;t have explicit access to modify the preamble of that source file, but we are allowed to add optional packages to the list of what is included. We do that by modifying the &#8220;<code>EXTRA_PACKAGES</code>&#8221; line of the doxyfile. For instance, if we edit the doxyfile like this:</p>
<p><br/></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="txt" style="font-family:monospace;">...
# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX 
# packages that should be included in the LaTeX output.
&nbsp;
EXTRA_PACKAGES = amsmath xr amsfonts
...</pre></td></tr></table></div>

<p>then when doxygen generates <code>_formulas.tex</code> it will include in the preamble a list of includes like this</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="tex" style="font-family:monospace;">    \usepackage{amsmath}
    \usepackage{xr}
    \usepackage{amsfonts}</pre></td></tr></table></div>

<p><br/></p>
<p>Note that Doxygen tokenizes the list of packages (parses it) at whitespace, and then takes each token and wraps it with &#8220;\usepackage{<TOKEN>}&#8221;, inserting it into the header. We can hijack this method of input by making <code>EXTRA_PACKAGES</code> variable like this</p>
<p><br/></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="txt" style="font-family:monospace;">...
EXTRA_PACKAGES = amsmath xr}\externaldocument[paper-]{dummy}% amsfonts
...</pre></td></tr></table></div>

<p><br/></p>
<p>Then the preamble of <code>_formulas.tex</code> will look like this</p>
<p><br/></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="tex" style="font-family:monospace;">    \usepackage{amsmath}
    \usepackage{amsfonts}
    \usepackage{xr}\externaldocument[paper-]{dummy}%}
    \usepackage{hyperref}</pre></td></tr></table></div>

<p><br/></p>
<p>Note how we use a comment character (percent) to comment out the closing bracket that doxygen put&#8217;s around our &#8216;package&#8217;. Now we have an extra command in our preamble. If you haven&#8217;t looked up the <code>xr</code> documentation yet, this command means to look for a file called &#8220;<code>dummy.aux</code>&#8221; generated by latex. The package extracts all the labels from that file and appends &#8220;<code>paper-</code>&#8221; to the front of the label names. Now we can change our code documentation to look like this:</p>
<p><br/></p>
<div style="overflow:auto;height:4in">

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #ff0000; font-style: italic;">/**
 *  \file       CTheoreticalModel.h
 *  \author     Joe Author (jauthor@institute.edu)
 *  \date       Apr 17, 2010
 *  \brief      Definition file for CTheoreticalModel class
 */</span>
&nbsp;
<span style="color: #339900;">#ifndef CTHEORETICALMODEL_H_</span>
<span style="color: #339900;">#define CTHEORETICALMODEL_H_</span>
&nbsp;
&nbsp;
<span style="color: #ff0000; font-style: italic;">/**
 *  \brief  Theoretical Model derived in section \f$\ref{paper-sec:Model}\f$,
 *          page \f$\pageref{paper-sec:Model}\f$
 *
 *  This is a detailed description of the model
 */</span>
<span style="color: #0000ff;">class</span> CTheoreticalModel
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">private</span><span style="color: #008080;">:</span>
        <span style="color: #0000ff;">double</span>    m_alpha<span style="color: #008080;">;</span>    <span style="color: #666666;">///&lt; [parameter] defined in equation \f$\ref{paper-eqn:alphaDef}\f$</span>
        <span style="color: #0000ff;">double</span>    m_beta<span style="color: #008080;">;</span>     <span style="color: #666666;">///&lt; [parameter] defined in equation \f$\ref{paper-eqn:betaDef}\f$</span>
&nbsp;
    <span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
        <span style="color: #ff0000; font-style: italic;">/**
         *  \brief      Construct a new model using the given parameters
         *  \param[in]  alpha   [parameter] defined in equation
         *                      \f$\ref{paper-eqn:alphaDef}\f$
         *  \param[in]  beta    [parameter] defined in equation
         *                      \f$\ref{paper-eqn:betaDef}\f$
         */</span>
        CTheoreticalModel<span style="color: #008000;">&#40;</span> <span style="color: #0000ff;">double</span> alpha, <span style="color: #0000ff;">double</span> beta <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
        <span style="color: #ff0000; font-style: italic;">/**
         *  \brief      calculates [some property] by implementing algorithm
         *              \f$\ref{paper-alg:SomeAlgorithm}\f$ on page
         *              \f$\pageref{paper-alg:SomeAlgorithm}\f$
         *  \return     [some property]
         */</span>
        <span style="color: #0000ff;">double</span> algorithmA<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
        <span style="color: #ff0000; font-style: italic;">/**
         *  \brief      updates the model by [some parameter] according to the
         *              dynamics of equation \f$\ref{paper-eqn:SomeEquation}\f$
         *              on page \f$\pageref{paper-eqn:SomeEquation}\f$
         *  \param[in]  gamma   [parameter] defined in equation
         *                      \f$\ref{paper-eqn:gammaDef}\f$
         */</span>
        <span style="color: #0000ff;">void</span> equationB<span style="color: #008000;">&#40;</span> <span style="color: #0000ff;">double</span> gamma <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
        <span style="color: #ff0000; font-style: italic;">/**
         *  \brief      tests [some parameter] against the model; implements
         *              condition \f$\ref{paper-eqn:SomeCondition}\f$
         *  \param[in]  theta   [some parameter] defined by equation
         *                      \f$\ref{paper-eqn:thetaDef}\f$
         */</span>
        <span style="color: #0000ff;">bool</span> testC<span style="color: #008000;">&#40;</span> <span style="color: #0000ff;">double</span> theta <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #339900;">#endif /* CTHEORETICALMODEL_H_ */</span></pre></td></tr></table></div>

</div>
<p><br/></p>
<p>Now all we have to do is dump <code>dummy.aux</code> (generated when we build the paper using latex) into the <code>html</code> directory where doxygen is going to build <code>_formulas.tex</code> and then when we make the documentation it looks like this:</p>
<p><br/><br />
<iframe src="wp-content/manual/01/doxyB/class_c_theoretical_model.html" style="width:100%;height:4in"><br />
</iframe><br />
<br/></p>
<p>Sure, all the references are images&#8230; which isn&#8217;t particularly great, but it&#8217;s a lot better than having to go in and change the labels every time we make a change to the referenced document. Whenever writing a code and a referenced document are done in parallel, this could be quite a handy trick. If you want the html document to look a little more professional, add a package that will set the font to the same as the font set by your doxygen <code>CSS</code> stylesheet. </p>
<p>If you want to play around with the files used in this post, pick them up here: <a href="wp-content/manual/01/dummy.7z">dummy.7z</a>. Create the latex document with the following command.</p>
<p><br/></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="sh" style="font-family:monospace;">latex dummy.tex</pre></td></tr></table></div>

<p><br/></p>
<p>Then copy <code>dummy.aux</code> into the <code>html</code> directory.</p>
<p><br/></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="sh" style="font-family:monospace;">cp dummy.aux html/</pre></td></tr></table></div>

<p><br/></p>
<p>Then run doxygen</p>
<p><br/></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="sh" style="font-family:monospace;">doxygen doxyfile</pre></td></tr></table></div>

<p><br/></p>
]]></content:encoded>
			<wfw:commentRss>http://cheshirekow.com/blog/?feed=rss2&amp;p=335</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>TxDuino: Configuration Builder in WxWidgets</title>
		<link>http://cheshirekow.com/blog/?p=305</link>
		<comments>http://cheshirekow.com/blog/?p=305#comments</comments>
		<pubDate>Sat, 31 Oct 2009 21:01:08 +0000</pubDate>
		<dc:creator>cheshirekow</dc:creator>
				<category><![CDATA[Projects]]></category>

		<guid isPermaLink="false">http://cheshirekow.com/blog/?p=305</guid>
		<description><![CDATA[In relation to the TxDuino (somewhat documented here), I wrote a C++ class to ease the interfacing with the device. That code was posted here. In this post, I am sharing a program that can be used to easily discover and save the configuration of the saturation points of the different actuators on a vehicle. [...]]]></description>
			<content:encoded><![CDATA[<img style='float: left; margin-right: 10px; border: none;' src='http://www.gravatar.com/avatar.php?gravatar_id=b30a23a04ca0f61ac513426b4d50907f&amp;default=http://use.perl.org/images/pix.gif' alt='No Gravatar' width=40 height=40/><p>In relation to the TxDuino (somewhat documented <a href="http://cheshirekow.com/blog/?p=236">here</a>), I wrote a C++ class to ease the interfacing with the device. That code was posted <a href="http://cheshirekow.com/blog/?p=288">here</a>. In this post, I am sharing a program that can be used to easily discover and save the configuration of the saturation points of the different actuators on a vehicle. The program is written using the wxWidgets toolkit so *should* be compatible with any wx-supported operating system. Of course, at this point in time I still haven&#8217;t updated the TxDuino class with linux implementations yet, but hopefully that will happen soon. </p>
<p>The saturation points are the raw commands that correspond to the extreme edges of the actuators range. For instance, if the actuator is a servo, then the minimum saturation point is the minimum command that the servo can actually achieve. If a command lower than that is sent, then the servo will constantly jitter as it cannot actually achieve that rotation. By setting the saturation points, normalized commands (percentages) can be sent to the device using the <code>TxDuino::setPercent()</code> function. </p>
<p>A screenshot of the program in action is below:</p>
<div id="attachment_306" class="wp-caption aligncenter" style="width: 310px"><a href="http://cheshirekow.com/blog/wp-content/uploads/2009/10/screenshot.jpg"><img src="http://cheshirekow.com/blog/wp-content/uploads/2009/10/screenshot-300x293.jpg" alt="Actuator Configuration Tester" title="Actuator Configuration Tester" width="300" height="293" class="size-medium wp-image-306" /></a><p class="wp-caption-text">Actuator Configuration Tester</p></div>
<p>You can connect to the device by entering the device name in the text field at the top and clicking &#8220;Connect&#8221; (or pressing enter). Once the device is connected (success or failure will be reported in the console at the bottom), then commands can start being sent. You can start sending commands by clicking &#8220;Continue&#8221; or stop at any time by clicking &#8220;Pause&#8221;. Note that &#8220;pausing&#8221; won&#8217;t stop your vehicle from doing something retarded, the vehicle&#8217;s actuators will just be stuck in the last commanded state. If the program is not paused, then every time you change one of the values in the spin controls, then that new value is sent as the current command.</p>
<p>To discover the value of the minimum saturation point of one of the actuators, start by clicking on the spin control for that channel, setting it to zero, and hitting enter (this makes the control think it has changed whether it has or not so the value is sent to that channel). If the actuator is saturated (on a servo, if it&#8217;s making noise and/or jittering but not correcting itself) then raise the value by one unit. Keep raising the value until the actuator is no longer saturated. Repeat for the max saturation point and the neutral point. The neutral point is the point corresponding to 0%. For a servo this is most likely near the center of it&#8217;s range. For a speed controller, it should be the same as the minimum saturation.</p>
<p>A windows binary of this program can be downloaded here: <a href='http://cheshirekow.com/blog/wp-content/uploads/2009/10/tester.exe' >Tester</a> .<br />
The source can be downloaded here: <a href='http://cheshirekow.com/blog/wp-content/uploads/2009/10/src1.zip'>TxDuino Actuator Configuration Tester</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://cheshirekow.com/blog/?feed=rss2&amp;p=305</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>TxDuino: C++ classes (windows)</title>
		<link>http://cheshirekow.com/blog/?p=288</link>
		<comments>http://cheshirekow.com/blog/?p=288#comments</comments>
		<pubDate>Sat, 31 Oct 2009 20:38:31 +0000</pubDate>
		<dc:creator>cheshirekow</dc:creator>
				<category><![CDATA[Projects]]></category>

		<guid isPermaLink="false">http://cheshirekow.com/blog/?p=288</guid>
		<description><![CDATA[In order to make interfacing with the TxDuino as easy as possible, I wrote a little c++ class to take care of all the heavy lifting. You connect to a TxDuino device by creating a TxDuino object. The constructor accepts a device name. In windows that looks like &#8220;\\.\COM8&#8221; (my arduino is installed on COM [...]]]></description>
			<content:encoded><![CDATA[<img style='float: left; margin-right: 10px; border: none;' src='http://www.gravatar.com/avatar.php?gravatar_id=b30a23a04ca0f61ac513426b4d50907f&amp;default=http://use.perl.org/images/pix.gif' alt='No Gravatar' width=40 height=40/><p>In order to make interfacing with the <a href="http://cheshirekow.com/blog/?p=236">TxDuino</a> as easy as possible, I wrote a little c++ class to take care of all the heavy lifting. You connect to a TxDuino device by creating a <code>TxDuino</code> object. The constructor accepts a device name. In windows that looks like &#8220;<code>\\.\COM8</code>&#8221; (my arduino is installed on COM port 8). In linux it&#8217;ll look something like &#8220;<code>/dev/ttyS2</code>&#8221; except that I haven&#8217;t gotten around to implementing the linux part of this class yet. </p>
<p>The class, along with the supporting classes and test program are included here: <a href='http://cheshirekow.com/blog/wp-content/uploads/2009/10/src.zip'>TxDuino Class Source</a>.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #ff0000; font-style: italic;">/**
 *  \file       TxDuino.h
 *  \date:      Oct 27, 2009
 *  \brief:
 *
 *  detail:
 */</span>
&nbsp;
<span style="color: #339900;">#ifndef CTXDUINO_H_</span>
<span style="color: #339900;">#define CTXDUINO_H_</span>
&nbsp;
&nbsp;
<span style="color: #339900;">#include &lt;vector&gt;</span>
<span style="color: #339900;">#include &lt;string&gt;</span>
&nbsp;
<span style="color: #339900;">#include &quot;types.h&quot;</span>
&nbsp;
&nbsp;
<span style="color: #0000ff;">namespace</span> txduino
<span style="color: #008000;">&#123;</span>
&nbsp;
&nbsp;
<span style="color: #ff0000; font-style: italic;">/**
 *  \brief  operating system dependendant implementation structure
 */</span>
<span style="color: #0000ff;">struct</span> STxDuinoImpl<span style="color: #008080;">;</span>
&nbsp;
<span style="color: #ff0000; font-style: italic;">/**
 *  \brief Class encapsulating the interface / API for communicating with one
 *  TxDuino device. The TxDuino sends a standard RC PPM signal encoding
 *  commands for up to 8 PWM channels (servos, engine controllers).
 *
 *  The magnitude of each channel is divided into 250 discrete segments.
 *  Exactly how those segments are interpreted by the actuators is determined
 *  by the configuration of this object.
 *
 *  note: channels are zero indexed
 *
 *  \todo   add a constructor that accepts a csv file with the saturations and
 *          neutral points that can be generated from the test program
 */</span>
<span style="color: #0000ff;">class</span> CTxDuino
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">private</span><span style="color: #008080;">:</span>
        STxDuinoImpl<span style="color: #000040;">*</span>   m_osInfo<span style="color: #008080;">;</span>   <span style="color: #666666;">/// pointer to os-dependant implementation</span>
        std<span style="color: #008080;">::</span><span style="color: #007788;">string</span>     m_devName<span style="color: #008080;">;</span>  <span style="color: #666666;">/// system device name,</span>
                                    <span style="color: #666666;">/// i.e. &quot;\\.\COM2&quot;, &quot;/dev/tty2&quot;</span>
&nbsp;
        u8          m_chan      <span style="color: #008000;">&#91;</span><span style="color: #0000dd;">9</span><span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span>    <span style="color: #666666;">/// value for each channel [0,250]</span>
        u8          m_neutral   <span style="color: #008000;">&#91;</span><span style="color: #0000dd;">8</span><span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span>    <span style="color: #666666;">/// the &quot;center&quot; for each actuator</span>
        u8          m_minsat    <span style="color: #008000;">&#91;</span><span style="color: #0000dd;">8</span><span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span>    <span style="color: #666666;">/// the minimum value for each channel</span>
        u8          m_maxsat    <span style="color: #008000;">&#91;</span><span style="color: #0000dd;">8</span><span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span>    <span style="color: #666666;">/// the maximum value for each channel</span>
&nbsp;
&nbsp;
    <span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
        <span style="color: #ff0000; font-style: italic;">/**
         *  \brief  Constructs a new TxDuino object serving as an interface
         *          into on particular TxDuino device.
         *  \param  strDevice   device string, i.e. &quot;\\.\COM2&quot;, &quot;/dev/tty2&quot;
         */</span>
        CTxDuino<span style="color: #008000;">&#40;</span> std<span style="color: #008080;">::</span><span style="color: #007788;">string</span> strDevice <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
        <span style="color: #ff0000; font-style: italic;">/**
         *  \brief  cleans up OS resources reserved for this serial connection
         */</span>
        <span style="color: #0000ff;">virtual</span> ~CTxDuino<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
        <span style="color: #ff0000; font-style: italic;">/**
         *  \brief  sends the current channel definitions to the device
         */</span>
        <span style="color: #0000ff;">void</span> send<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
        <span style="color: #ff0000; font-style: italic;">/**
         *  \brief  sets the value of an actuator as a percent of it's viable
         *          range.
         *  \param  chan        the channel to set
         *  \param  percent     -100% &lt; percent &lt; 100%; value to set channel to
         */</span>
        <span style="color: #0000ff;">void</span> setPercent<span style="color: #008000;">&#40;</span> s32 chan, f64 percent <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
        <span style="color: #ff0000; font-style: italic;">/**
         *  \brief  returns the percent value the indicated actuator is set to,
         *          note: if the neutral point is equal to one of the saturation
         *          points this value may be unreliable
         *  \param  chan        the channel to get
         *  \return percent value of actuator on indicated channel
         */</span>
        f64 getPercent<span style="color: #008000;">&#40;</span> s32 chan <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
        <span style="color: #ff0000; font-style: italic;">/**
         *  \brief  sets the raw value of the actuator pulse width
         *  \param  chan        the channel to set
         *  \param  value      0 &lt; value &lt; 250; value to set channel to
         */</span>
        <span style="color: #0000ff;">void</span> setRaw<span style="color: #008000;">&#40;</span> s32 chan, u8 value <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
        <span style="color: #ff0000; font-style: italic;">/**
         *  \brief  returns the raw value the indicated actuator is set to
         *  \param  chan        the channel to get
         *  \return a value between 0 and 250 indicated the pulse length for
         *          that actuator (multiply by 4us and add 700us to get the
         *          actual pulse length)
         */</span>
        u8 getRaw<span style="color: #008000;">&#40;</span> s32 chan <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
&nbsp;
&nbsp;
        <span style="color: #ff0000; font-style: italic;">/**
         *  \brief  sets the raw value of the actuator pulse width corresponding
         *          to a neutral state of that actuator
         *  \param  chan        the channel to set
         *  \param  value      0 &lt; value &lt; 250; value to set channel to
         */</span>
        <span style="color: #0000ff;">void</span> setNeutral<span style="color: #008000;">&#40;</span> s32 chan, u8 value <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
        <span style="color: #ff0000; font-style: italic;">/**
         *  \brief  returns the raw value corresponding to a neutral state of
         *          the indicated actuator
         *  \param  chan        the channel to get
         *  \return a value between 0 and 250 indicated the pulse length for
         *          that actuator (multiply by 4us and add 700us to get the
         *          actual pulse length)
         */</span>
        u8 getNeutral<span style="color: #008000;">&#40;</span> s32 chan <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
&nbsp;
&nbsp;
        <span style="color: #ff0000; font-style: italic;">/**
         *  \brief  sets the raw value of the actuator pulse width corresponding
         *          to the minimum state of the indicated actuator
         *  \param  chan        the channel to set
         *  \param  value      0 &lt; value &lt; 250; value to set channel to
         */</span>
        <span style="color: #0000ff;">void</span> setMinSat<span style="color: #008000;">&#40;</span> s32 chan, u8 value <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
        <span style="color: #ff0000; font-style: italic;">/**
         *  \brief  returns the raw value corresponding to a minimum state of
         *          the indicated actuator
         *  \param  chan        the channel to get
         *  \return a value between 0 and 250 indicated the pulse length for
         *          that actuator (multiply by 4us and add 700us to get the
         *          actual pulse length)
         */</span>
        u8 getMinSat<span style="color: #008000;">&#40;</span> s32 chan <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
&nbsp;
&nbsp;
        <span style="color: #ff0000; font-style: italic;">/**
         *  \brief  sets the raw value of the actuator pulse width corresponding
         *          to the maximum state of the indicated actuator
         *  \param  chan        the channel to set
         *  \param  value      0 &lt; value &lt; 250; value to set channel to
         */</span>
        <span style="color: #0000ff;">void</span> setMaxSat<span style="color: #008000;">&#40;</span> s32 chan, u8 value <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
        <span style="color: #ff0000; font-style: italic;">/**
         *  \brief  returns the raw value corresponding to a maximum state of
         *          the indicated actuator
         *  \param  chan        the channel to get
         *  \return a value between 0 and 250 indicated the pulse length for
         *          that actuator (multiply by 4us and add 700us to get the
         *          actual pulse length)
         */</span>
        u8 getMaxSat<span style="color: #008000;">&#40;</span> s32 chan <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
        <span style="color: #ff0000; font-style: italic;">/**
         *  \brief  return the device name that was used to connect to this
         *          txduino
         */</span>
        std<span style="color: #008080;">::</span><span style="color: #007788;">string</span> getName<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #339900;">#endif /* CTXDUINO_H_ */</span></pre></td></tr></table></div>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #ff0000; font-style: italic;">/**
 *  \file       CTxDuino.cpp
 *  \date:      Oct 27, 2009
 *  \brief:
 *
 *  detail:
 */</span>
&nbsp;
<span style="color: #339900;">#include &quot;CTxDuino.h&quot;</span>
<span style="color: #339900;">#include &quot;compile.h&quot;</span>
&nbsp;
<span style="color: #339900;">#include &lt;iostream&gt;</span>
<span style="color: #339900;">#include &lt;iomanip&gt;</span>
<span style="color: #339900;">#include &lt;sstream&gt;</span>
<span style="color: #339900;">#include &lt;cmath&gt;</span>
&nbsp;
<span style="color: #339900;">#include &quot;IllegalArgumentException.h&quot;</span>
<span style="color: #339900;">#include &quot;IOException.h&quot;</span>
&nbsp;
<span style="color: #339900;">#ifdef TXD_MINGW</span>
<span style="color: #339900;">#include &lt;windows.h&gt;</span>
<span style="color: #339900;">#endif</span>
&nbsp;
<span style="color: #0000ff;">namespace</span> txduino
<span style="color: #008000;">&#123;</span>
&nbsp;
&nbsp;
&nbsp;
<span style="color: #339900;">#ifdef TXD_MINGW</span>
<span style="color: #0000ff;">struct</span> STxDuinoImpl
<span style="color: #008000;">&#123;</span>
    HANDLE hComPort<span style="color: #008080;">;</span>    <span style="color: #666666;">/// handle to the opened COM device</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
<span style="color: #339900;">#endif</span>
&nbsp;
&nbsp;
<span style="color: #339900;">#ifdef TXD_LINUX</span>
<span style="color: #0000ff;">struct</span> STxDuinoImpl
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">FILE</span> hSerialFile<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
<span style="color: #339900;">#endif</span>
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
<span style="color: #ff0000; font-style: italic;">/**
 *  The initial state of the individual actuators is initialized as follows
 *
 *  \verbatim
 *      minimum saturation: 0
 *                 neutral: 125
 *      maximum saturation: 250
 *                   value: 125
 *  \endverbatim
 *
 *  Note that this is probably not appropriate for your system. Many of the
 *  servos that we've used have minimum saturations around 10 and maximum
 *  saturations around 240. Use the actuator test program to determine what
 *  these values should be.
 */</span>
CTxDuino<span style="color: #008080;">::</span><span style="color: #007788;">CTxDuino</span><span style="color: #008000;">&#40;</span> std<span style="color: #008080;">::</span><span style="color: #007788;">string</span> strDevice <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">using</span> std<span style="color: #008080;">::</span><span style="color: #0000dd;">cout</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">using</span> std<span style="color: #008080;">::</span><span style="color: #007788;">endl</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">using</span> std<span style="color: #008080;">::</span><span style="color: #007788;">stringstream</span><span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #666666;">// intiialize all the arrays</span>
    <span style="color: #0000ff;">for</span><span style="color: #008000;">&#40;</span> <span style="color: #0000ff;">int</span> i<span style="color: #000080;">=</span><span style="color: #0000dd;">0</span><span style="color: #008080;">;</span> i <span style="color: #000080;">&lt;</span> <span style="color: #0000dd;">8</span><span style="color: #008080;">;</span> i<span style="color: #000040;">++</span> <span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        m_chan      <span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">125</span><span style="color: #008080;">;</span>
        m_minsat    <span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
        m_maxsat    <span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">250</span><span style="color: #008080;">;</span>
        m_neutral   <span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">125</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #666666;">// stop byte</span>
    m_chan<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">8</span><span style="color: #008000;">&#93;</span>   <span style="color: #000080;">=</span> <span style="color: #208080;">0xFF</span><span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #666666;">// initialize the OS dependant information</span>
    m_osInfo    <span style="color: #000080;">=</span> <span style="color: #0000dd;">new</span> STxDuinoImpl<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
<span style="color: #ff0000; font-style: italic;">/* ----------------------------------------------------------------------------
 * Windows Specific Implementation:
 * ---------------------------------------------------------------------------*/</span>
&nbsp;
<span style="color: #339900;">#ifdef TXD_MINGW</span>
    <span style="color: #666666;">// open the file using the windows API</span>
    m_osInfo<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>hComPort  <span style="color: #000080;">=</span>
    CreateFile<span style="color: #008000;">&#40;</span> strDevice.<span style="color: #007788;">c_str</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>,          <span style="color: #666666;">// file name</span>
        GENERIC_READ <span style="color: #000040;">|</span> GENERIC_WRITE,       <span style="color: #666666;">// access mode: read and write</span>
        FILE_SHARE_READ<span style="color: #000040;">|</span>FILE_SHARE_WRITE,   <span style="color: #666666;">// (sharing)</span>
        <span style="color: #0000ff;">NULL</span>,                               <span style="color: #666666;">// (security) 0: none</span>
        OPEN_EXISTING,                      <span style="color: #666666;">// (creation) i.e. don't make it</span>
        <span style="color: #0000dd;">0</span>,                                  <span style="color: #666666;">// (overlapped operation)</span>
        <span style="color: #0000ff;">NULL</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>                              <span style="color: #666666;">// no template file</span>
&nbsp;
    <span style="color: #666666;">// check to make sure the file open succeeded</span>
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span> m_osInfo<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>hComPort <span style="color: #000080;">==</span> INVALID_HANDLE_VALUE <span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        stringstream message<span style="color: #008000;">&#40;</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">in</span> <span style="color: #000040;">|</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">out</span> <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        message <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;Invalid Device Name: &quot;</span> <span style="color: #000080;">&lt;&lt;</span> strDevice<span style="color: #008080;">;</span>
        <span style="color: #0000ff;">throw</span> IllegalArgumentException<span style="color: #008000;">&#40;</span>message.<span style="color: #007788;">str</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #666666;">// get the current settings on the com port</span>
    DCB dcb<span style="color: #008080;">;</span>
    GetCommState<span style="color: #008000;">&#40;</span> m_osInfo<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>hComPort, <span style="color: #000040;">&amp;</span>dcb <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #666666;">// change the settings, the TxDuino uses a BAUD rate of 9600</span>
    dcb.<span style="color: #007788;">fBinary</span>     <span style="color: #000080;">=</span>   <span style="color: #0000dd;">1</span><span style="color: #008080;">;</span>
    dcb.<span style="color: #007788;">BaudRate</span>    <span style="color: #000080;">=</span>   CBR_9600<span style="color: #008080;">;</span>
    dcb.<span style="color: #007788;">Parity</span>      <span style="color: #000080;">=</span>   NOPARITY<span style="color: #008080;">;</span>
    dcb.<span style="color: #007788;">ByteSize</span>    <span style="color: #000080;">=</span>   <span style="color: #0000dd;">8</span><span style="color: #008080;">;</span>
    dcb.<span style="color: #007788;">StopBits</span>    <span style="color: #000080;">=</span>   ONESTOPBIT<span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #666666;">// set the new settings for the port</span>
    SetCommState<span style="color: #008000;">&#40;</span> m_osInfo<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>hComPort, <span style="color: #000040;">&amp;</span>dcb <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #339900;">#endif</span>
&nbsp;
&nbsp;
<span style="color: #008000;">&#125;</span>
&nbsp;
&nbsp;
&nbsp;
CTxDuino<span style="color: #008080;">::</span>~CTxDuino<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
&nbsp;
<span style="color: #ff0000; font-style: italic;">/* ----------------------------------------------------------------------------
 * Windows Specific Implementation:
 * ---------------------------------------------------------------------------*/</span>
&nbsp;
<span style="color: #339900;">#ifdef TXD_MINGW</span>
    <span style="color: #666666;">// close the device if it's open</span>
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span> m_osInfo<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>hComPort <span style="color: #000040;">!</span><span style="color: #000080;">=</span> INVALID_HANDLE_VALUE <span style="color: #008000;">&#41;</span>
        CloseHandle<span style="color: #008000;">&#40;</span> m_osInfo<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>hComPort <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #339900;">#endif</span>
&nbsp;
<span style="color: #0000dd;">delete</span> m_osInfo<span style="color: #008080;">;</span>
&nbsp;
<span style="color: #008000;">&#125;</span>
&nbsp;
&nbsp;
&nbsp;
<span style="color: #0000ff;">void</span> CTxDuino<span style="color: #008080;">::</span><span style="color: #007788;">send</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">using</span> std<span style="color: #008080;">::</span><span style="color: #007788;">stringstream</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
    <span style="color: #666666;">// ensure that the last byte of the packet is the stop byte</span>
    m_chan<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">8</span><span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #208080;">0xFF</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
<span style="color: #ff0000; font-style: italic;">/* ----------------------------------------------------------------------------
 * Windows Specific Implementation:
 * ---------------------------------------------------------------------------*/</span>
&nbsp;
<span style="color: #339900;">#ifdef TXD_MINGW</span>
    DWORD bytesWritten<span style="color: #008080;">;</span>
&nbsp;
    BOOL retVal <span style="color: #000080;">=</span>
    WriteFile<span style="color: #008000;">&#40;</span>  m_osInfo<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>hComPort, <span style="color: #666666;">// output handle</span>
                m_chan,             <span style="color: #666666;">// buffer of bytes to send</span>
                <span style="color: #0000dd;">9</span>,                  <span style="color: #666666;">// number of bytes to send from buffer</span>
                <span style="color: #000040;">&amp;</span>bytesWritten,      <span style="color: #666666;">// pointer to a word that receives number of</span>
                                    <span style="color: #666666;">// bytes written</span>
                <span style="color: #0000ff;">NULL</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>              <span style="color: #666666;">// pointer to an OVERLAPPED struct</span>
&nbsp;
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span> bytesWritten <span style="color: #000040;">!</span><span style="color: #000080;">=</span> <span style="color: #0000dd;">9</span> <span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        stringstream message<span style="color: #008000;">&#40;</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">in</span> <span style="color: #000040;">|</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">out</span> <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        message <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;Bytes written to device less than expected: &quot;</span>
                <span style="color: #000080;">&lt;&lt;</span> bytesWritten <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;, expecting 9&quot;</span><span style="color: #008080;">;</span>
        <span style="color: #0000ff;">throw</span> IOException<span style="color: #008000;">&#40;</span>message.<span style="color: #007788;">str</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span> retVal <span style="color: #000080;">==</span> <span style="color: #0000dd;">0</span> <span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        stringstream message<span style="color: #008000;">&#40;</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">in</span> <span style="color: #000040;">|</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">out</span> <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        message <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;Writing to device failed; error code: &quot;</span> <span style="color: #000080;">&lt;&lt;</span> GetLastError<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        <span style="color: #0000ff;">throw</span> IOException<span style="color: #008000;">&#40;</span>message.<span style="color: #007788;">str</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #339900;">#endif</span>
&nbsp;
<span style="color: #008000;">&#125;</span>
&nbsp;
&nbsp;
&nbsp;
<span style="color: #ff0000; font-style: italic;">/**
 *  If the percent is positive, the raw value is calculated as follows
 *
 *  \verbatim
 *      raw = neutral + (max - neutral) * percent
 *  \endverbatim
 *
 *  if the percent is negative, the raw value is calculated as follows
 *
 *  \verbatim
 *      raw = neutral - (neutral - min) * percent
 *  \endverbatim
 */</span>
<span style="color: #0000ff;">void</span> CTxDuino<span style="color: #008080;">::</span><span style="color: #007788;">setPercent</span><span style="color: #008000;">&#40;</span> s32 chan, f64 percent <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">using</span> std<span style="color: #008080;">::</span><span style="color: #007788;">stringstream</span><span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>chan <span style="color: #000080;">&lt;</span> <span style="color: #0000dd;">0</span> <span style="color: #000040;">||</span> chan <span style="color: #000080;">&gt;</span> <span style="color: #0000dd;">7</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        stringstream message<span style="color: #008000;">&#40;</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">in</span> <span style="color: #000040;">|</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">out</span> <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        message <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;Invalid channel number: &quot;</span> <span style="color: #000080;">&lt;&lt;</span> chan <span style="color: #000080;">&lt;&lt;</span> HERE
                <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;valid channels are 0-7&quot;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>percent <span style="color: #000080;">&gt;</span> <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        m_chan<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #008000;">&#40;</span>u8<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#40;</span>m_neutral<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span> <span style="color: #000040;">+</span>
                    <span style="color: #008000;">&#40;</span> m_maxsat<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span> <span style="color: #000040;">-</span> m_neutral<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span> <span style="color: #000040;">*</span> percent <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">else</span>
    <span style="color: #008000;">&#123;</span>
        m_chan<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #008000;">&#40;</span>u8<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#40;</span>m_neutral<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span> <span style="color: #000040;">-</span>
                    <span style="color: #008000;">&#40;</span> m_minsat<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span> <span style="color: #000040;">-</span> m_neutral<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span> <span style="color: #000040;">*</span> percent <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
&nbsp;
&nbsp;
<span style="color: #ff0000; font-style: italic;">/**
 *  If the value is strictly less than the neutral value then the percent value
 *  is calculated by
 *
 *  \verbatim
 *      percent = -( neutral - value ) / (neutral - min);
 *  \endverbatim
 *
 *  If the value is strictly greater than the neutral value then the percent
 *  value is calculated by
 *
 *  \verbatim
 *      percent = ( value - neutral ) / (max - neutral);
 *  \endverbatim
 *
 *  If the value is equal to the neutral value then the percent value is zero.
 */</span>
f64 CTxDuino<span style="color: #008080;">::</span><span style="color: #007788;">getPercent</span><span style="color: #008000;">&#40;</span> s32 chan <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">using</span> std<span style="color: #008080;">::</span><span style="color: #007788;">stringstream</span><span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>chan <span style="color: #000080;">&lt;</span> <span style="color: #0000dd;">0</span> <span style="color: #000040;">||</span> chan <span style="color: #000080;">&gt;</span> <span style="color: #0000dd;">7</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        stringstream message<span style="color: #008000;">&#40;</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">in</span> <span style="color: #000040;">|</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">out</span> <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        message <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;Invalid channel number: &quot;</span> <span style="color: #000080;">&lt;&lt;</span> chan <span style="color: #000080;">&lt;&lt;</span> HERE
                <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;valid channels are 0-7&quot;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span> m_chan<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span> <span style="color: #000080;">&lt;</span> m_neutral<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span> <span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0000ff;">return</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">double</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #000040;">-</span><span style="color: #008000;">&#40;</span>m_neutral<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span> <span style="color: #000040;">-</span> m_chan<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span> <span style="color: #000040;">/</span>
                    <span style="color: #008000;">&#40;</span>m_neutral<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span> <span style="color: #000040;">-</span> m_minsat<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">else</span> <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span> m_chan<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span> <span style="color: #000080;">&gt;</span> m_neutral<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span> <span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0000ff;">return</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">double</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span>m_chan<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span> <span style="color: #000040;">-</span> m_neutral<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span> <span style="color: #000040;">/</span>
                    <span style="color: #008000;">&#40;</span>m_maxsat<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span> <span style="color: #000040;">-</span> m_neutral<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">else</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0000ff;">return</span> <span style="color:#800080;">0.0</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
&nbsp;
&nbsp;
<span style="color: #0000ff;">void</span> CTxDuino<span style="color: #008080;">::</span><span style="color: #007788;">setRaw</span><span style="color: #008000;">&#40;</span> s32 chan, u8 value <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">using</span> std<span style="color: #008080;">::</span><span style="color: #007788;">stringstream</span><span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>chan <span style="color: #000080;">&lt;</span> <span style="color: #0000dd;">0</span> <span style="color: #000040;">||</span> chan <span style="color: #000080;">&gt;</span> <span style="color: #0000dd;">7</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        stringstream message<span style="color: #008000;">&#40;</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">in</span> <span style="color: #000040;">|</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">out</span> <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        message <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;Invalid channel number: &quot;</span> <span style="color: #000080;">&lt;&lt;</span> chan <span style="color: #000080;">&lt;&lt;</span> HERE
                <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;valid channels are 0-7&quot;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>value <span style="color: #000080;">&gt;</span> <span style="color: #0000dd;">250</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        stringstream message<span style="color: #008000;">&#40;</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">in</span> <span style="color: #000040;">|</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">out</span> <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        message <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;Invalid value: &quot;</span> <span style="color: #000080;">&lt;&lt;</span> value <span style="color: #000080;">&lt;&lt;</span> HERE
                <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;valid channels are 0-250&quot;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    m_chan<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> value<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
&nbsp;
&nbsp;
u8 CTxDuino<span style="color: #008080;">::</span><span style="color: #007788;">getRaw</span><span style="color: #008000;">&#40;</span> s32 chan <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">using</span> std<span style="color: #008080;">::</span><span style="color: #007788;">stringstream</span><span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>chan <span style="color: #000080;">&lt;</span> <span style="color: #0000dd;">0</span> <span style="color: #000040;">||</span> chan <span style="color: #000080;">&gt;</span> <span style="color: #0000dd;">7</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        stringstream message<span style="color: #008000;">&#40;</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">in</span> <span style="color: #000040;">|</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">out</span> <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        message <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;Invalid channel number: &quot;</span> <span style="color: #000080;">&lt;&lt;</span> chan <span style="color: #000080;">&lt;&lt;</span> HERE
                <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;valid channels are 0-7&quot;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">return</span> m_chan<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
&nbsp;
&nbsp;
<span style="color: #0000ff;">void</span> CTxDuino<span style="color: #008080;">::</span><span style="color: #007788;">setNeutral</span><span style="color: #008000;">&#40;</span> s32 chan, u8 value <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">using</span> std<span style="color: #008080;">::</span><span style="color: #007788;">stringstream</span><span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>chan <span style="color: #000080;">&lt;</span> <span style="color: #0000dd;">0</span> <span style="color: #000040;">||</span> chan <span style="color: #000080;">&gt;</span> <span style="color: #0000dd;">7</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        stringstream message<span style="color: #008000;">&#40;</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">in</span> <span style="color: #000040;">|</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">out</span> <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        message <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;Invalid channel number: &quot;</span> <span style="color: #000080;">&lt;&lt;</span> chan <span style="color: #000080;">&lt;&lt;</span> HERE
                <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;valid channels are 0-7&quot;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>value <span style="color: #000080;">&gt;</span> <span style="color: #0000dd;">250</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        stringstream message<span style="color: #008000;">&#40;</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">in</span> <span style="color: #000040;">|</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">out</span> <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        message <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;Invalid value: &quot;</span> <span style="color: #000080;">&lt;&lt;</span> value <span style="color: #000080;">&lt;&lt;</span> HERE
                <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;valid channels are 0-250&quot;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    m_neutral<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> value<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
&nbsp;
&nbsp;
u8 CTxDuino<span style="color: #008080;">::</span><span style="color: #007788;">getNeutral</span><span style="color: #008000;">&#40;</span> s32 chan <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">using</span> std<span style="color: #008080;">::</span><span style="color: #007788;">stringstream</span><span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>chan <span style="color: #000080;">&lt;</span> <span style="color: #0000dd;">0</span> <span style="color: #000040;">||</span> chan <span style="color: #000080;">&gt;</span> <span style="color: #0000dd;">7</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        stringstream message<span style="color: #008000;">&#40;</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">in</span> <span style="color: #000040;">|</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">out</span> <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        message <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;Invalid channel number: &quot;</span> <span style="color: #000080;">&lt;&lt;</span> chan <span style="color: #000080;">&lt;&lt;</span> HERE
                <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;valid channels are 0-7&quot;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">return</span> m_neutral<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
&nbsp;
&nbsp;
<span style="color: #0000ff;">void</span> CTxDuino<span style="color: #008080;">::</span><span style="color: #007788;">setMinSat</span><span style="color: #008000;">&#40;</span> s32 chan, u8 value <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">using</span> std<span style="color: #008080;">::</span><span style="color: #007788;">stringstream</span><span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>chan <span style="color: #000080;">&lt;</span> <span style="color: #0000dd;">0</span> <span style="color: #000040;">||</span> chan <span style="color: #000080;">&gt;</span> <span style="color: #0000dd;">7</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        stringstream message<span style="color: #008000;">&#40;</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">in</span> <span style="color: #000040;">|</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">out</span> <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        message <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;Invalid channel number: &quot;</span> <span style="color: #000080;">&lt;&lt;</span> chan <span style="color: #000080;">&lt;&lt;</span> HERE
                <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;valid channels are 0-7&quot;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>value <span style="color: #000080;">&gt;</span> <span style="color: #0000dd;">250</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        stringstream message<span style="color: #008000;">&#40;</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">in</span> <span style="color: #000040;">|</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">out</span> <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        message <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;Invalid value: &quot;</span> <span style="color: #000080;">&lt;&lt;</span> value <span style="color: #000080;">&lt;&lt;</span> HERE
                <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;valid channels are 0-250&quot;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    m_minsat<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> value<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
&nbsp;
&nbsp;
u8 CTxDuino<span style="color: #008080;">::</span><span style="color: #007788;">getMinSat</span><span style="color: #008000;">&#40;</span> s32 chan <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">using</span> std<span style="color: #008080;">::</span><span style="color: #007788;">stringstream</span><span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>chan <span style="color: #000080;">&lt;</span> <span style="color: #0000dd;">0</span> <span style="color: #000040;">||</span> chan <span style="color: #000080;">&gt;</span> <span style="color: #0000dd;">7</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        stringstream message<span style="color: #008000;">&#40;</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">in</span> <span style="color: #000040;">|</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">out</span> <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        message <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;Invalid channel number: &quot;</span> <span style="color: #000080;">&lt;&lt;</span> chan <span style="color: #000080;">&lt;&lt;</span> HERE
                <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;valid channels are 0-7&quot;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">return</span> m_minsat<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
&nbsp;
&nbsp;
<span style="color: #0000ff;">void</span> CTxDuino<span style="color: #008080;">::</span><span style="color: #007788;">setMaxSat</span><span style="color: #008000;">&#40;</span> s32 chan, u8 value <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">using</span> std<span style="color: #008080;">::</span><span style="color: #007788;">stringstream</span><span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>chan <span style="color: #000080;">&lt;</span> <span style="color: #0000dd;">0</span> <span style="color: #000040;">||</span> chan <span style="color: #000080;">&gt;</span> <span style="color: #0000dd;">7</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        stringstream message<span style="color: #008000;">&#40;</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">in</span> <span style="color: #000040;">|</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">out</span> <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        message <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;Invalid channel number: &quot;</span> <span style="color: #000080;">&lt;&lt;</span> chan <span style="color: #000080;">&lt;&lt;</span> HERE
                <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;valid channels are 0-7&quot;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>value <span style="color: #000080;">&gt;</span> <span style="color: #0000dd;">250</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        stringstream message<span style="color: #008000;">&#40;</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">in</span> <span style="color: #000040;">|</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">out</span> <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        message <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;Invalid value: &quot;</span> <span style="color: #000080;">&lt;&lt;</span> value <span style="color: #000080;">&lt;&lt;</span> HERE
                <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;valid channels are 0-250&quot;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    m_maxsat<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> value<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
&nbsp;
&nbsp;
u8 CTxDuino<span style="color: #008080;">::</span><span style="color: #007788;">getMaxSat</span><span style="color: #008000;">&#40;</span> s32 chan <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">using</span> std<span style="color: #008080;">::</span><span style="color: #007788;">stringstream</span><span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>chan <span style="color: #000080;">&lt;</span> <span style="color: #0000dd;">0</span> <span style="color: #000040;">||</span> chan <span style="color: #000080;">&gt;</span> <span style="color: #0000dd;">7</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        stringstream message<span style="color: #008000;">&#40;</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">in</span> <span style="color: #000040;">|</span> stringstream<span style="color: #008080;">::</span><span style="color: #007788;">out</span> <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        message <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;Invalid channel number: &quot;</span> <span style="color: #000080;">&lt;&lt;</span> chan <span style="color: #000080;">&lt;&lt;</span> HERE
                <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;valid channels are 0-7&quot;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">return</span> m_maxsat<span style="color: #008000;">&#91;</span>chan<span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
&nbsp;
&nbsp;
std<span style="color: #008080;">::</span><span style="color: #007788;">string</span> CTxDuino<span style="color: #008080;">::</span><span style="color: #007788;">getName</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">return</span> m_devName<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>A re-write of the <code>serialTest.exe</code> program that sends sinusoidal commands to the plane using this new class demonstrates its use.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #ff0000; font-style: italic;">/**
 * 	\file		serialTest.cpp
 *  \date:      Oct 27, 2009
 *  \brief:
 *
 *  detail:
 *  This is a simple test program that demonstrates how to connect to and
 *  write commands to the arduino transmitter interface using windows.
 *
 *  the TxDuino is an interface into the futaba FP-TP-FM transmitter module,
 *  which accepts an RC PPM input. This signal contains a maximum of 8
 *  servo channels.
 */</span>
&nbsp;
<span style="color: #339900;">#include &lt;iostream&gt;</span>
<span style="color: #339900;">#include &lt;iomanip&gt;</span>
<span style="color: #339900;">#include &lt;cmath&gt;</span>
&nbsp;
<span style="color: #339900;">#include &quot;CTxDuino.h&quot;</span>
<span style="color: #339900;">#include &quot;constants.h&quot;</span>
&nbsp;
<span style="color: #0000ff;">using</span> <span style="color: #0000ff;">namespace</span> std<span style="color: #008080;">;</span>
<span style="color: #0000ff;">using</span> <span style="color: #0000ff;">namespace</span> txduino<span style="color: #008080;">;</span>
&nbsp;
<span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span> <span style="color: #0000ff;">int</span> argc, <span style="color: #0000ff;">char</span><span style="color: #000040;">**</span> argv <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #666666;">// check to ensure that the command line included a device to open</span>
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span> argc <span style="color: #000080;">&lt;</span> <span style="color: #0000dd;">2</span> <span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;Usage: serialTest.exe [Device Name]<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>
                <span style="color: #FF0000;">&quot;   where [Device Name] is the name of the COM port file on<span style="color: #000099; font-weight: bold;">\n</span> &quot;</span>
                <span style="color: #FF0000;">&quot;   windows (i.e. \\\\.\\COM8), or the name of the serial<span style="color: #000099; font-weight: bold;">\n</span> &quot;</span>
                <span style="color: #FF0000;">&quot;   device on *nix (i.e. /dev/tty8)<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span> <span style="color: #000080;">&lt;&lt;</span> endl<span style="color: #008080;">;</span>
&nbsp;
        <span style="color: #0000ff;">return</span> <span style="color: #000040;">-</span><span style="color: #0000dd;">1</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #666666;">// grab a pointer to the device to open</span>
    <span style="color: #0000ff;">char</span><span style="color: #000040;">*</span>       strDevName <span style="color: #000080;">=</span> argv<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #666666;">// create the txduino device</span>
    CTxDuino tx<span style="color: #008000;">&#40;</span>strDevName<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #666666;">// send a sinusoidal input on all channels (except for channel 3, which is</span>
    <span style="color: #666666;">// usually the throttle) for 10 seconds</span>
    <span style="color: #0000ff;">for</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> i<span style="color: #000080;">=</span><span style="color: #0000dd;">0</span><span style="color: #008080;">;</span> i <span style="color: #000080;">&lt;</span> <span style="color: #0000dd;">1000</span><span style="color: #008080;">;</span> i<span style="color: #000040;">++</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0000ff;">for</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> j<span style="color: #000080;">=</span><span style="color: #0000dd;">0</span><span style="color: #008080;">;</span> j <span style="color: #000080;">&lt;</span> <span style="color: #0000dd;">8</span><span style="color: #008080;">;</span> j<span style="color: #000040;">++</span><span style="color: #008000;">&#41;</span>
            tx.<span style="color: #007788;">setRaw</span><span style="color: #008000;">&#40;</span>j, <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">unsigned</span> <span style="color: #0000ff;">char</span><span style="color: #008000;">&#41;</span>
                            <span style="color: #008000;">&#40;</span><span style="color:#800080;">125.0</span> <span style="color: #000040;">+</span> <span style="color:#800080;">75.0</span> <span style="color: #000040;">*</span> <span style="color: #0000dd;">sin</span><span style="color: #008000;">&#40;</span> <span style="color:#800080;">2.0</span> <span style="color: #000040;">*</span> PI <span style="color: #000040;">*</span> i <span style="color: #000040;">/</span> <span style="color:#800080;">100.0</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
        tx.<span style="color: #007788;">setRaw</span><span style="color: #008000;">&#40;</span><span style="color: #0000dd;">2</span>, <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
        <span style="color: #0000ff;">for</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> j<span style="color: #000080;">=</span><span style="color: #0000dd;">0</span><span style="color: #008080;">;</span> j <span style="color: #000080;">&lt;</span> <span style="color: #0000dd;">8</span><span style="color: #008080;">;</span> j<span style="color: #000040;">++</span><span style="color: #008000;">&#41;</span>
            <span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> setw<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">3</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span><span style="color: #008000;">&#41;</span>tx.<span style="color: #007788;">getRaw</span><span style="color: #008000;">&#40;</span>j<span style="color: #008000;">&#41;</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot; | &quot;</span><span style="color: #008080;">;</span>
        <span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> endl<span style="color: #008080;">;</span>
&nbsp;
        tx.<span style="color: #007788;">send</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #339900;">#ifdef TXD_MIGNW</span>
        Sleep<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #339900;">#endif</span>
&nbsp;
<span style="color: #339900;">#ifdef TXD_LINUX</span>
        usleep<span style="color: #008000;">&#40;</span><span style="color:#800080;">0.001</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #339900;">#endif</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
&nbsp;
    <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://cheshirekow.com/blog/?feed=rss2&amp;p=288</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>TxDuino: Custom PC Controlled RC Transmitter</title>
		<link>http://cheshirekow.com/blog/?p=236</link>
		<comments>http://cheshirekow.com/blog/?p=236#comments</comments>
		<pubDate>Sat, 31 Oct 2009 20:22:49 +0000</pubDate>
		<dc:creator>cheshirekow</dc:creator>
				<category><![CDATA[Projects]]></category>

		<guid isPermaLink="false">http://cheshirekow.com/blog/?p=236</guid>
		<description><![CDATA[In our lab we have some very light weight foam aircraft that we do control work with. In order to keep the weight down, we use micro RC receivers that generate PWM signals for each of the servos that deflect one of three control surfaces: ailerons, elevator, and rudder. Note that both ailerons are linked [...]]]></description>
			<content:encoded><![CDATA[<img style='float: left; margin-right: 10px; border: none;' src='http://www.gravatar.com/avatar.php?gravatar_id=b30a23a04ca0f61ac513426b4d50907f&amp;default=http://use.perl.org/images/pix.gif' alt='No Gravatar' width=40 height=40/><p>In our lab we have some very light weight foam aircraft that we do control work with. In order to keep the weight down, we use micro RC receivers that generate <a href="http://en.wikipedia.org/wiki/Pulse-width_modulation">PWM</a> signals for each of the servos that deflect one of three control surfaces: <a href="http://en.wikipedia.org/wiki/Ailerons">ailerons</a>, <a href="http://en.wikipedia.org/wiki/Elevator_%28aircraft%29">elevator</a>, and <a href="http://en.wikipedia.org/wiki/Rudder#Aircraft_rudders">rudder</a>. Note that both ailerons are linked and are together controlled by a single servo (a common setup for these lightweight foam planes). A PWM signal is also sent to control the throttle of the propeller. The glowing little spheres are reflective features to aid in <a href="http://en.wikipedia.org/wiki/Motion_capture">motion capture</a> which we use for estimation of the vehicle&#8217;s <a href="http://en.wikipedia.org/wiki/State_space_%28controls%29#State_variables">state</a>.</p>
<div id="attachment_255" class="wp-caption aligncenter" style="width: 310px"><a href="http://cheshirekow.com/blog/wp-content/uploads/2009/10/PA300001.JPG"><img src="http://cheshirekow.com/blog/wp-content/uploads/2009/10/PA300001-300x225.jpg" alt="One of our &#039;lil baby airplanes" title="Spitfire Foamie" width="300" height="225" class="size-medium wp-image-255" /></a><p class="wp-caption-text">One of our 'lil baby airplanes</p></div>
<p>The trick, however, is to get our control codes, running on a PC somewhere in the room, to actually change the deflection of the airplane&#8217;s control surfaces, or the throttle of the propeller.</p>
<p>The TxDuino project aims to create a single device that allows a PC to control an RC vehicle. At the time of starting this project, the only option for doing this was a device from <a href="http://tti-us.com/rc/">here</a> that could be plugged into the trainer port of a transmitter. An arduino has been used to achieve this same setup as described <a href="http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1193927390">here</a>. Going through the handheld transmitter, however, is a huge hassle for a number of reasons so I set out to create a simple single device that could accomplish this. As it turns out, so did the guys at Tom&#8217;s RC, their solution being this guy <a href="http://www.tti-us.com/rc/projects.htm">here</a>. Anyway, since the work is done, I&#8217;ll share the results. </p>
<p>The easiest way that I figured to pull this off is to work with a modular RC transmitter, and interface directly with the module. For instance this is a transmitter</p>
<div id="attachment_237" class="wp-caption aligncenter" style="width: 310px"><a href="http://cheshirekow.com/blog/wp-content/uploads/2009/10/PA190140.JPG"><img src="http://cheshirekow.com/blog/wp-content/uploads/2009/10/PA190140-300x225.jpg" alt="Futaba Modular Transmitter" title="Futaba Transmitter" width="300" height="225" class="size-medium wp-image-237" /></a><p class="wp-caption-text">Futaba Modular Transmitter</p></div>
<p>And this is the module that plugs into the back of the transmitter</p>
<div id="attachment_238" class="wp-caption aligncenter" style="width: 177px"><a href="http://cheshirekow.com/blog/wp-content/uploads/2009/10/PA300002.JPG"><img src="http://cheshirekow.com/blog/wp-content/uploads/2009/10/PA300002.JPG" alt="the FP-TP-FM Transmitter Module" title="Futaba Transmitter Module" width="167" height="224" class="size-full wp-image-238" /></a><p class="wp-caption-text">the FP-TP-FM Transmitter Module</p></div>
<p>The handheld part creates some kind of <em>signal</em> that it sends to the module, which does <em>something</em>, and then sends <em>something else</em> to the antenna. If I can figure out how to recreate that signal, then the &#8220;somethings&#8221; aren&#8217;t very important. The modules are cheap enough and easy enough to find that there isn&#8217;t much of a need to re-engineer that part.</p>
<p>To begin with, I needed to do some investigation. There are 5 pins on the back of the transmitter. It was easy enough by tracing the module circuit to find the source, ground, and RF out (antenna) pins, but what about the other two? I was hoping one of them was the control signal in a not too esoteric form, and I had no idea what the last would be. I managed to find the control signal with a little probing. Here is a little video showing the transmitter (Tx) hooked up to the module, via some wires with alligator clips which made it easy to investigate things. </p>
<p><object class="wp-caption aligncenter" width="340" height="285" ><param name="movie" value="http://www.youtube-nocookie.com/v/r0gk7WGOia8&#038;hl=en&#038;fs=1&#038;rel=0&#038;border=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube-nocookie.com/v/r0gk7WGOia8&#038;hl=en&#038;fs=1&#038;rel=0&#038;border=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="340" height="285"></embed></object></p>
<p>After figuring our a little of what was going on, I found <a href="http://www.rcgroups.com/forums/showthread.php?t=387442&#038;page=4">this</a> forum post that had a pretty good discussion of the pinouts on this particular module. In particular, <a href="http://www.rcgroups.com/forums/showpost.php?p=8390279&#038;postcount=48">this</a> post I found to be accurate and helpful.</p>
<p>Basically, looking at the back of the transmitter (or the top of the module, when the cover is off) the pins are</p>

<div class="wp_syntax"><div class="code"><pre class="txt" style="font-family:monospace;">        1   2   3   4   5
        .   .   .   .   .
&nbsp;
     left side
     #1 PPM
     #2 V+
     #3 RF check
     #4 ground
     #5 RF out
     right side</pre></div></div>

<p>Of particular importance is the note on that post that the hand-held part is actually pulling the line low to make the pulses, and that the PPM line is at 2.5 volts.</p>
<p>I found a description of the PPM signal <a href="http://www.mftech.de/ppm_en.htm">here</a>. While the measurements I made using the oscilloscope did not match the information on that page exactly (I measured a 4us pulse between channels), using the signal description from that page has had good results. The details of the PPM frame are repeated here.</p>
<ul>
<li>complete PPM-Frame has a length of 22.5 ms. </li>
<li>consists of an overlong start segment combined with 8 analog channels. </li>
<li>stop pulse of 0.3 ms follows every channel&#8217;s impulse. </li>
<li>The length of a channel&#8217;s impulse ranges from 0.7ms to 1.7 ms</li>
</ul>
<p>Below is a video of the PPM signal from the transmitter. You can see the impulse length for each channel changes as I manipulate the control sticks on the handheld part of the transmitter. I apologize for the poor light sensing on my crappy little digital camera. Also, note that channel 5 jumps up and down because it is a flip switch (see the photo above) and only has two possible positions. </p>
<p><object class="wp-caption aligncenter" width="340" height="285"><param name="movie" value="http://www.youtube-nocookie.com/v/qidv_oY1dxw&#038;hl=en&#038;fs=1&#038;rel=0&#038;border=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube-nocookie.com/v/qidv_oY1dxw&#038;hl=en&#038;fs=1&#038;rel=0&#038;border=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="340" height="285"></embed></object></p>
<p>Ok, now that I know what is happening, I need a way to recreate that PPM signal using some kind of device that I can connect to my PC. Hey, the arduino is easy to develop with, comes with a USB controller, and has a nice software library that handles the PC interface stack. It&#8217;s also built around an Atmel microcontroller (my decimila specifically uses a ATmega168L) which has some pretty sophisticated features. It runs at 16Mhz, has three timers that can be used for generating interrupts, and comes with a (relatively) standard C / C++ compiler for writing code. Furthermore, the arduino&#8217;s bootloader means that I don&#8217;t even have to worry about messing with a programmer to get something up and running. </p>
<p>I wont go into all the gory details of the TxDuino design, but I will point out some of the relevant considerations. </p>
<p>The 168L has three timers. <code>Timer1</code> is a 16-bit counter, <code>Timer0</code> and <code>Timer2</code> are 8-bit counters. Timers 0 and 1 share a <a href="http://en.wikipedia.org/wiki/prescaler">prescaler</a>, Timer2 has it&#8217;s own. The prescaler is a component that reduces the update rate of the timer, so we can scale the 16Mhz system clock to some fraction of it&#8217;s rate. Using an 8-bit counter would be extremely limiting because scaling the clock down enough that the counter capacity is sufficient would provide a counter resolution that is too coarse for the fine control we need to generate our waveform. This means I want to use <code>Timer1</code>. However, <code>Timer0</code> is used by the serial stack. I want to be able to send commands from the PC to the TxDuino which will require use of the serial interface. Thus, the serial baud rate will dictate the prescale factor used by Timer0, and thus used by Timer1&#8230; meaning that my choices are limited to whatever the serial stack allows. </p>
<p>A simple arduino test program, however, quells this dilemma.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"> <span style="color: #993333;">int</span> inByte <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>         <span style="color: #666666; font-style: italic;">// incoming serial byte</span>
&nbsp;
 <span style="color: #666666; font-style: italic;">//define the Timer1 overflow interrupt service routine</span>
 ISR<span style="color: #009900;">&#40;</span>TIMER1_OVF_vect<span style="color: #009900;">&#41;</span> 
 <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// print out the current value of the timer control register B which</span>
    <span style="color: #666666; font-style: italic;">// contains the timer prescale value, set when the serial BAUD rate </span>
    <span style="color: #666666; font-style: italic;">// is defined</span>
    Serial.<span style="color: #202020;">print</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Timer1: &quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    Serial.<span style="color: #202020;">print</span><span style="color: #009900;">&#40;</span>TCCR1B<span style="color: #339933;">,</span> HEX<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    Serial.<span style="color: #202020;">print</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\r</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
 <span style="color: #993333;">void</span> setup<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
   <span style="color: #666666; font-style: italic;">// set Timer1 to operate in &quot;normal&quot; mode</span>
   TCCR1A <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #666666; font-style: italic;">// activate Timer1 overflow interrupt </span>
   TIMSK1 <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span> <span style="color: #339933;">&lt;&lt;</span> TOIE1<span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #666666; font-style: italic;">// start serial port at 9600 bps:</span>
   Serial.<span style="color: #202020;">begin</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">9600</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
&nbsp;
 <span style="color: #993333;">void</span> loop<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
   <span style="color: #666666; font-style: italic;">// if we get a valid byte, read analog ins:</span>
   <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>Serial.<span style="color: #202020;">available</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&gt;</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #666666; font-style: italic;">// get incoming byte:</span>
     inByte <span style="color: #339933;">=</span> Serial.<span style="color: #202020;">read</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     Serial.<span style="color: #202020;">print</span><span style="color: #009900;">&#40;</span>inByte<span style="color: #339933;">,</span> BYTE<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     Serial.<span style="color: #202020;">print</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\r</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
 <span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>This program sets the serial baud rate to 9600 bits/sec, and then prints out the value of the <code>Timer1</code> control register. A subset of the bits in that register indicate what the prescaler is set to, and thus what the prescale factor is. Running this program, and looking at the datasheet, I was able to determine that the prescale factor is set to 64. This means that the timer resolution for <code>Timer1</code> is </p>
<img src='http://s.wordpress.com/latex.php?latex=%20%5Cfrac%7B%2064%20%5Cfrac%7B%5Ctext%7Bsystem%20ticks%7D%7D%7B%5Ctext%7Bcounter%20tick%7D%7D%20%7D%20%7B16%2C000%2C000%20%5Cfrac%7B%5Ctext%7Bsystem%20ticks%7D%7D%7B%5Ctext%7Bsecond%7D%7D%7D%20%3D%200.000004%20s%20%3D%204%20%5Cmu%20s&#038;bg=ffffff&#038;fg=000000&#038;s=2' alt=' \frac{ 64 \frac{\text{system ticks}}{\text{counter tick}} } {16,000,000 \frac{\text{system ticks}}{\text{second}}} = 0.000004 s = 4 \mu s' title=' \frac{ 64 \frac{\text{system ticks}}{\text{counter tick}} } {16,000,000 \frac{\text{system ticks}}{\text{second}}} = 0.000004 s = 4 \mu s' class='latex' /> 
<p>And the 16-bit timer has a range of zero to </p>
<img src='http://s.wordpress.com/latex.php?latex=%20%282%5E%7B16%7D%20-%201%29%20%5Ccdot%20%284%20%5Cmu%20s%29%20%3D%2065535%20%5Ccdot%204%20%5Cmu%20s%20%3D%20262140%20%5Cmu%20s%20%3D%20262%2B%20ms%20&#038;bg=ffffff&#038;fg=000000&#038;s=2' alt=' (2^{16} - 1) \cdot (4 \mu s) = 65535 \cdot 4 \mu s = 262140 \mu s = 262+ ms ' title=' (2^{16} - 1) \cdot (4 \mu s) = 65535 \cdot 4 \mu s = 262140 \mu s = 262+ ms ' class='latex' />
<p>Since our frame length is 22.5 ms, we have plenty of range to work with. Also, the range on the individual servo channels is 1000 us, so that gives us 1000/4 = 250 possible steps for each channel (251 possible discrete positions). That gives us a resolution of better than +/- 0.5% for each channel, which is quite acceptable.</p>
<p>Also, since the PPM signal pulls the voltage on the line low, we cannot just use <a href="http://arduino.cc/en/Reference/DigitalWrite"><code>digitalWrite()</code></a> like we usually do when writing to a pin with the arduino. Instead, we need a way to drive the voltage to zero when we want to pull the line low, and a way to basically &#8220;do nothing&#8221; when we want the line high. We can do this by setting the pin voltage to <a href="http://arduino.cc/en/Reference/Constants"><code>LOW</code></a>, and then switching between <a href="http://arduino.cc/en/Reference/Constants"><code>INPUT</code></a> and <a href="http://arduino.cc/en/Reference/Constants"><code>OUTPUT</code></a> using <a href="http://arduino.cc/en/Reference/PinMode"><code>pinMode()</code></a></p>
<p>The last consideration is the serial packet format. I decided to keep things simple. Since each channel can only have 251 possible values, I used an unsigned 8-bit integer (<img src='http://s.wordpress.com/latex.php?latex=2%5E8%20-%201%20%3D%20255&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='2^8 - 1 = 255' title='2^8 - 1 = 255' class='latex' /> possible values for an 8-bit number) for each channel, with values 0-250, and reserving 0xFF (255 in decimal) as a end-of-packet identifier. </p>
<p>Here is a little test code to demonstrate the use of <code>pinMode()</code> to set the voltage of the line high / lo. It listens for either an <code>'a'</code> or <code>'b'</code> character over serial, and sets the line high or low depending on what is sent. If you want to play with this, you can use the terminal from within the Arduino software to send the commands.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">int</span> inByte      <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>    <span style="color: #666666; font-style: italic;">// incoming serial byte</span>
<span style="color: #993333;">int</span> ppmPin      <span style="color: #339933;">=</span> <span style="color: #0000dd;">2</span><span style="color: #339933;">;</span>    <span style="color: #666666; font-style: italic;">// pin to make the waveform on</span>
&nbsp;
&nbsp;
<span style="color: #666666; font-style: italic;">// to setup the device, we will initialize all the channels, and initialize the</span>
<span style="color: #666666; font-style: italic;">// timer settings</span>
<span style="color: #993333;">void</span> setup<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// start serial port at 9600 bps, note that this also sets the Timer1</span>
    <span style="color: #666666; font-style: italic;">// prescaler, so we need to ensure that we don't change it later; a test </span>
    <span style="color: #666666; font-style: italic;">// using a previous program showed that 9600 baud set the prescaler to 64</span>
    <span style="color: #666666; font-style: italic;">// or the Timer1 control register B to 0x03.</span>
    Serial.<span style="color: #202020;">begin</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">9600</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// we configure the signal pin as an input; not that the signal actually is</span>
    <span style="color: #666666; font-style: italic;">// an input but we modify the signal by pulling it low when we need to</span>
    pinMode<span style="color: #009900;">&#40;</span>ppmPin<span style="color: #339933;">,</span> INPUT<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
    <span style="color: #666666; font-style: italic;">// then we set the inital state of the pin to be low</span>
    digitalWrite<span style="color: #009900;">&#40;</span>ppmPin<span style="color: #339933;">,</span> LOW<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
<span style="color: #666666; font-style: italic;">// the main routine monitors the serial port, and on receipt of a completed </span>
<span style="color: #666666; font-style: italic;">// packet will recalculate the compare points for the specified signal</span>
<span style="color: #993333;">void</span> loop<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// if there's a byte available on the serial port, then read it in</span>
    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>Serial.<span style="color: #202020;">available</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&gt;</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">// get incoming byte</span>
        inByte <span style="color: #339933;">=</span> Serial.<span style="color: #202020;">read</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
&nbsp;
        <span style="color: #b1b100;">switch</span><span style="color: #009900;">&#40;</span>inByte<span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #b1b100;">case</span> <span style="color: #ff0000;">'a'</span><span style="color: #339933;">:</span>
                pinMode<span style="color: #009900;">&#40;</span>ppmPin<span style="color: #339933;">,</span> OUTPUT<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                Serial.<span style="color: #202020;">print</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;setting pin low<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
&nbsp;
            <span style="color: #b1b100;">case</span> <span style="color: #ff0000;">'b'</span><span style="color: #339933;">:</span>
                pinMode<span style="color: #009900;">&#40;</span>ppmPin<span style="color: #339933;">,</span> INPUT<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                Serial.<span style="color: #202020;">print</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;setting pin high<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
&nbsp;
            <span style="color: #b1b100;">default</span><span style="color: #339933;">:</span>
                <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Here is a photo of the arduino hooked up with a resistor from the PPM pin to ground which allows me to look at the signal as I&#8217;m testing. The wire from the right side of the resistor to the ground terminal on the arduino is hidden behind the black probe. The other things connected to the breadboard are the transmitter module (the thing in the metal shield), and the back circuit board from the transmitter (the green thing; the pins from that board are plugged into the breadboard). The red thing is the battery for the transmitter. </p>
<div id="attachment_277" class="wp-caption aligncenter" style="width: 310px"><a href="http://cheshirekow.com/blog/wp-content/uploads/2009/10/PA260169.JPG"><img src="http://cheshirekow.com/blog/wp-content/uploads/2009/10/PA260169-300x225.jpg" alt="Arduino Test Setup" title="Arduino Test Setup" width="300" height="225" class="size-medium wp-image-277" /></a><p class="wp-caption-text">Arduino Test Setup</p></div>
<p>Well that&#8217;s pretty much it as far as background and design. Here is the final code that I used to generate the desired waveform. I wont describe it much here since it&#8217;s heavily commented already. Basically it uses two compare match interrupts with <code>Timer1</code>. The two interrupts leap-frog each other and signal either a rising edge or a falling edge. The counter is not cleared when the interrupts are serviced, until the last falling edge is serviced.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">int</span> inByte      <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>    <span style="color: #666666; font-style: italic;">// incoming serial byte</span>
<span style="color: #993333;">int</span> ppmPin      <span style="color: #339933;">=</span> <span style="color: #0000dd;">2</span><span style="color: #339933;">;</span>    <span style="color: #666666; font-style: italic;">// pin to make the waveform on</span>
<span style="color: #993333;">int</span> chan<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">8</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>            <span style="color: #666666; font-style: italic;">// 8 channels encoded as 250 * (percent range)</span>
&nbsp;
<span style="color: #993333;">int</span> compA<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">9</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>           <span style="color: #666666; font-style: italic;">// 9 compare points for Timer1</span>
<span style="color: #993333;">int</span> compB<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">9</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>           <span style="color: #666666; font-style: italic;">// 9 compare points for Timer2</span>
<span style="color: #993333;">int</span> iCompA      <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>    <span style="color: #666666; font-style: italic;">// compare point index for currently active</span>
<span style="color: #993333;">int</span> iCompB      <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>    <span style="color: #666666; font-style: italic;">// compare point index for currently active</span>
&nbsp;
&nbsp;
<span style="color: #666666; font-style: italic;">// the 0xFF byte will serve as a packet delimeter, we don't want to read</span>
<span style="color: #666666; font-style: italic;">// garbage from the serial so we'll start as soon as we get one of those but</span>
<span style="color: #666666; font-style: italic;">// not before</span>
<span style="color: #993333;">int</span> bDelimReceived  <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// we don't want to write to any of the compare registers unless we have to </span>
<span style="color: #666666; font-style: italic;">// so we'll only do so at the end of a frame if that frame involved a change</span>
<span style="color: #666666; font-style: italic;">// in the current signal</span>
<span style="color: #993333;">int</span> bSignalChanged  <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// index for which channel is next to read in</span>
<span style="color: #993333;">int</span> iChan <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
<span style="color: #666666; font-style: italic;">// define the Timer1 compare match interrupt service routine for the rising </span>
<span style="color: #666666; font-style: italic;">// edge</span>
ISR<span style="color: #009900;">&#40;</span>TIMER1_COMPA_vect<span style="color: #009900;">&#41;</span> 
<span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// to set the line high, we switch the pin mode to &quot;INPUT&quot;</span>
    pinMode<span style="color: #009900;">&#40;</span>ppmPin<span style="color: #339933;">,</span> INPUT<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
    <span style="color: #666666; font-style: italic;">// if this is not the last rising edge</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> iCompA <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">8</span> <span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">// then we change the compare register to issue an interrupt at the next</span>
        <span style="color: #666666; font-style: italic;">// rising edge, by incrementing the compare point counter</span>
        iCompA<span style="color: #339933;">++;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">// and then setting the compare register</span>
        OCR1A <span style="color: #339933;">=</span> compA<span style="color: #009900;">&#91;</span>iCompA<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// if this is the last rising edge then we need to set the compare</span>
    <span style="color: #666666; font-style: italic;">// register to be at the time of the rising edge following the start </span>
    <span style="color: #666666; font-style: italic;">// frame</span>
    <span style="color: #b1b100;">else</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">// first, if the signal has changed since while writing the last frame</span>
        <span style="color: #666666; font-style: italic;">// then we need to update the compare points</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> bSignalChanged <span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            compA<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000dd;">3550</span><span style="color: #339933;">;</span>
            <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">8</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
                compA<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">-=</span> chan<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
            <span style="color: #666666; font-style: italic;">// the end of the first pulse is 75 ticks (300us) after that</span>
            compB<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> compA<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">+</span> <span style="color: #0000dd;">75</span><span style="color: #339933;">;</span>
&nbsp;
            <span style="color: #666666; font-style: italic;">// and then the rest of the compare points depend on the value of</span>
            <span style="color: #666666; font-style: italic;">// each channel</span>
            <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> i <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">9</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span> <span style="color: #009900;">&#41;</span>
            <span style="color: #009900;">&#123;</span>
                compA<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> compB<span style="color: #009900;">&#91;</span>i<span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">+</span> chan<span style="color: #009900;">&#91;</span>i<span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">+</span> <span style="color: #0000dd;">175</span><span style="color: #339933;">;</span>
                compB<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> compA<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">+</span> <span style="color: #0000dd;">75</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
&nbsp;
            bSignalChanged <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">// then we set the compare point to match the end of the start segment</span>
        iCompA  <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
        OCR1A   <span style="color: #339933;">=</span> compA<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// define the Timer1 compare match interrupt service routine for the falling </span>
<span style="color: #666666; font-style: italic;">// edge</span>
ISR<span style="color: #009900;">&#40;</span>TIMER1_COMPB_vect<span style="color: #009900;">&#41;</span> 
<span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// to set the pin low we open the collector</span>
    pinMode<span style="color: #009900;">&#40;</span>ppmPin<span style="color: #339933;">,</span> OUTPUT<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
    <span style="color: #666666; font-style: italic;">// if this is not the last falling edge</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> iCompB <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">8</span> <span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">// then we change the compare register to issue an interrupt at the next</span>
        <span style="color: #666666; font-style: italic;">// rising edge, by incrementing the compare point counter</span>
        iCompB<span style="color: #339933;">++;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">// and then setting the compare register</span>
        OCR1B <span style="color: #339933;">=</span> compB<span style="color: #009900;">&#91;</span>iCompB<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// if this is the last falling edge</span>
    <span style="color: #b1b100;">else</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">// then we wrap around to the beginning</span>
        iCompB<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">// and set the compare register</span>
        OCR1B <span style="color: #339933;">=</span> compB<span style="color: #009900;">&#91;</span>iCompB<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">// and we also need to reset the timer because this is the end of the </span>
        <span style="color: #666666; font-style: italic;">// frame</span>
        TCNT1 <span style="color: #339933;">=</span> <span style="color: #208080;">0x00</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
<span style="color: #666666; font-style: italic;">// to setup the device, we will initialize all the channels, and initialize the</span>
<span style="color: #666666; font-style: italic;">// timer settings</span>
<span style="color: #993333;">void</span> setup<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// initialize all eight channels to be at 125, or neutral</span>
    <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">8</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
        chan<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000dd;">125</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// initialize the throttle to be &quot;full left&quot; which is actually &quot;full stop&quot;</span>
    chan<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// start serial port at 9600 bps, note that this also sets the Timer1</span>
    <span style="color: #666666; font-style: italic;">// prescaler, so we need to ensure that we don't change it later; a test </span>
    <span style="color: #666666; font-style: italic;">// using a previous program showed that 9600 baud set the prescaler to 64</span>
    <span style="color: #666666; font-style: italic;">// or the Timer1 control register B to 0x03.</span>
    Serial.<span style="color: #202020;">begin</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">9600</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// set Timer1 to operate in &quot;normal&quot; Mode, and set the</span>
    <span style="color: #666666; font-style: italic;">// prescaler to 64; the default mode is one of the PWM modes so we need to</span>
    <span style="color: #666666; font-style: italic;">// set this</span>
    TCCR1A <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// note: Timer0 and Timer1 share a prescaler, and Timer0 is used by the </span>
    <span style="color: #666666; font-style: italic;">// serial lines. Therefore, we cannot pick the value of the prescaler, </span>
    <span style="color: #666666; font-style: italic;">// rather it is determined by the baud rate we want. A simple program has </span>
    <span style="color: #666666; font-style: italic;">// shown that setting the baud rate to 9600 involves setting the prescaler </span>
    <span style="color: #666666; font-style: italic;">// to 64</span>
&nbsp;
    Serial.<span style="color: #202020;">print</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Timer Control Registers: <span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    Serial.<span style="color: #202020;">print</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;   A: 0x&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    Serial.<span style="color: #202020;">print</span><span style="color: #009900;">&#40;</span>TCCR1A<span style="color: #339933;">,</span> HEX<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    Serial.<span style="color: #202020;">print</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    Serial.<span style="color: #202020;">print</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;   B: 0x&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    Serial.<span style="color: #202020;">print</span><span style="color: #009900;">&#40;</span>TCCR1B<span style="color: #339933;">,</span> HEX<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    Serial.<span style="color: #202020;">print</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// set the Timer1 output compare register A to 3550 ticks, which corresponds </span>
    <span style="color: #666666; font-style: italic;">// to 14,200us with the prescale set to 64; the math goes like this: </span>
    <span style="color: #666666; font-style: italic;">//    with the prescaler set to 64, the Timer1 period is 64/16e6 = 4us</span>
    <span style="color: #666666; font-style: italic;">//    want an interrupt issued after 22.5ms - 8*700us - 9*300us = 14,200us</span>
    <span style="color: #666666; font-style: italic;">//    means we want an interrupt issued after 14,200/4 = 3550 ticks</span>
    compA<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000dd;">3550</span><span style="color: #339933;">;</span>
    OCR1A <span style="color: #339933;">=</span> compA<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// set Timer1 output compare register B to something 300us/4us = 75 ticks </span>
    <span style="color: #666666; font-style: italic;">// after the first compare point for timer A</span>
    compB<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> compA<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">+</span> <span style="color: #0000dd;">75</span><span style="color: #339933;">;</span>
    OCR1B <span style="color: #339933;">=</span> compB<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// we can go ahead and initialize all the other compare points as well, we</span>
    <span style="color: #666666; font-style: italic;">// know that all the channels are set to zero, but I'll do this the long </span>
    <span style="color: #666666; font-style: italic;">// way because it'll match code that we use elsewhere in this program</span>
    <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> i<span style="color: #339933;">=</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">9</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        compA<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> compB<span style="color: #009900;">&#91;</span>i<span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">+</span> chan<span style="color: #009900;">&#91;</span>i<span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">+</span> <span style="color: #0000dd;">175</span><span style="color: #339933;">;</span>
        compB<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> compA<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">+</span> <span style="color: #0000dd;">75</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// activate Timer1 output compare interrupt with compare register A and</span>
    <span style="color: #666666; font-style: italic;">// compare register B by setting the Output Compare Interrupt Enable bits</span>
    TIMSK1 <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span> <span style="color: #339933;">&lt;&lt;</span> OCIE1A <span style="color: #339933;">|</span> <span style="color: #0000dd;">1</span> <span style="color: #339933;">&lt;&lt;</span> OCIE1B<span style="color: #339933;">;</span>
&nbsp;
&nbsp;
    <span style="color: #666666; font-style: italic;">// we configure the signal pin as an input; not that the signal actually is</span>
    <span style="color: #666666; font-style: italic;">// an input but we modify the signal by an open collector so to make the</span>
    <span style="color: #666666; font-style: italic;">// signal high we enable a 20K pull-up resistor, and to make the signal </span>
    <span style="color: #666666; font-style: italic;">// low we open the collector</span>
    pinMode<span style="color: #009900;">&#40;</span>ppmPin<span style="color: #339933;">,</span> INPUT<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
    <span style="color: #666666; font-style: italic;">// then we set the inital state of the pin to be low</span>
    digitalWrite<span style="color: #009900;">&#40;</span>ppmPin<span style="color: #339933;">,</span> LOW<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
&nbsp;
<span style="color: #666666; font-style: italic;">// the main routine monitors the serial port, and on receipt of a completed </span>
<span style="color: #666666; font-style: italic;">// packet will recalculate the compare points for the specified signal</span>
<span style="color: #993333;">void</span> loop<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// if there's a byte available on the serial port, then read it in</span>
    <span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span>Serial.<span style="color: #202020;">available</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&gt;</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">// get incoming byte</span>
        inByte <span style="color: #339933;">=</span> Serial.<span style="color: #202020;">read</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
&nbsp;
        <span style="color: #666666; font-style: italic;">// if the byte is a packet delimiter, then start recording the new </span>
        <span style="color: #666666; font-style: italic;">// packet by resetting the channel indexer</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> inByte <span style="color: #339933;">==</span> <span style="color: #208080;">0xFF</span> <span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            bDelimReceived  <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
            iChan           <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">// otherwise, if we've recieved at least one packet delimiter and the</span>
        <span style="color: #666666; font-style: italic;">// current channel index is valid, then record the chanel value; </span>
        <span style="color: #b1b100;">else</span> <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>bDelimReceived <span style="color: #339933;">&amp;&amp;</span> iChan <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">8</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #666666; font-style: italic;">// we can save some processing time by only updating the stored </span>
            <span style="color: #666666; font-style: italic;">// values if the incoming command has changed, so we'll condition</span>
            <span style="color: #666666; font-style: italic;">// the calculations on the fact that the byte is different than</span>
            <span style="color: #666666; font-style: italic;">// what is already stored</span>
            <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>inByte <span style="color: #339933;">!=</span> chan<span style="color: #009900;">&#91;</span>iChan<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span>
            <span style="color: #009900;">&#123;</span>
                <span style="color: #666666; font-style: italic;">// the protocol is defined to send values between 0 and 250 </span>
                <span style="color: #666666; font-style: italic;">// inclusive, for 250 distinct values; the timing increment is </span>
                <span style="color: #666666; font-style: italic;">// between 0 and 250 so we simply store the value</span>
                chan<span style="color: #009900;">&#91;</span>iChan<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> inByte<span style="color: #339933;">;</span>
&nbsp;
                <span style="color: #666666; font-style: italic;">// since the signal changed, we need to raise the flag</span>
                bSignalChanged <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">true</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
&nbsp;
            <span style="color: #666666; font-style: italic;">// then we increment the channel index so that we're ready for </span>
            <span style="color: #666666; font-style: italic;">// the next byte that's sent</span>
            iChan<span style="color: #339933;">++;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>In order to test this, I wrote this little program to send a sinusoidal input to the TxDuino. Note this code is specific to windows.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/**
 *  \file       serialTest.cpp
 *  \date:      Oct 27, 2009
 *  \brief:
 *
 *  detail:
 *  This is a simple test program that demonstrates how to connect to and
 *  write commands to the arduino transmitter interface using windows.
 *
 *  the TxDuino is an interface into the futaba FP-TP-FM transmitter module,
 *  which accepts an RC PPM input. This signal contains a maximum of 8
 *  servo channels.
 */</span>
&nbsp;
<span style="color: #339933;">#include &lt;iostream&gt;</span>
<span style="color: #339933;">#include &lt;iomanip&gt;</span>
<span style="color: #339933;">#include &lt;cmath&gt;</span>
<span style="color: #339933;">#include &lt;windows.h&gt;</span>
&nbsp;
<span style="color: #339933;">#define PI 3.14159265</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span> <span style="color: #993333;">int</span> argc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span><span style="color: #339933;">**</span> argv <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    using std<span style="color: #339933;">::</span><span style="color: #000066;">cout</span><span style="color: #339933;">;</span>
    using std<span style="color: #339933;">::</span><span style="color: #202020;">endl</span><span style="color: #339933;">;</span>
    using std<span style="color: #339933;">::</span><span style="color: #202020;">sin</span><span style="color: #339933;">;</span>
    using std<span style="color: #339933;">::</span><span style="color: #202020;">setw</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// check to ensure that the command line included a device to open</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> argc <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">2</span> <span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">cout</span> <span style="color: #339933;">&lt;&lt;</span> <span style="color: #ff0000;">&quot;Usage: serialTest.exe [Device Name]<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>
                <span style="color: #ff0000;">&quot;   where [Device Name] is the name of the COM port file on<span style="color: #000099; font-weight: bold;">\n</span> &quot;</span>
                <span style="color: #ff0000;">&quot;   windows (i.e. \\\\.\\COM8), or the name of the serial<span style="color: #000099; font-weight: bold;">\n</span> &quot;</span>
                <span style="color: #ff0000;">&quot;   device on *nix (i.e. /dev/tty8)<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span> <span style="color: #339933;">&lt;&lt;</span> endl<span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// grab a pointer to the device to open</span>
    <span style="color: #993333;">char</span><span style="color: #339933;">*</span>       strDevName <span style="color: #339933;">=</span> argv<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// open the file using the windows API</span>
    HANDLE      hComPort         <span style="color: #339933;">=</span>
    CreateFile<span style="color: #009900;">&#40;</span> strDevName<span style="color: #339933;">,</span>
        GENERIC_READ <span style="color: #339933;">|</span> GENERIC_WRITE<span style="color: #339933;">,</span>       <span style="color: #666666; font-style: italic;">// access mode: read and write</span>
        FILE_SHARE_READ<span style="color: #339933;">|</span>FILE_SHARE_WRITE<span style="color: #339933;">,</span>   <span style="color: #666666; font-style: italic;">// (sharing)</span>
        NULL<span style="color: #339933;">,</span>                               <span style="color: #666666; font-style: italic;">// (security) 0: none</span>
        OPEN_EXISTING<span style="color: #339933;">,</span>                      <span style="color: #666666; font-style: italic;">// (creation) i.e. don't make it</span>
        <span style="color: #0000dd;">0</span><span style="color: #339933;">,</span>                                  <span style="color: #666666; font-style: italic;">// (overlapped operation)</span>
        NULL<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>                              <span style="color: #666666; font-style: italic;">// no template file</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// check to make sure the file open succeeded</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> hComPort <span style="color: #339933;">==</span> INVALID_HANDLE_VALUE <span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">cout</span> <span style="color: #339933;">&lt;&lt;</span> <span style="color: #ff0000;">&quot;FATAL, Invalid device name: &quot;</span> <span style="color: #339933;">&lt;&lt;</span> strDevName <span style="color: #339933;">&lt;&lt;</span> <span style="color: #ff0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span> <span style="color: #339933;">&lt;&lt;</span> endl<span style="color: #339933;">;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">2</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// get the current settings on the com port</span>
    DCB dcb<span style="color: #339933;">;</span>
    GetCommState<span style="color: #009900;">&#40;</span> hComPort<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>dcb <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// change the settings, the TxDuino uses a BAUD rate of 9600</span>
    dcb.<span style="color: #202020;">fBinary</span>     <span style="color: #339933;">=</span>   <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
    dcb.<span style="color: #202020;">BaudRate</span>    <span style="color: #339933;">=</span>   CBR_9600<span style="color: #339933;">;</span>
    dcb.<span style="color: #202020;">Parity</span>      <span style="color: #339933;">=</span>   NOPARITY<span style="color: #339933;">;</span>
    dcb.<span style="color: #202020;">ByteSize</span>    <span style="color: #339933;">=</span>   <span style="color: #0000dd;">8</span><span style="color: #339933;">;</span>
    dcb.<span style="color: #202020;">StopBits</span>    <span style="color: #339933;">=</span>   ONESTOPBIT<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// set the new settings for the port</span>
    SetCommState<span style="color: #009900;">&#40;</span> hComPort<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>dcb <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// allocate the data buffer for sending over serial</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span> data<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">9</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// set the last byte to be the stop byte</span>
    data<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">8</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #208080;">0xFF</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// send a sinusoidal input on all channels (except for channel 3, which is</span>
    <span style="color: #666666; font-style: italic;">// usually the throttle) for 10 seconds</span>
    <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> i<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">1000</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> j<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> j <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">8</span><span style="color: #339933;">;</span> j<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
            data<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">unsigned</span> <span style="color: #993333;">char</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color:#800080;">125.0</span> <span style="color: #339933;">+</span> <span style="color:#800080;">75.0</span> <span style="color: #339933;">*</span> sin<span style="color: #009900;">&#40;</span> <span style="color:#800080;">2.0</span> <span style="color: #339933;">*</span> PI <span style="color: #339933;">*</span> i <span style="color: #339933;">/</span> <span style="color:#800080;">100.0</span> <span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        data<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
        data<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">8</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #208080;">0xFF</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> j<span style="color: #339933;">=</span><span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> j <span style="color: #339933;">&lt;</span> <span style="color: #0000dd;">8</span><span style="color: #339933;">;</span> j<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
            <span style="color: #000066;">cout</span> <span style="color: #339933;">&lt;&lt;</span> setw<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">3</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&lt;&lt;</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span>data<span style="color: #009900;">&#91;</span>j<span style="color: #009900;">&#93;</span> <span style="color: #339933;">&lt;&lt;</span> <span style="color: #ff0000;">&quot; | &quot;</span><span style="color: #339933;">;</span>
        <span style="color: #000066;">cout</span> <span style="color: #339933;">&lt;&lt;</span> endl<span style="color: #339933;">;</span>
&nbsp;
&nbsp;
&nbsp;
        DWORD bytesWritten<span style="color: #339933;">;</span>
&nbsp;
        BOOL retVal <span style="color: #339933;">=</span>
        WriteFile<span style="color: #009900;">&#40;</span>  hComPort<span style="color: #339933;">,</span>       <span style="color: #666666; font-style: italic;">// output handle</span>
                    data<span style="color: #339933;">,</span>           <span style="color: #666666; font-style: italic;">// buffer of bytes to send</span>
                    <span style="color: #0000dd;">9</span><span style="color: #339933;">,</span>              <span style="color: #666666; font-style: italic;">// number of bytes to send from buffer</span>
                    <span style="color: #339933;">&amp;</span>bytesWritten<span style="color: #339933;">,</span>  <span style="color: #666666; font-style: italic;">// pointer to a word that recieves number of</span>
                                    <span style="color: #666666; font-style: italic;">// bytes written</span>
                    NULL<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>          <span style="color: #666666; font-style: italic;">// pointer to an OVERLAPPED struct</span>
&nbsp;
        Sleep<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
    <span style="color: #666666; font-style: italic;">// close the device</span>
    CloseHandle<span style="color: #009900;">&#40;</span> hComPort <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The result of running this test program with the probes attached to the arduino is below. </p>
<p><object class="wp-caption aligncenter" width="340" height="285"><param name="movie" value="http://www.youtube-nocookie.com/v/pSNgNgWAPtw&#038;hl=en&#038;fs=1&#038;rel=0&#038;border=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube-nocookie.com/v/pSNgNgWAPtw&#038;hl=en&#038;fs=1&#038;rel=0&#038;border=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="340" height="285"></embed></object></p>
<p>Then I disconnected the line from the handheld part of the transmitter to the module, and connected the arduino&#8217;s output instead. This is shown below. </p>
<div id="attachment_280" class="wp-caption aligncenter" style="width: 310px"><a href="http://cheshirekow.com/blog/wp-content/uploads/2009/10/PA260170.JPG"><img src="http://cheshirekow.com/blog/wp-content/uploads/2009/10/PA260170-300x225.jpg" alt="Arduino Replacing PPM from Handheld" title="Arduino Replacing PPM from Handheld" width="300" height="225" class="size-medium wp-image-280" /></a><p class="wp-caption-text">Arduino Replacing PPM from Handheld</p></div>
<p>By connecting the oscilloscope probes like this</p>
<div id="attachment_279" class="wp-caption aligncenter" style="width: 310px"><a href="http://cheshirekow.com/blog/wp-content/uploads/2009/10/PA260171.JPG"><img src="http://cheshirekow.com/blog/wp-content/uploads/2009/10/PA260171-300x225.jpg" alt="Arduino Replacing PPM from Handheld with Probes" title="Arduino Replacing PPM from Handheld with Probes" width="300" height="225" class="size-medium wp-image-279" /></a><p class="wp-caption-text">Arduino Replacing PPM from Handheld with Probes</p></div>
<p>I was able to test the output, which is shown here. </p>
<p><object class="wp-caption aligncenter" width="340" height="285"><param name="movie" value="http://www.youtube-nocookie.com/v/deA7yNOKW1Y&#038;hl=en&#038;fs=1&#038;rel=0&#038;border=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube-nocookie.com/v/deA7yNOKW1Y&#038;hl=en&#038;fs=1&#038;rel=0&#038;border=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="340" height="285"></embed></object></p>
<p>Everything looks good at this point. The next thing to do is connect the voltage and ground pins of the module directly to the batter, they RF out line to the antenna, and the RF good line to ground through a resistor. This is shown below. Note the module is underneath the little breadboard. </p>
<div id="attachment_282" class="wp-caption aligncenter" style="width: 310px"><a href="http://cheshirekow.com/blog/wp-content/uploads/2009/10/PA290172.JPG"><img src="http://cheshirekow.com/blog/wp-content/uploads/2009/10/PA290172-300x225.jpg" alt="TxDuino Prototype" title="TxDuino Prototype" width="300" height="225" class="size-medium wp-image-282" /></a><p class="wp-caption-text">TxDuino Prototype</p></div>
<p>And when running the test program, this is what the airplane does.</p>
<p><object class="wp-caption aligncenter" width="340" height="285"><param name="movie" value="http://www.youtube-nocookie.com/v/KhNexR9xfxs&#038;hl=en&#038;fs=1&#038;rel=0&#038;border=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube-nocookie.com/v/KhNexR9xfxs&#038;hl=en&#038;fs=1&#038;rel=0&#038;border=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="340" height="285"></embed></object></p>
<p>And here you can see the waveform generated by the completed TxDuino prototype</p>
<div id="attachment_283" class="wp-caption aligncenter" style="width: 310px"><a href="http://cheshirekow.com/blog/wp-content/uploads/2009/10/PA290173.JPG"><img src="http://cheshirekow.com/blog/wp-content/uploads/2009/10/PA290173-300x225.jpg" alt="TxDuino Prototype Moneyshot" title="TxDuino Prototype Moneyshot" width="300" height="225" class="size-medium wp-image-283" /></a><p class="wp-caption-text">TxDuino Prototype Moneyshot</p></div>
<p>And that&#8217;s that. </p>
]]></content:encoded>
			<wfw:commentRss>http://cheshirekow.com/blog/?feed=rss2&amp;p=236</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Installing Ubuntu 9.04</title>
		<link>http://cheshirekow.com/blog/?p=222</link>
		<comments>http://cheshirekow.com/blog/?p=222#comments</comments>
		<pubDate>Mon, 19 Oct 2009 19:53:50 +0000</pubDate>
		<dc:creator>cheshirekow</dc:creator>
				<category><![CDATA[Software Notes]]></category>

		<guid isPermaLink="false">http://cheshirekow.com/blog/?p=222</guid>
		<description><![CDATA[These are my install notes for installing Ubuntu 9.04 on a Dell XPS with two NVIDIA 7900 GS cards in SLI and three monitors. Some of this is quite specific to this setup. 
I did a no-cd install using the method described here
To install ubuntu without an install CD, I used the net installer. This [...]]]></description>
			<content:encoded><![CDATA[<img style='float: left; margin-right: 10px; border: none;' src='http://www.gravatar.com/avatar.php?gravatar_id=b30a23a04ca0f61ac513426b4d50907f&amp;default=http://use.perl.org/images/pix.gif' alt='No Gravatar' width=40 height=40/><p>These are my install notes for installing Ubuntu 9.04 on a Dell XPS with two NVIDIA 7900 GS cards in SLI and three monitors. Some of this is quite specific to this setup. </p>
<p>I did a no-cd install using the method described <a href="http://ubuntuforums.org/archive/index.php/t-28948.html">here</a></p>
<p>To install ubuntu without an install CD, I used the net installer. This was done on a system currently using windows XP, that already had an additional partition for linux. </p>
<p>The first thing I needed to do is download the linux kernel and the net installer. These are in two files <code>linux.bin</code> and <code>initrd.gz</code>. I got them from </p>
<p><a href="http://archive.ubuntu.com/ubuntu/dists/jaunty/main/installer-i386/current/images/netboot/ubuntu-installer/i386/">http://archive.ubuntu.com/ubuntu/dists/jaunty/main/installer-i386/current/images/netboot/ubuntu-installer/i386/</a></p>
<p>For future versions, replace &#8220;jaunty&#8221; with the nickname of the current distribution. After downloading these two files in windows, I placed them in <code>C:\boot</a>. This directory didn't exist yet, so I created it. </p>
<p>The next thing I needed was a boot loader that will allow me to choose which operating system to boot into. I used the open source GRUB for windows. I got it from the sourceforge page at <a href="http://sourceforge.net/projects/grub4dos/">http://sourceforge.net/projects/grub4dos/</a>. The installer wasn't necessary. Instead I downloaded the grub4dos-0.4.4.zip file from the download page <a href="http://sourceforge.net/projects/grub4dos/files/">http://sourceforge.net/projects/grub4dos/files/</a>. Then I extracted "<code>gldr</code>" into "<code>C:\</code>" and extracted "<code>menu.lst</code>" into "<code>C:\boot\grub\</code>".</p>
<p>Next, I opened <code>menu.lst</code> with a text editor (<a href="http://notepad-plus.sourceforge.net/uk/site.htm">notepad++</a>). At the very bottom I added the following</p>

<div class="wp_syntax"><div class="code"><pre class="txt" style="font-family:monospace;">    title Ubuntu Installer (hd0,1)
    kernel (hd0,1)/boot/linux vga=normal ramdisk_size=14972
    root=/dev/rd/1 rw
    initrd (hd0,1)/boot/initrd.gz</pre></div></div>

<p>Note that the numbers above refer to the physical drive and logical partition, so this may change. Check the drive that you're working with.</p>
<p>The next thing I did was I edited <code>boot.ini</code> so that the windows boot loader would give me the option of loading GRUB instead of windows xp. To edit <code>boot.ini</code> run <code>msconfig</code> and click on the edit button for boot.ini. Then I added this line at the end</p>

<div class="wp_syntax"><div class="code"><pre class="txt" style="font-family:monospace;">    C:\gldr=&quot;Start GRUB&quot;</pre></div></div>

<p>Then I restarted the computer. It stopped after the POST and gave the option of booting into windows or GRUB. I selected GRUB and hit enter. When GRUB loaded I went down to the last optionm "Ubuntu Installer" and hit enter. It then booted into the Ubuntu Net Installer</p>
<p>The installer attempted to use DHCP to connect to the internet. It then asked for a hostname so I put in the static IP address for this machine. </p>
<p>In the last step of the installer it said something about "only the base system is installed" and it asked what other parts to install. I selected something and hit "enter" but that didn't select the item for install, it just advanced to the next step. Thus I ended up with a base installation and just a console prompt. So I installed the rest of the desktop OS with</p>

<div class="wp_syntax"><div class="code"><pre class="txt" style="font-family:monospace;">    sudo apt-get install ubuntu-desktop</pre></div></div>

<p>Then I rebooted to get the desktop. When I was logged in, there was a little green circuit icon on the top right of the desktop. When I clicked this, it prompted me to install the closed-source nvidia drivers. I accepted that and rebooted. I had some problems with the multiple monitors though so I had to edit xorg.conf. Next time, don't reboot, but first open <code>xorg.conf</code> for editing.</p>

<div class="wp_syntax"><div class="code"><pre class="txt" style="font-family:monospace;">    sudo gedit /etc/X11/xorg.conf</pre></div></div>

<p>Then I opened a separate terminal and run</p>

<div class="wp_syntax"><div class="code"><pre class="txt" style="font-family:monospace;">    sudo lspci | grep VGA</pre></div></div>

<p>The first column of what prints out is the "Bus Id" and I used that in <code>xorg.conf</code> need that in a minute. Back in <code>xorg.conf</code> and I edited it as follows.</p>

<div class="wp_syntax"><div class="code"><pre class="txt" style="font-family:monospace;"># nvidia-settings: X configuration file generated by nvidia-settings
# nvidia-settings:  version 1.0  (buildd@palmer)  Sun Feb  1 20:21:04 UTC 2009
&nbsp;
Section &quot;ServerLayout&quot;
    Identifier     &quot;Layout0&quot;
    Screen      0  &quot;Screen0&quot; 1680 0
    Screen      1  &quot;Screen1&quot; RightOf &quot;Screen0&quot;
    Screen      2  &quot;Screen2&quot; LeftOf &quot;Screen0&quot;
    InputDevice    &quot;Keyboard0&quot; &quot;CoreKeyboard&quot;
    InputDevice    &quot;Mouse0&quot; &quot;CorePointer&quot;
EndSection
&nbsp;
Section &quot;Files&quot;
EndSection
&nbsp;
Section &quot;Module&quot;
    Load           &quot;dbe&quot;
    Load           &quot;extmod&quot;
    Load           &quot;type1&quot;
    Load           &quot;freetype&quot;
    Load           &quot;glx&quot;
EndSection
&nbsp;
Section &quot;ServerFlags&quot;
    Option         &quot;Xinerama&quot; &quot;1&quot;
EndSection
&nbsp;
Section &quot;InputDevice&quot;
    # generated from default
    Identifier     &quot;Mouse0&quot;
    Driver         &quot;mouse&quot;
    Option         &quot;Protocol&quot; &quot;auto&quot;
    Option         &quot;Device&quot; &quot;/dev/psaux&quot;
    Option         &quot;Emulate3Buttons&quot; &quot;no&quot;
    Option         &quot;ZAxisMapping&quot; &quot;4 5&quot;
EndSection
&nbsp;
Section &quot;InputDevice&quot;
    # generated from default
    Identifier     &quot;Keyboard0&quot;
    Driver         &quot;kbd&quot;
EndSection
&nbsp;
Section &quot;Monitor&quot;
    # HorizSync source: edid, VertRefresh source: edid
    Identifier     &quot;Monitor2&quot;
    VendorName     &quot;Unknown&quot;
    ModelName      &quot;DELL 2007WFP&quot;
    HorizSync       30.0 - 83.0
    VertRefresh     56.0 - 76.0
    Option         &quot;DPMS&quot;
EndSection
&nbsp;
Section &quot;Monitor&quot;
    # HorizSync source: edid, VertRefresh source: edid
    Identifier     &quot;Monitor0&quot;
    VendorName     &quot;Unknown&quot;
    ModelName      &quot;DELL 2007WFP&quot;
    HorizSync       30.0 - 83.0
    VertRefresh     56.0 - 76.0
    Option         &quot;DPMS&quot;
EndSection
&nbsp;
Section &quot;Monitor&quot;
    # HorizSync source: edid, VertRefresh source: edid
    Identifier     &quot;Monitor1&quot;
    VendorName     &quot;Unknown&quot;
    ModelName      &quot;DELL 2007WFP&quot;
    HorizSync       30.0 - 83.0
    VertRefresh     56.0 - 76.0
    Option         &quot;DPMS&quot;
EndSection
&nbsp;
Section &quot;Device&quot;
    Identifier     &quot;Device2&quot;
    Driver         &quot;nvidia&quot;
    VendorName     &quot;NVIDIA Corporation&quot;
    BoardName      &quot;GeForce 7900 GS&quot;
    BusID          &quot;PCI:1:0:0&quot;
    Screen          1
EndSection
&nbsp;
Section &quot;Device&quot;
    Identifier     &quot;Device0&quot;
    Driver         &quot;nvidia&quot;
    VendorName     &quot;NVIDIA Corporation&quot;
    BoardName      &quot;GeForce 7900 GS&quot;
    BusID          &quot;PCI:1:0:0&quot;
    Screen          0
EndSection
&nbsp;
Section &quot;Device&quot;
    Identifier     &quot;Device1&quot;
    Driver         &quot;nvidia&quot;
    VendorName     &quot;NVIDIA Corporation&quot;
    BoardName      &quot;GeForce 7900 GS&quot;
    BusID          &quot;PCI:6:0:0&quot;
EndSection
&nbsp;
Section &quot;Screen&quot;
    Identifier     &quot;Screen2&quot;
    Device         &quot;Device2&quot;
    Monitor        &quot;Monitor2&quot;
    DefaultDepth    24
    Option         &quot;TwinView&quot; &quot;0&quot;
    Option         &quot;metamodes&quot; &quot;DFP-1: nvidia-auto-select +0+0&quot;
    SubSection     &quot;Display&quot;
        Depth       24
    EndSubSection
EndSection
&nbsp;
Section &quot;Screen&quot;
    Identifier     &quot;Screen0&quot;
    Device         &quot;Device0&quot;
    Monitor        &quot;Monitor0&quot;
    DefaultDepth    24
    Option         &quot;TwinView&quot; &quot;0&quot;
    Option         &quot;TwinViewXineramaInfoOrder&quot; &quot;DFP-0&quot;
    Option         &quot;metamodes&quot; &quot;DFP-0: nvidia-auto-select +0+0; DFP-0: 1600x1024 +0+0; DFP-0: 1440x900 +0+0; DFP-0: 1400x1050 +0+0; DFP-0: 1360x768 +0+0; DFP-0: 1360x768_60_0 +0+0; DFP-0: 1280x1024 +0+0; DFP-0: 1280x1024_60 +0+0; DFP-0: 1280x960 +0+0; DFP-0: 1152x864 +0+0; DFP-0: 1152x864_75_0 +0+0; DFP-0: 1152x864_70 +0+0; DFP-0: 1152x864_60 +0+0; DFP-0: 1024x768 +0+0; DFP-0: 1024x768_70 +0+0; DFP-0: 1024x768_60 +0+0; DFP-0: 960x600 +0+0; DFP-0: 960x540 +0+0; DFP-0: 896x672 +0+0; DFP-0: 840x525 +0+0; DFP-0: 840x525d70 +0+0; DFP-0: 840x525d60 +0+0; DFP-0: 840x525d60_0 +0+0; DFP-0: 832x624 +0+0; DFP-0: 800x600 +0+0; DFP-0: 800x600d60 +0+0; DFP-0: 800x600_75 +0+0; DFP-0: 800x600_72 +0+0; DFP-0: 800x600_60 +0+0; DFP-0: 800x600_56 +0+0; DFP-0: 800x512 +0+0; DFP-0: 720x450 +0+0; DFP-0: 680x384 +0+0; DFP-0: 680x384d60_0 +0+0; DFP-0: 640x512 +0+0; DFP-0: 640x512d60 +0+0; DFP-0: 640x480 +0+0&quot;
    SubSection     &quot;Display&quot;
        Depth       24
    EndSubSection
EndSection
&nbsp;
Section &quot;Screen&quot;
    Identifier     &quot;Screen1&quot;
    Device         &quot;Device1&quot;
    Monitor        &quot;Monitor1&quot;
    DefaultDepth    24
    Option         &quot;TwinView&quot; &quot;0&quot;
    Option         &quot;metamodes&quot; &quot;nvidia-auto-select +0+0&quot;
    SubSection     &quot;Display&quot;
        Depth       24
    EndSubSection
EndSection</pre></div></div>

<p>Then I needed to install flash in Firefox. I opened a terminal and typed.</p>

<div class="wp_syntax"><div class="code"><pre class="txt" style="font-family:monospace;">    sudo apt-get install flash-nonfree</pre></div></div>

<p>But then I needed to fix a few things because flash is buggy and closed source. I opened a terminal and typed the following.</p>

<div class="wp_syntax"><div class="code"><pre class="txt" style="font-family:monospace;">    # Flash also looks for /usr/lib/libesd.so.1
    sudo ln -s /usr/lib/libesd.so.0 /usr/lib/libesd.so.1
&nbsp;
    # Flash expects /tmp/.esd/socket to exist.
    sudo mkdir -p /tmp/.esd/
    sudo touch /tmp/.esd/socket</pre></div></div>

<p>And this enabled sound in flash pages. </p>
]]></content:encoded>
			<wfw:commentRss>http://cheshirekow.com/blog/?feed=rss2&amp;p=222</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Equation for the Line of Night on a Map of Earth</title>
		<link>http://cheshirekow.com/blog/?p=185</link>
		<comments>http://cheshirekow.com/blog/?p=185#comments</comments>
		<pubDate>Sun, 06 Sep 2009 19:46:08 +0000</pubDate>
		<dc:creator>cheshirekow</dc:creator>
				<category><![CDATA[Math]]></category>

		<guid isPermaLink="false">http://cheshirekow.com/blog/?p=185</guid>
		<description><![CDATA[Recently a friend of mine expressed an interest in knowing what the equation was for the night/day line on a rectangular map of the earth. For example: 
The line of night is generated by a projection of the Sun&#8217;s light onto the Earth, which we will consider to be a perfect spheroid with semi-major axis [...]]]></description>
			<content:encoded><![CDATA[<img style='float: left; margin-right: 10px; border: none;' src='http://www.gravatar.com/avatar.php?gravatar_id=b30a23a04ca0f61ac513426b4d50907f&amp;default=http://use.perl.org/images/pix.gif' alt='No Gravatar' width=40 height=40/><p>Recently a friend of mine expressed an interest in knowing what the equation was for the night/day line on a rectangular map of the earth. For example: </p>
<div id="attachment_186" class="wp-caption aligncenter" style="width: 310px"><a href="http://cheshirekow.com/blog/wp-content/uploads/2009/09/map.png"><img src="http://cheshirekow.com/blog/wp-content/uploads/2009/09/map-300x160.png" alt="Line of Night" title="map" width="300" height="160" class="size-medium wp-image-186" /></a><p class="wp-caption-text">Line of Night</p></div>
<p>The line of night is generated by a projection of the Sun&#8217;s light onto the Earth, which we will consider to be a perfect spheroid with semi-major axis of <img src='http://s.wordpress.com/latex.php?latex=R_1&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='R_1' title='R_1' class='latex' /> and semi-minor axis of <img src='http://s.wordpress.com/latex.php?latex=R_2&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='R_2' title='R_2' class='latex' />. If viewed from the &#8220;side&#8221; the line of night will appear to be a line with slope equal to that of the axial tilt (a.k.a obliquity) of earth. This is the inclination angle of Earth&#8217;s planetary rotation axis in relation to its orbital plane, usually denoted by <img src='http://s.wordpress.com/latex.php?latex=%5Cepsilon&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\epsilon' title='\epsilon' class='latex' /> </p>
<div id="attachment_187" class="wp-caption aligncenter" style="width: 310px"><a href="http://cheshirekow.com/blog/wp-content/uploads/2009/09/earthsun.png"><img src="http://cheshirekow.com/blog/wp-content/uploads/2009/09/earthsun-300x163.png" alt="Earth / Sun System" title="earthsun" width="300" height="163" class="size-medium wp-image-187" /></a><p class="wp-caption-text">Earth / Sun System</p></div>
<p>A typical map of the earth is a projection from spherical coordinates onto a cylindrical plane. This is done by drawing a rectangular image where the latitude (<img src='http://s.wordpress.com/latex.php?latex=%5Clambda&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\lambda' title='\lambda' class='latex' />) is mapped to the x-axis and the longitude (<img src='http://s.wordpress.com/latex.php?latex=%5Cphi&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\phi' title='\phi' class='latex' />) is mapped to the y-axis (contrary to the coordinate system used by the digital imaging industry, here we describe the origin as being in the center of the image, with the positive x-axis being to the right, and positive y-axis being up).</p>
<p>Consider then a plane that is perpendicular to the earth&#8217;s plane of orbit, and perpendicular to the vector pointing from the center of the earth toward the sun, and that intersects the earth at it&#8217;s center. The line of night is the intersection of this plane with the Earth. From this observation we can develop an equation for the line of night in terms of <img src='http://s.wordpress.com/latex.php?latex=%5Cphi&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\phi' title='\phi' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=%5Clambda&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\lambda' title='\lambda' class='latex' />.</p>
<div id="attachment_189" class="wp-caption aligncenter" style="width: 190px"><a href="http://cheshirekow.com/blog/wp-content/uploads/2009/09/earthB.png"><img src="http://cheshirekow.com/blog/wp-content/uploads/2009/09/earthB.png" alt="Lattitude and Longitude" title="earthB" width="180" height="226" class="size-full wp-image-189" /></a><p class="wp-caption-text">Lattitude and Longitude</p></div>
<div id="attachment_190" class="wp-caption aligncenter" style="width: 196px"><a href="http://cheshirekow.com/blog/wp-content/uploads/2009/09/earthA.png"><img src="http://cheshirekow.com/blog/wp-content/uploads/2009/09/earthA.png" alt="Line of Night" title="earthA" width="186" height="221" class="size-full wp-image-190" /></a><p class="wp-caption-text">Line of Night</p></div>
<p>If we place a coordinate system on the surface of the earth, centered at the intersection of the line of night with the equator with the positive x-axis corresponding to positive <img src='http://s.wordpress.com/latex.php?latex=%5Clambda&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\lambda' title='\lambda' class='latex' /> and positive y-axis corresponding to positive <img src='http://s.wordpress.com/latex.php?latex=%5Cphi&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\phi' title='\phi' class='latex' /> we can describe the line-of-night plane as </p>
<img src='http://s.wordpress.com/latex.php?latex=y%20%3D%20s%20x&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y = s x' title='y = s x' class='latex' />
<p>where the slope <img src='http://s.wordpress.com/latex.php?latex=s&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='s' title='s' class='latex' /> is related to the obliquity as</p>
<img src='http://s.wordpress.com/latex.php?latex=%20s%20%3D%20%5Cfrac%7B1%7D%7B%5Ctan%28%5Cepsilon%29%7D%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' s = \frac{1}{\tan(\epsilon)} ' title=' s = \frac{1}{\tan(\epsilon)} ' class='latex' />
<p>where <img src='http://s.wordpress.com/latex.php?latex=%5Cepsilon&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\epsilon' title='\epsilon' class='latex' /> is the inclination of the axial tilt of the Earth&#8217;s axis at solstice (<img src='http://s.wordpress.com/latex.php?latex=%5Cepsilon_0&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\epsilon_0' title='\epsilon_0' class='latex' />) scaled according to the position of the Earth in it&#8217;s orbit</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%5Cepsilon%20%3D%20%5Cepsilon_0%20%5Ccos%28%20%5Cfrac%7Bday%7D%7B360%7D%20%29%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' \epsilon = \epsilon_0 \cos( \frac{day}{360} ) ' title=' \epsilon = \epsilon_0 \cos( \frac{day}{360} ) ' class='latex' />
<p>The inclination of the earth&#8217;s axis at solstice is <img src='http://s.wordpress.com/latex.php?latex=%5Cepsilon_0%20%3D%2023.5%5E%5Ccirc%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\epsilon_0 = 23.5^\circ ' title='\epsilon_0 = 23.5^\circ ' class='latex' /></p>
<p>From the parameterization of a spheroid, we know that </p>
<img src='http://s.wordpress.com/latex.php?latex=%20x%20%3D%20R_1%20%5Csin%28%20%5Clambda%20%29%20%5Ccos%28%20%5Cphi%20%29%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' x = R_1 \sin( \lambda ) \cos( \phi ) ' title=' x = R_1 \sin( \lambda ) \cos( \phi ) ' class='latex' /> <br/><br />
<img src='http://s.wordpress.com/latex.php?latex=%20y%20%3D%20R_2%20%5Csin%28%20%5Cphi%20%29%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' y = R_2 \sin( \phi ) ' title=' y = R_2 \sin( \phi ) ' class='latex' />
<p>Combining these with the equation above for the line-of-night plane we see that</p>
<img src='http://s.wordpress.com/latex.php?latex=%20y%20%3D%20%5Cfrac%7B1%7D%7B%5Ctan%28%20%5Cepsilon%20%29%7D%20x%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' y = \frac{1}{\tan( \epsilon )} x ' title=' y = \frac{1}{\tan( \epsilon )} x ' class='latex' /> <br/><br />
<img src='http://s.wordpress.com/latex.php?latex=%20%20R_2%20%5Csin%28%20%5Cphi%20%29%20%3D%20%5Cfrac%7B1%7D%7B%5Ctan%28%20%5Cepsilon%20%29%7D%20R_1%20%5Csin%28%20%5Clambda%20%29%20%5Ccos%28%20%5Cphi%20%29%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='  R_2 \sin( \phi ) = \frac{1}{\tan( \epsilon )} R_1 \sin( \lambda ) \cos( \phi )  ' title='  R_2 \sin( \phi ) = \frac{1}{\tan( \epsilon )} R_1 \sin( \lambda ) \cos( \phi )  ' class='latex' /> <br/><br />
<img src='http://s.wordpress.com/latex.php?latex=%20%20%5Ctan%28%20%5Cphi%20%29%20%3D%20%5Cfrac%7B1%7D%7B%5Ctan%28%20%5Cepsilon%20%29%7D%20%5Cfrac%7BR_1%7D%7BR_2%7D%20%5Csin%28%20%5Clambda%20%29%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='  \tan( \phi ) = \frac{1}{\tan( \epsilon )} \frac{R_1}{R_2} \sin( \lambda )  ' title='  \tan( \phi ) = \frac{1}{\tan( \epsilon )} \frac{R_1}{R_2} \sin( \lambda )  ' class='latex' /> <br/><br />
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20%5Cphi%20%20%3D%20%5Ctext%7Btan%7D%5E-1%20%5Cleft%28%20%5Cfrac%7B1%7D%7B%5Ctan%28%20%5Cepsilon%20%29%7D%20%5Cfrac%7BR_1%7D%7BR_2%7D%20%5Csin%28%20%5Clambda%20%29%20%5Cright%29%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   \phi  = \text{tan}^-1 \left( \frac{1}{\tan( \epsilon )} \frac{R_1}{R_2} \sin( \lambda ) \right) ' title='   \phi  = \text{tan}^-1 \left( \frac{1}{\tan( \epsilon )} \frac{R_1}{R_2} \sin( \lambda ) \right) ' class='latex' /> 
<p>Plotting the value of the longitude against latitude over a range of axial inclinations from <img src='http://s.wordpress.com/latex.php?latex=%5Cepsilon%20%3D%200&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\epsilon = 0' title='\epsilon = 0' class='latex' /> to <img src='http://s.wordpress.com/latex.php?latex=%5Cepsilon%20%3D%2023.5%5E%5Ccirc&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\epsilon = 23.5^\circ' title='\epsilon = 23.5^\circ' class='latex' />, and assuming <img src='http://s.wordpress.com/latex.php?latex=R_1%20%3D%20R_2&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='R_1 = R_2' title='R_1 = R_2' class='latex' /> results in the following:</p>
<div id="attachment_202" class="wp-caption aligncenter" style="width: 310px"><a href="http://cheshirekow.com/blog/wp-content/uploads/2009/09/lineofnight_plot.png"><img src="http://cheshirekow.com/blog/wp-content/uploads/2009/09/lineofnight_plot-300x241.png" alt="Plot of Resulting Line-of-Night Equation" title="lineofnight_plot" width="300" height="241" class="size-medium wp-image-202" /></a><p class="wp-caption-text">Plot of Resulting Line-of-Night Equation</p></div>
<p>Which has exactly the shape we were looking for.</p>
]]></content:encoded>
			<wfw:commentRss>http://cheshirekow.com/blog/?feed=rss2&amp;p=185</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Point on an Ellipsoid of Minimum Distance to Another Point in Space</title>
		<link>http://cheshirekow.com/blog/?p=86</link>
		<comments>http://cheshirekow.com/blog/?p=86#comments</comments>
		<pubDate>Fri, 04 Sep 2009 19:41:30 +0000</pubDate>
		<dc:creator>cheshirekow</dc:creator>
				<category><![CDATA[Math]]></category>

		<guid isPermaLink="false">http://cheshirekow.com/blog/?p=86</guid>
		<description><![CDATA[This is a response to a question posted on the irrlicht forums at here. 
PDF file:
Closest point on an ellipsoid to a point in space (to come)
If one wants to know the closest point on an ellipsoid to another point in space, it can be found using constrained nonlinear optimization. It was stated in the [...]]]></description>
			<content:encoded><![CDATA[<img style='float: left; margin-right: 10px; border: none;' src='http://www.gravatar.com/avatar.php?gravatar_id=b30a23a04ca0f61ac513426b4d50907f&amp;default=http://use.perl.org/images/pix.gif' alt='No Gravatar' width=40 height=40/><p>This is a response to a question posted on the irrlicht forums at <a href="http://irrlicht.sourceforge.net/phpBB2/viewtopic.php?t=34885&#038;start=0&#038;postdays=0&#038;postorder=asc&#038;highlight=">here</a>. </p>
<p>PDF file:<br />
<a href="#">Closest point on an ellipsoid to a point in space</a> (to come)</p>
<p>If one wants to know the closest point on an ellipsoid to another point in space, it can be found using constrained nonlinear optimization. It was stated in the forum thread that there is no closed-form solution to this problem, though I find that rather surprising. I will update this post if I can confirm (or confirm an opposition) to that fact.</p>
<p>In any case, given a point <img src='http://s.wordpress.com/latex.php?latex=%5Cvec%7Bp%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\vec{p}' title='\vec{p}' class='latex' /> in space, where</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%5Cvec%7Bp%7D%20%3D%20%5Cbegin%7Bbmatrix%7D%20p_x%20%5C%5C%20p_y%20%5C%5C%20p_z%20%20%5Cend%7Bbmatrix%7D%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' \vec{p} = \begin{bmatrix} p_x \\ p_y \\ p_z  \end{bmatrix} ' title=' \vec{p} = \begin{bmatrix} p_x \\ p_y \\ p_z  \end{bmatrix} ' class='latex' />
<p>we want to find a point <img src='http://s.wordpress.com/latex.php?latex=%5Cvec%7Bq%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\vec{q}' title='\vec{q}' class='latex' /> that minimizes the euclidean distance to<br />
<img src='http://s.wordpress.com/latex.php?latex=%5Cvec%7Bp%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\vec{p}' title='\vec{p}' class='latex' /> subject to the contraint that it is on an ellipsoid with the<br />
following functional description</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%5Cfrac%7Bx%5E2%7D%7Ba%5E2%7D%20%2B%20%5Cfrac%7By%5E2%7D%7Bb%5E2%7D%20%2B%20%20%5Cfrac%7Bz%5E2%7D%7Bc%5E2%7D%20%3D%201%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' \frac{x^2}{a^2} + \frac{y^2}{b^2} +  \frac{z^2}{c^2} = 1 ' title=' \frac{x^2}{a^2} + \frac{y^2}{b^2} +  \frac{z^2}{c^2} = 1 ' class='latex' />
<p>This corresponds to the minimization of the following cost function (the &#8220;cost&#8221; is the distance to the target point)</p>
<img src='http://s.wordpress.com/latex.php?latex=%20J%28%5Cvec%7Bq%7D%29%20%3D%20%5Csqrt%7B%20%28p_x-q_x%29%5E2%20%2B%20%28p_y-q_y%29%5E2%20%2B%20%20%28p_z-q_z%29%5E2%20%7D%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' J(\vec{q}) = \sqrt{ (p_x-q_x)^2 + (p_y-q_y)^2 +  (p_z-q_z)^2 } ' title=' J(\vec{q}) = \sqrt{ (p_x-q_x)^2 + (p_y-q_y)^2 +  (p_z-q_z)^2 } ' class='latex' />
<p>subject to the following constraint (which just says that it must be on the ellipsoid)</p>
<img src='http://s.wordpress.com/latex.php?latex=%20f%28%5Cvec%7Bq%7D%29%20%3D%20%5Cfrac%7Bq_x%5E2%7D%7Ba%7D%20%2B%20%5Cfrac%7Bq_y%5E2%7D%7Bb%7D%20%2B%20%5Cfrac%7Bq_z%5E2%7D%7Bc%7D%20-%201%20%3D%200%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' f(\vec{q}) = \frac{q_x^2}{a} + \frac{q_y^2}{b} + \frac{q_z^2}{c} - 1 = 0 ' title=' f(\vec{q}) = \frac{q_x^2}{a} + \frac{q_y^2}{b} + \frac{q_z^2}{c} - 1 = 0 ' class='latex' />
<p>Now there are many ways to solve this problem. I will outline two of them here known as <i>steepest descent</i> (or <i>gradient search</i>) and the <i>leGrange method</i>.</p>
<h1>Steepest Descent</h1>
<p>First comes steepest decent, because it is the easiest to understand graphically. The goal here is that, starting at some point on the ellipse, we will look at how the value of the cost function changes depending on the direction we move, and choose to move in the direction that most improves the cost. To begin with, let us redefine the problem in terms of two independent variables, and let the third be dependent. In the following formulation, I will choose <img src='http://s.wordpress.com/latex.php?latex=q_z&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='q_z' title='q_z' class='latex' /> to be the dependent variable, but you should note that this is not always the best choice. A good choice of dependent variable is to look at the coordinates of the target point and pick the one that is furthest from the origin (to avoid numerically ill-conditioned situations).</p>
<p>Using <img src='http://s.wordpress.com/latex.php?latex=q_z&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='q_z' title='q_z' class='latex' /> as the dependent variable we can reformulate the constraint as the following</p>
<img src='http://s.wordpress.com/latex.php?latex=q_z%20%3D%20%5Cpm%20c%20%5Csqrt%7B%201%20-%20%5Cfrac%7Bq_x%5E2%7D%7Ba%5E2%7D%20-%20%5Cfrac%7Bq_y%5E2%7D%7Bb%5E2%7D%20%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='q_z = \pm c \sqrt{ 1 - \frac{q_x^2}{a^2} - \frac{q_y^2}{b^2} }' title='q_z = \pm c \sqrt{ 1 - \frac{q_x^2}{a^2} - \frac{q_y^2}{b^2} }' class='latex' />
<p>Given this, we exam the effect that changing each of our independent variables has on our cost function, by calculating the partial derivatives. First though, we note that the minimum of a square root expression will occur at the same point as the minimum of the argument, so we will throw away the square root part and use </p>
<img src='http://s.wordpress.com/latex.php?latex=%20J%20%3D%20%28p_x-q_x%29%5E2%20%2B%20%28p_y-q_y%29%5E2%20%2B%20%20%28p_z-q_z%29%5E2%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' J = (p_x-q_x)^2 + (p_y-q_y)^2 +  (p_z-q_z)^2  ' title=' J = (p_x-q_x)^2 + (p_y-q_y)^2 +  (p_z-q_z)^2  ' class='latex' />
<p>for the derivatives instead.</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%5Cfrac%7B%20%5Cpartial%20J%20%7D%7B%20%5Cpartial%20q_x%20%7D%20%3D%20-2%28p_x%20-%20q_x%29%20%2B%20-2%28p_z%20-%20q_z%29%5Cfrac%7B%20%5Cpartial%20q_z%20%7D%7B%20%5Cpartial%20q_x%20%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' \frac{ \partial J }{ \partial q_x } = -2(p_x - q_x) + -2(p_z - q_z)\frac{ \partial q_z }{ \partial q_x }' title=' \frac{ \partial J }{ \partial q_x } = -2(p_x - q_x) + -2(p_z - q_z)\frac{ \partial q_z }{ \partial q_x }' class='latex' /><br />
<img src='http://s.wordpress.com/latex.php?latex=%20%5Cfrac%7B%20%5Cpartial%20J%20%7D%7B%20%5Cpartial%20q_y%20%7D%20%3D%20-2%28p_y%20-%20q_y%29%20%2B%20-2%28p_z%20-%20q_z%29%5Cfrac%7B%20%5Cpartial%20q_z%20%7D%7B%20%5Cpartial%20q_y%20%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' \frac{ \partial J }{ \partial q_y } = -2(p_y - q_y) + -2(p_z - q_z)\frac{ \partial q_z }{ \partial q_y }' title=' \frac{ \partial J }{ \partial q_y } = -2(p_y - q_y) + -2(p_z - q_z)\frac{ \partial q_z }{ \partial q_y }' class='latex' />
<p>And given the equation above for <img src='http://s.wordpress.com/latex.php?latex=q_z&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='q_z' title='q_z' class='latex' /> we can determine the following</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%5Cfrac%7B%20%5Cpartial%20q_z%20%7D%7B%20%5Cpartial%20q_x%20%7D%20%3D%20%5Cpm%20c%20%5Cfrac%7B1%7D%7B2%7D%20%5Csqrt%7B%201%20-%20%5Cfrac%7Bq_x%5E2%7D%7Ba%5E2%7D%20-%20%5Cfrac%7Bq_y%5E2%7D%7Bb%5E2%7D%20%7D%5E%7B-%5Cfrac%7B1%7D%7B2%7D%7D%20%5Cleft%28%20-2%20%5Cfrac%7Bq_x%7D%7Ba%5E2%7D%5Cright%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' \frac{ \partial q_z }{ \partial q_x } = \pm c \frac{1}{2} \sqrt{ 1 - \frac{q_x^2}{a^2} - \frac{q_y^2}{b^2} }^{-\frac{1}{2}} \left( -2 \frac{q_x}{a^2}\right)' title=' \frac{ \partial q_z }{ \partial q_x } = \pm c \frac{1}{2} \sqrt{ 1 - \frac{q_x^2}{a^2} - \frac{q_y^2}{b^2} }^{-\frac{1}{2}} \left( -2 \frac{q_x}{a^2}\right)' class='latex' />
<p>which simplifies to </p>
<img src='http://s.wordpress.com/latex.php?latex=%20%5Cfrac%7B%20%5Cpartial%20q_z%20%7D%7B%20%5Cpartial%20q_x%20%7D%20%3D%20%5Cmp%20%5Cfrac%7Bc%7D%7Ba%5E2%7D%20%5Cfrac%7Bq_x%7D%7Bq_z%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' \frac{ \partial q_z }{ \partial q_x } = \mp \frac{c}{a^2} \frac{q_x}{q_z}' title=' \frac{ \partial q_z }{ \partial q_x } = \mp \frac{c}{a^2} \frac{q_x}{q_z}' class='latex' />
<p>and similarly </p>
<img src='http://s.wordpress.com/latex.php?latex=%20%5Cfrac%7B%20%5Cpartial%20q_z%20%7D%7B%20%5Cpartial%20q_y%20%7D%20%3D%20%5Cmp%20%5Cfrac%7Bc%7D%7Bb%5E2%7D%20%5Cfrac%7Bq_y%7D%7Bq_z%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' \frac{ \partial q_z }{ \partial q_y } = \mp \frac{c}{b^2} \frac{q_y}{q_z}' title=' \frac{ \partial q_z }{ \partial q_y } = \mp \frac{c}{b^2} \frac{q_y}{q_z}' class='latex' />
<p>Note that the sign of these derivatives is opposite the sign of <img src='http://s.wordpress.com/latex.php?latex=q_z&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='q_z' title='q_z' class='latex' />. Therefore we see the following</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%5Cfrac%7B%20%5Cpartial%20J%20%7D%7B%20%5Cpartial%20q_x%20%7D%20%3D%20-2%28p_x%20-%20q_x%29%20%2B%202%20sign%28q_z%29%20%28p_z%20-%20q_z%29%5Cleft%28%20%5Cfrac%7Bc%7D%7Ba%5E2%7D%20%5Cfrac%7Bq_x%7D%7Bq_z%7D%20%5Cright%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' \frac{ \partial J }{ \partial q_x } = -2(p_x - q_x) + 2 sign(q_z) (p_z - q_z)\left( \frac{c}{a^2} \frac{q_x}{q_z} \right)' title=' \frac{ \partial J }{ \partial q_x } = -2(p_x - q_x) + 2 sign(q_z) (p_z - q_z)\left( \frac{c}{a^2} \frac{q_x}{q_z} \right)' class='latex' /><br />
<img src='http://s.wordpress.com/latex.php?latex=%20%5Cfrac%7B%20%5Cpartial%20J%20%7D%7B%20%5Cpartial%20q_y%20%7D%20%3D%20-2%28p_y%20-%20q_y%29%20%2B%202%20sign%28q_z%29%20%28p_z%20-%20q_z%29%5Cleft%28%20%5Cfrac%7Bc%7D%7Bb%5E2%7D%20%5Cfrac%7Bq_y%7D%7Bq_z%7D%20%5Cright%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' \frac{ \partial J }{ \partial q_y } = -2(p_y - q_y) + 2 sign(q_z) (p_z - q_z)\left( \frac{c}{b^2} \frac{q_y}{q_z} \right)' title=' \frac{ \partial J }{ \partial q_y } = -2(p_y - q_y) + 2 sign(q_z) (p_z - q_z)\left( \frac{c}{b^2} \frac{q_y}{q_z} \right)' class='latex' />
<p>where <img src='http://s.wordpress.com/latex.php?latex=sign%28x%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='sign(x)' title='sign(x)' class='latex' /> is the <i>signum</i> function and returns <img src='http://s.wordpress.com/latex.php?latex=-1&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='-1' title='-1' class='latex' /> if the argument is less than zero (<img src='http://s.wordpress.com/latex.php?latex=x%20%3C%200&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='x &lt; 0' title='x &lt; 0' class='latex' />) or <img src='http://s.wordpress.com/latex.php?latex=1&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='1' title='1' class='latex' /> if the argument is greater than zero (<img src='http://s.wordpress.com/latex.php?latex=x%20%3E%200&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='x &gt; 0' title='x &gt; 0' class='latex' />).</p>
<p>Now we solve for the minimum point using the following algorithm</p>
<ol>
<li>start at some <img src='http://s.wordpress.com/latex.php?latex=q_x&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='q_x' title='q_x' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=q_y&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='q_y' title='q_y' class='latex' /></li>
<li>calculate <img src='http://s.wordpress.com/latex.php?latex=%5Cpm%20q_z&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\pm q_z' title='\pm q_z' class='latex' /></li>
<li>pick whichever of the two is closer by picking the one with the same sign as <img src='http://s.wordpress.com/latex.php?latex=p_z&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='p_z' title='p_z' class='latex' /></li>
<li>calculate the cost <img src='http://s.wordpress.com/latex.php?latex=J&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='J' title='J' class='latex' /></li>
<li>if <img src='http://s.wordpress.com/latex.php?latex=J&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='J' title='J' class='latex' /> of the current iteration is within some tolerance of <img src='http://s.wordpress.com/latex.php?latex=J&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='J' title='J' class='latex' /> at the previous iteration, stop here</li>
<li>calcluate <img src='http://s.wordpress.com/latex.php?latex=%5Cfrac%7B%5Cpartial%20J%7D%7B%5Cpartial%20q_x%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\frac{\partial J}{\partial q_x}' title='\frac{\partial J}{\partial q_x}' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=%5Cfrac%7B%5Cpartial%20J%7D%7B%5Cpartial%20q_y%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\frac{\partial J}{\partial q_y}' title='\frac{\partial J}{\partial q_y}' class='latex' /></li>
<li>calculate <img src='http://s.wordpress.com/latex.php?latex=%5CDelta%20x&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\Delta x' title='\Delta x' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=%5CDelta%20y&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\Delta y' title='\Delta y' class='latex' /> from <img src='http://s.wordpress.com/latex.php?latex=J&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='J' title='J' class='latex' />, <img src='http://s.wordpress.com/latex.php?latex=%5Cfrac%7B%5Cpartial%20J%7D%7B%5Cpartial%20q_x%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\frac{\partial J}{\partial q_x}' title='\frac{\partial J}{\partial q_x}' class='latex' />, and <img src='http://s.wordpress.com/latex.php?latex=%5Cfrac%7B%5Cpartial%20J%7D%7B%5Cpartial%20q_y%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\frac{\partial J}{\partial q_y}' title='\frac{\partial J}{\partial q_y}' class='latex' /></li>
<li>update <img src='http://s.wordpress.com/latex.php?latex=q_x&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='q_x' title='q_x' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=q_y&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='q_y' title='q_y' class='latex' /> using <img src='http://s.wordpress.com/latex.php?latex=%5CDelta%20x&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\Delta x' title='\Delta x' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=%5CDelta%20y&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\Delta y' title='\Delta y' class='latex' /></li>
<li>return to (1)</li>
</ol>
<p>Here is a matlab code that demonstrates this algorithm. Note that in this code, for the initial guess I use the intersection of the line segment between the origin of the ellipse and <img src='http://s.wordpress.com/latex.php?latex=%5Cvec%7Bp%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\vec{p}' title='\vec{p}' class='latex' /> with the surface of the ellipse.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
</pre></td><td class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">clc</span>;
<span style="color: #0000FF;">clear</span>;
&nbsp;
<span style="color: #228B22;">% define the ellipsoid parameters</span>
a   = <span style="color: #33f;">3</span>;
b   = <span style="color: #33f;">7</span>;
c   = <span style="color: #33f;">9</span>;
&nbsp;
<span style="color: #228B22;">% createa a 100 x 100 point mesh for displaying the ellipsoid</span>
x   = <span style="color: #0000FF;">linspace</span><span style="color: #080;">&#40;</span> -a, a, <span style="color: #33f;">50</span> <span style="color: #080;">&#41;</span>;
y   = <span style="color: #0000FF;">linspace</span><span style="color: #080;">&#40;</span> -b, b, <span style="color: #33f;">50</span> <span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% calculate the z coordinates</span>
<span style="color: #080;">&#91;</span>X,Y<span style="color: #080;">&#93;</span>   = <span style="color: #0000FF;">meshgrid</span><span style="color: #080;">&#40;</span>x,y<span style="color: #080;">&#41;</span>;
Zp      = c*<span style="color: #0000FF;">sqrt</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span> - X.*X/<span style="color: #080;">&#40;</span>a*a<span style="color: #080;">&#41;</span> - Y.*Y/<span style="color: #080;">&#40;</span>b*b<span style="color: #080;">&#41;</span> <span style="color: #080;">&#41;</span>;
Zm      = -Zp;
&nbsp;
<span style="color: #228B22;">% create the point we're going to calculate the closest too</span>
px = <span style="color: #33f;">3</span>;
py = <span style="color: #33f;">4</span>;
pz = <span style="color: #33f;">8</span>;
&nbsp;
&nbsp;
<span style="color: #228B22;">% create an initial guess by finding the intersection of the ray from the</span>
<span style="color: #228B22;">% centroid to point with the ellipsoid surface</span>
k = <span style="color: #0000FF;">sqrt</span><span style="color: #080;">&#40;</span> <span style="color: #33f;">1</span> / <span style="color: #080;">&#40;</span> <span style="color: #080;">&#40;</span>px^<span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>/<span style="color: #080;">&#40;</span>a^<span style="color: #33f;">2</span><span style="color: #080;">&#41;</span> + <span style="color: #080;">&#40;</span>py^<span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>/<span style="color: #080;">&#40;</span>b^<span style="color: #33f;">2</span><span style="color: #080;">&#41;</span> + <span style="color: #080;">&#40;</span>pz^<span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>/<span style="color: #080;">&#40;</span>c^<span style="color: #33f;">2</span><span style="color: #080;">&#41;</span> <span style="color: #080;">&#41;</span> <span style="color: #080;">&#41;</span>;
&nbsp;
qx = k*px;
qy = k*py;
<span style="color: #0000FF;">qz</span> = k*pz;
&nbsp;
<span style="color: #228B22;">% this is the scale factor for our movement along the ellipse, this can</span>
<span style="color: #228B22;">% start off quite large because it will be reduced as needed</span>
s = <span style="color: #33f;">1</span>;
&nbsp;
&nbsp;
<span style="color: #228B22;">% this is the main loop, you'll want to put some kind of tolerance based</span>
<span style="color: #228B22;">% terminal condition, i.e. when the cost function (distance) is only </span>
<span style="color: #228B22;">% bouncing back and forth between a tolerance or something more tailored to</span>
<span style="color: #228B22;">% your application, I will stop when the distance is +/- 1%</span>
<span style="color: #33f;">i</span> = <span style="color: #33f;">1</span>;
<span style="color: #0000FF;">while</span> <span style="color: #33f;">1</span>
    <span style="color: #228B22;">% calculate the z for our given x and y</span>
    qz_plus     = c * <span style="color: #0000FF;">sqrt</span><span style="color: #080;">&#40;</span> <span style="color: #33f;">1</span> - qx*qx/<span style="color: #080;">&#40;</span>a*a<span style="color: #080;">&#41;</span> - qy*qy/<span style="color: #080;">&#40;</span>b*b<span style="color: #080;">&#41;</span> <span style="color: #080;">&#41;</span>;
    qz_minus    = - qz_plus;
&nbsp;
    <span style="color: #228B22;">% we want the one that get's us closest to the target so </span>
    <span style="color: #0000FF;">if</span><span style="color: #080;">&#40;</span> <span style="color: #0000FF;">abs</span><span style="color: #080;">&#40;</span>pz - qz_plus<span style="color: #080;">&#41;</span> &lt; <span style="color: #0000FF;">abs</span><span style="color: #080;">&#40;</span>pz - qz_minus<span style="color: #080;">&#41;</span> <span style="color: #080;">&#41;</span>
        <span style="color: #0000FF;">qz</span> = qz_plus;
    <span style="color: #0000FF;">else</span>
        <span style="color: #0000FF;">qz</span> = qz_minus;
    <span style="color: #0000FF;">end</span>
&nbsp;
&nbsp;
&nbsp;
    <span style="color: #228B22;">% calculate the current value of the cost function</span>
    <span style="color: #0000FF;">J</span>           = <span style="color: #0000FF;">sqrt</span><span style="color: #080;">&#40;</span> <span style="color: #080;">&#40;</span>px - qx<span style="color: #080;">&#41;</span>^<span style="color: #33f;">2</span> + <span style="color: #080;">&#40;</span>py - qy<span style="color: #080;">&#41;</span>^<span style="color: #33f;">2</span> + <span style="color: #080;">&#40;</span>pz - <span style="color: #0000FF;">qz</span><span style="color: #080;">&#41;</span>^<span style="color: #33f;">2</span> <span style="color: #080;">&#41;</span>;
&nbsp;
    <span style="color: #228B22;">% store the current values for the plots</span>
    qxplot<span style="color: #080;">&#40;</span><span style="color: #33f;">i</span><span style="color: #080;">&#41;</span>   = qx;
    qyplot<span style="color: #080;">&#40;</span><span style="color: #33f;">i</span><span style="color: #080;">&#41;</span>   = qy;
    qzplot<span style="color: #080;">&#40;</span><span style="color: #33f;">i</span><span style="color: #080;">&#41;</span>   = <span style="color: #0000FF;">qz</span>;
    Jplot<span style="color: #080;">&#40;</span><span style="color: #33f;">i</span><span style="color: #080;">&#41;</span>    = <span style="color: #0000FF;">J</span>;
&nbsp;
    <span style="color: #228B22;">% check to see if we overshot the goal or jumped off the ellipsoid</span>
    <span style="color: #0000FF;">if</span><span style="color: #080;">&#40;</span> <span style="color: #33f;">i</span> &gt; <span style="color: #33f;">1</span> <span style="color: #080;">&#41;</span>
        <span style="color: #228B22;">% if we jumped off the ellipsoid or overshot the minimal cost</span>
        <span style="color: #0000FF;">if</span><span style="color: #080;">&#40;</span> <span style="color: #0000FF;">imag</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">qz</span><span style="color: #080;">&#41;</span> ~= <span style="color: #33f;">0</span> || <span style="color: #0000FF;">J</span> &gt; Jplot<span style="color: #080;">&#40;</span><span style="color: #33f;">i</span>-<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> <span style="color: #080;">&#41;</span>;
            <span style="color: #228B22;">% then go back to the previous position and use a finer </span>
            <span style="color: #228B22;">% step size</span>
            qx = qxplot<span style="color: #080;">&#40;</span><span style="color: #33f;">i</span>-<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
            qy = qyplot<span style="color: #080;">&#40;</span><span style="color: #33f;">i</span>-<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
            <span style="color: #0000FF;">qz</span> = qzplot<span style="color: #080;">&#40;</span><span style="color: #33f;">i</span>-<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
            <span style="color: #0000FF;">J</span>  = Jplot<span style="color: #080;">&#40;</span><span style="color: #33f;">i</span>-<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
            s = s/<span style="color: #33f;">10</span>;
            <span style="color: #33f;">i</span> = <span style="color: #33f;">i</span>-<span style="color: #33f;">1</span>;
&nbsp;
            <span style="color: #228B22;">% if we did just jump over the actual minimum, let's check to </span>
            <span style="color: #228B22;">% see how confident we are at this point, if we're with in </span>
            <span style="color: #228B22;">% 1% there's no need to continue</span>
            <span style="color: #0000FF;">if</span><span style="color: #080;">&#40;</span> <span style="color: #33f;">i</span> &gt; <span style="color: #33f;">3</span> <span style="color: #080;">&#41;</span>
                <span style="color: #0000FF;">if</span><span style="color: #080;">&#40;</span> <span style="color: #0000FF;">abs</span><span style="color: #080;">&#40;</span> <span style="color: #080;">&#40;</span>Jplot<span style="color: #080;">&#40;</span><span style="color: #33f;">i</span>-<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span> - Jplot<span style="color: #080;">&#40;</span><span style="color: #33f;">i</span>-<span style="color: #33f;">3</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> / Jplot<span style="color: #080;">&#40;</span><span style="color: #33f;">i</span>-<span style="color: #33f;">3</span><span style="color: #080;">&#41;</span> <span style="color: #080;">&#41;</span> &lt; <span style="color: #33f;">0.001</span> <span style="color: #080;">&#41;</span>
                    <span style="color: #0000FF;">break</span>;
                <span style="color: #0000FF;">end</span>
            <span style="color: #0000FF;">end</span>
        <span style="color: #0000FF;">end</span>
    <span style="color: #0000FF;">end</span>
&nbsp;
    <span style="color: #228B22;">% calculate the gradient of the cost with respect to our control</span>
    <span style="color: #228B22;">% variables; since we divide by qz in the second term we first need</span>
    <span style="color: #228B22;">% to check whether or not qz is too close to zero; if it is, we know</span>
    <span style="color: #228B22;">% that the second term should be zero</span>
    <span style="color: #0000FF;">if</span><span style="color: #080;">&#40;</span> <span style="color: #0000FF;">qz</span> &lt; 1e-10 <span style="color: #080;">&#41;</span>
        dJdx = -<span style="color: #33f;">2</span>*<span style="color: #080;">&#40;</span>px - qx<span style="color: #080;">&#41;</span>;
        dJdy = -<span style="color: #33f;">2</span>*<span style="color: #080;">&#40;</span>py - qy<span style="color: #080;">&#41;</span>;
    <span style="color: #0000FF;">else</span>
        dJdx    = -<span style="color: #33f;">2</span>*<span style="color: #080;">&#40;</span>px - qx<span style="color: #080;">&#41;</span> + <span style="color: #33f;">2</span>*<span style="color: #0000FF;">sign</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">qz</span><span style="color: #080;">&#41;</span>*<span style="color: #080;">&#40;</span>pz - <span style="color: #0000FF;">qz</span><span style="color: #080;">&#41;</span>*<span style="color: #080;">&#40;</span> c/<span style="color: #080;">&#40;</span>a*a<span style="color: #080;">&#41;</span> * qx/<span style="color: #0000FF;">qz</span> <span style="color: #080;">&#41;</span>;
        dJdy    = -<span style="color: #33f;">2</span>*<span style="color: #080;">&#40;</span>py - qy<span style="color: #080;">&#41;</span> + <span style="color: #33f;">2</span>*<span style="color: #0000FF;">sign</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">qz</span><span style="color: #080;">&#41;</span>*<span style="color: #080;">&#40;</span>pz - <span style="color: #0000FF;">qz</span><span style="color: #080;">&#41;</span>*<span style="color: #080;">&#40;</span> c/<span style="color: #080;">&#40;</span>b*b<span style="color: #080;">&#41;</span> * qy/<span style="color: #0000FF;">qz</span> <span style="color: #080;">&#41;</span>;
    <span style="color: #0000FF;">end</span>
&nbsp;
    <span style="color: #228B22;">% calculate the update vector that we will move along</span>
    dx          = -<span style="color: #0000FF;">J</span>/dJdx;
    dy          = -<span style="color: #0000FF;">J</span>/dJdy;
&nbsp;
    <span style="color: #228B22;">% calculate the magnitude of that update vector</span>
    magnitude   = <span style="color: #0000FF;">sqrt</span><span style="color: #080;">&#40;</span> dx*dx + dy*dy <span style="color: #080;">&#41;</span>;
&nbsp;
    <span style="color: #228B22;">% normalize our update vector so that we don't shoot off at an</span>
    <span style="color: #228B22;">% uncontrolable rate</span>
    dx          = s * <span style="color: #080;">&#40;</span><span style="color: #33f;">1</span>/magnitude<span style="color: #080;">&#41;</span> *dx;
    dy          = s * <span style="color: #080;">&#40;</span><span style="color: #33f;">1</span>/magnitude<span style="color: #080;">&#41;</span> *dy;
&nbsp;
    <span style="color: #228B22;">% update the current position </span>
    qx          = qx + dx;
    qy          = qy + dy;
&nbsp;
    <span style="color: #228B22;">% increment the index </span>
    <span style="color: #33f;">i</span> = <span style="color: #33f;">i</span>+<span style="color: #33f;">1</span>;
<span style="color: #0000FF;">end</span>;
&nbsp;
index = <span style="color: #33f;">1</span>:<span style="color: #33f;">i</span>+<span style="color: #33f;">1</span>;
&nbsp;
<span style="color: #228B22;">% generate a little report </span>
message = <span style="color: #0000FF;">sprintf</span><span style="color: #080;">&#40;</span> <span style="color: #080;">...</span>
    <span style="color: #080;">&#91;</span><span style="color:#A020F0;">'The closest point was found at [%f, %f, %f]'</span>, <span style="color: #080;">...</span>
     <span style="color:#A020F0;">'with a distance of %f and a confidence of +/- %f %%'</span><span style="color: #080;">&#93;</span>, <span style="color: #080;">...</span>
    <span style="">qx</span>, qy, <span style="color: #0000FF;">qz</span>, <span style="color: #0000FF;">J</span>, <span style="color: #33f;">100</span>*<span style="color: #0000FF;">abs</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#40;</span>Jplot<span style="color: #080;">&#40;</span><span style="color: #33f;">i</span>+<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>-Jplot<span style="color: #080;">&#40;</span><span style="color: #33f;">i</span>-<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> / Jplot<span style="color: #080;">&#40;</span><span style="color: #33f;">i</span>-<span style="color: #33f;">1</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span> <span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>message<span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% now we'll verify that the one we found is the closest</span>
Jmap_plus   = <span style="color: #0000FF;">sqrt</span><span style="color: #080;">&#40;</span> <span style="color: #080;">&#40;</span>px - X<span style="color: #080;">&#41;</span>.*<span style="color: #080;">&#40;</span>px - X<span style="color: #080;">&#41;</span> + <span style="color: #080;">&#40;</span>py - Y<span style="color: #080;">&#41;</span>.*<span style="color: #080;">&#40;</span>py - Y<span style="color: #080;">&#41;</span> + <span style="color: #080;">&#40;</span>pz - Zp<span style="color: #080;">&#41;</span>.*<span style="color: #080;">&#40;</span>pz - Zp <span style="color: #080;">&#41;</span> <span style="color: #080;">&#41;</span>;
Jmap_minus  = <span style="color: #0000FF;">sqrt</span><span style="color: #080;">&#40;</span> <span style="color: #080;">&#40;</span>px - X<span style="color: #080;">&#41;</span>.*<span style="color: #080;">&#40;</span>px - X<span style="color: #080;">&#41;</span> + <span style="color: #080;">&#40;</span>py - Y<span style="color: #080;">&#41;</span>.*<span style="color: #080;">&#40;</span>py - Y<span style="color: #080;">&#41;</span> + <span style="color: #080;">&#40;</span>pz - Zp<span style="color: #080;">&#41;</span>.*<span style="color: #080;">&#40;</span>pz - Zm <span style="color: #080;">&#41;</span> <span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #080;">&#91;</span>Jmin_plus_row, imin_plus_row<span style="color: #080;">&#93;</span> = <span style="color: #0000FF;">min</span><span style="color: #080;">&#40;</span> Jmap_plus <span style="color: #080;">&#41;</span>;
<span style="color: #080;">&#91;</span>Jmin_plus_col, imin_plus_col<span style="color: #080;">&#93;</span> = <span style="color: #0000FF;">min</span><span style="color: #080;">&#40;</span> Jmin_plus_row <span style="color: #080;">&#41;</span>;
&nbsp;
imin = imin_plus_row<span style="color: #080;">&#40;</span>imin_plus_col<span style="color: #080;">&#41;</span>;
jmin = imin_plus_col;
&nbsp;
xmin    = X<span style="color: #080;">&#40;</span>imin, jmin<span style="color: #080;">&#41;</span>;
ymin    = Y<span style="color: #080;">&#40;</span>imin, jmin<span style="color: #080;">&#41;</span>;
zmin    = Zp<span style="color: #080;">&#40;</span>imin, jmin<span style="color: #080;">&#41;</span>;
Jmin    = Jmin_plus_col;
Jmin2   = Jmap_plus<span style="color: #080;">&#40;</span>imin,jmin<span style="color: #080;">&#41;</span>;
&nbsp;
message = <span style="color: #0000FF;">sprintf</span><span style="color: #080;">&#40;</span> <span style="color: #080;">...</span> 
    <span style="color: #080;">&#91;</span><span style="color:#A020F0;">'The closest point by searching the mesh was at [%f, %f, %f]'</span> <span style="color: #080;">...</span>
     <span style="color:#A020F0;">'and has a distance of %f (%f)'</span><span style="color: #080;">&#93;</span>, xmin, ymin, zmin, Jmin, Jmin2 <span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>message<span style="color: #080;">&#41;</span>;
&nbsp;
&nbsp;
<span style="color: #228B22;">% and draw some pretty pictures</span>
&nbsp;
<span style="color: #0000FF;">close</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">figure</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">figure</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">grid</span> on;
<span style="color: #0000FF;">hold</span> on;
<span style="color: #0000FF;">mesh</span><span style="color: #080;">&#40;</span>X,Y,<span style="color: #0000FF;">real</span><span style="color: #080;">&#40;</span>Zp<span style="color: #080;">&#41;</span>, <span style="color:#A020F0;">'FaceAlpha'</span>, <span style="color: #33f;">0.5</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">mesh</span><span style="color: #080;">&#40;</span>X,Y,<span style="color: #0000FF;">real</span><span style="color: #080;">&#40;</span>Zm<span style="color: #080;">&#41;</span>, <span style="color:#A020F0;">'FaceAlpha'</span>, <span style="color: #33f;">0.5</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">plot3</span><span style="color: #080;">&#40;</span>px,py,pz,<span style="color:#A020F0;">'ko'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">plot3</span><span style="color: #080;">&#40;</span>qxplot,qyplot,qzplot,<span style="color:#A020F0;">'ko'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">plot3</span><span style="color: #080;">&#40;</span>qxplot,qyplot,qzplot,<span style="color:#A020F0;">'k-'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">plot3</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#91;</span>px qx<span style="color: #080;">&#93;</span>, <span style="color: #080;">&#91;</span>py qy<span style="color: #080;">&#93;</span>, <span style="color: #080;">&#91;</span>pz <span style="color: #0000FF;">qz</span><span style="color: #080;">&#93;</span>, <span style="color:#A020F0;">'b-'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">xlabel</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'X'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">ylabel</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Y'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">zlabel</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Z'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">title</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'steepest decent method'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">hold</span> off;
&nbsp;
<span style="color: #0000FF;">close</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">figure</span><span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">figure</span><span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">plot</span><span style="color: #080;">&#40;</span>index, Jplot, <span style="color:#A020F0;">'g-'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">xlabel</span><span style="color: #080;">&#40;</span> <span style="color:#A020F0;">'iteration'</span> <span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">ylabel</span><span style="color: #080;">&#40;</span> <span style="color:#A020F0;">'distance (cost)'</span> <span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">close</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">figure</span><span style="color: #080;">&#40;</span><span style="color: #33f;">3</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">figure</span><span style="color: #080;">&#40;</span><span style="color: #33f;">3</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">mesh</span><span style="color: #080;">&#40;</span>X,Y,<span style="color: #0000FF;">real</span><span style="color: #080;">&#40;</span>Jmap_plus<span style="color: #080;">&#41;</span>, <span style="color:#A020F0;">'FaceAlpha'</span>, <span style="color: #33f;">0.5</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">xlabel</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'X'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">ylabel</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Y'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">zlabel</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'Z'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">title</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'distance to target'</span><span style="color: #080;">&#41;</span>;</pre></td></tr></table></div>

<p>The output of this script is</p>
<p><code><br />
The closest point was found at [1.321810, 3.187960, 6.962411]with a distance of 2.133617 and a confidence of +/- 0.000000 %<br />
The closest point by searching the mesh was at [1.285714, 3.285714, 6.948103]and has a distance of 2.134354 (2.134354)<br />
</code></p>
<p>You can see the work done by the gradient search in the first figure, which is shown below:</p>
<div id="attachment_140" class="wp-caption aligncenter" style="width: 310px"><a href="http://cheshirekow.com/blog/?attachment_id=140" rel="attachment wp-att-140"><img src="http://cheshirekow.com/blog/wp-content/uploads/2009/09/ellipse_steepest_goodguess-300x196.png" alt="Result of Steepest Descent Algorithm" title="ellipse_steepest_goodguess" width="300" height="196" class="size-medium wp-image-140" /></a><p class="wp-caption-text">Result of Steepest Descent Algorithm</p></div>
<p><a href="http://cheshirekow.com/blog/wp-content/uploads/2009/09/ellipse_steepest_goodguess.png">Full Size</a></p>
<div id="attachment_149" class="wp-caption aligncenter" style="width: 310px"><a href="http://cheshirekow.com/blog/?attachment_id=149" rel="attachment wp-att-149"><img src="http://cheshirekow.com/blog/wp-content/uploads/2009/09/ellipse_steepest_goodguess_detail-300x212.png" alt="Detail of Steepest Descent" title="ellipse_steepest_goodguess_detail" width="300" height="212" class="size-medium wp-image-149" /></a><p class="wp-caption-text">Detail of Steepest Descent</p></div>
<p><a href="http://cheshirekow.com/blog/wp-content/uploads/2009/09/ellipse_steepest_goodguess_detail.png">Full Size</a></p>
<p>I know this doesn&#8217;t<i>look</i> like the closest point, but, as you can see, the script actually searches the mesh for the lowest value point and comes up with essentially the same point. To demonstrate, here is a 3d plot of the distance of each point on the upper half of the ellipse to the target point, with the minimum point labeled. This is the output of the script to figure 3. The reason it doesn&#8217;t look right is because of how matlab squashes everything to fit the window.</p>
<div id="attachment_142" class="wp-caption aligncenter" style="width: 310px"><a href="http://cheshirekow.com/blog/?attachment_id=142" rel="attachment wp-att-142"><img src="http://cheshirekow.com/blog/wp-content/uploads/2009/09/ellipse_distance_mesh-300x223.png" alt="Distance of Point on Ellipse to Target Point" title="ellipse_distance_mesh" width="300" height="223" class="size-medium wp-image-142" /></a><p class="wp-caption-text">Distance of Point on Ellipse to Target Point</p></div>
<p><a href="http://cheshirekow.com/blog/wp-content/uploads/2009/09/ellipse_distance_mesh.png">Full Size</a></p>
<p>And finally here is a plot of the distance calculated at each iteration of the loop. As you can see, it doesn&#8217;t take many to find a value that is pretty damn good.</p>
<p><a href="http://cheshirekow.com/blog/?attachment_id=141" rel="attachment wp-att-141"><img src="http://cheshirekow.com/blog/wp-content/uploads/2009/09/ellipse_steepest_distance-300x283.png" alt="ellipse_steepest_distance" title="ellipse_steepest_distance" width="300" height="283" class="aligncenter size-medium wp-image-141" /></a></p>
<p><a href="http://cheshirekow.com/blog/wp-content/uploads/2009/09/ellipse_steepest_distance.png">Full Size</a></p>
<p>Steepest decent works pretty well right? Well, not always. The initial guess used in the code above will save your ass, but steepest descent can suffer from problems of local minima. Look what happens when I try an initial guess on the other side of the ellipsoid. </p>
<div id="attachment_152" class="wp-caption aligncenter" style="width: 310px"><a href="http://cheshirekow.com/blog/?attachment_id=152" rel="attachment wp-att-152"><img src="http://cheshirekow.com/blog/wp-content/uploads/2009/09/ellipse_steepest_fail-300x170.png" alt="Failure of Steepest Descent Algorithm" title="ellipse_steepest_fail" width="300" height="170" class="size-medium wp-image-152" /></a><p class="wp-caption-text">Failure of Steepest Descent Algorithm</p></div>
<p><a href="http://cheshirekow.com/blog/wp-content/uploads/2009/09/ellipse_steepest_fail.png">Full Size</a></p>
<p>The algorithm get&#8217;s caught in a local minimum, and converges to a very precise, very incorrect solution. </p>
<h1>LeGrange Method</h1>
<p>This method is a little more elegant, but still ends up with a search algorithm. However, in this case we&#8217;re only doing a one dimensional search for root-finding of a polynomial, which is a quite well documented problem.</p>
<p>In this method, we note that, since the constraint must be satisfied everywhere, if we know the minimal cost <img src='http://s.wordpress.com/latex.php?latex=J%5E%2A&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='J^*' title='J^*' class='latex' /> is achieved at a point <img src='http://s.wordpress.com/latex.php?latex=%5Cvec%7Bq%7D%5E%2A&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\vec{q}^*' title='\vec{q}^*' class='latex' />, then we know that</p>
<img src='http://s.wordpress.com/latex.php?latex=%20J%5E%2A%20%3D%20%5Csqrt%7B%20%28p_x-q%5E%2A_x%29%5E2%20%2B%20%28p_y-q%5E%2A_y%29%5E2%20%2B%20%20%28p_z-q%5E%2A_z%29%5E2%20%7D%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' J^* = \sqrt{ (p_x-q^*_x)^2 + (p_y-q^*_y)^2 +  (p_z-q^*_z)^2 } ' title=' J^* = \sqrt{ (p_x-q^*_x)^2 + (p_y-q^*_y)^2 +  (p_z-q^*_z)^2 } ' class='latex' />
<p>and we also know that if the <i>augmented cost function</i> is defined as</p>
<img src='http://s.wordpress.com/latex.php?latex=%20L%20%3D%20J%28%5Cvec%7Bq%7D%29%20%2B%20%5Clambda%20f%28%5Cvec%7Bq%7D%29%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' L = J(\vec{q}) + \lambda f(\vec{q}) ' title=' L = J(\vec{q}) + \lambda f(\vec{q}) ' class='latex' />
<p>which expands to </p>
<img src='http://s.wordpress.com/latex.php?latex=%20L%20%3D%20%5Csqrt%7B%20%28p_x-q_x%29%5E2%20%2B%20%28p_y-q_y%29%5E2%20%2B%20%20%28p_z-q_z%29%5E2%20%7D%20%20%2B%20%20%5Clambda%20%5Cleft%5B%20%5Cfrac%7Bq_x%5E2%7D%7Ba%5E2%7D%20%2B%20%5Cfrac%7Bq_y%5E2%7D%7Bb%5E2%7D%20%2B%20%5Cfrac%7Bq_z%5E2%7D%7Bc%5E2%7D%20-%201%20%5Cright%5D%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' L = \sqrt{ (p_x-q_x)^2 + (p_y-q_y)^2 +  (p_z-q_z)^2 }  +  \lambda \left[ \frac{q_x^2}{a^2} + \frac{q_y^2}{b^2} + \frac{q_z^2}{c^2} - 1 \right] ' title=' L = \sqrt{ (p_x-q_x)^2 + (p_y-q_y)^2 +  (p_z-q_z)^2 }  +  \lambda \left[ \frac{q_x^2}{a^2} + \frac{q_y^2}{b^2} + \frac{q_z^2}{c^2} - 1 \right] ' class='latex' />
<p>then <img src='http://s.wordpress.com/latex.php?latex=L%5E%2A%20%3D%20J%5E%2A&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='L^* = J^*' title='L^* = J^*' class='latex' /> and is also at <img src='http://s.wordpress.com/latex.php?latex=%5Cvec%7Bq%7D%5E%2A&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\vec{q}^*' title='\vec{q}^*' class='latex' /> since the latter term must be zero if the constraint is to be satisfied. We can then minimize the cost function as we usually do, by taking the derivative with respect to the independent variables, setting them to zero, and solving the system for the unknowns.</p>
<p>First though, we note that the minimum of a square root expression will occur at the same point as the minimum of the argument, so we will throw away the square root part and solve instead for the minimum of </p>
<img src='http://s.wordpress.com/latex.php?latex=%20L%20%3D%20%28p_x-q_x%29%5E2%20%2B%20%28p_y-q_y%29%5E2%20%2B%20%20%28p_z-q_z%29%5E2%20%20%2B%20%20%5Clambda%20%20%5Cleft%5B%20%5Cfrac%7Bq_x%5E2%7D%7Ba%7D%20%2B%20%5Cfrac%7Bq_y%5E2%7D%7Bb%7D%20%2B%20%20%5Cfrac%7Bq_z%5E2%7D%7Bc%7D%20-%201%20%5Cright%5D%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' L = (p_x-q_x)^2 + (p_y-q_y)^2 +  (p_z-q_z)^2  +  \lambda  \left[ \frac{q_x^2}{a} + \frac{q_y^2}{b} +  \frac{q_z^2}{c} - 1 \right] ' title=' L = (p_x-q_x)^2 + (p_y-q_y)^2 +  (p_z-q_z)^2  +  \lambda  \left[ \frac{q_x^2}{a} + \frac{q_y^2}{b} +  \frac{q_z^2}{c} - 1 \right] ' class='latex' />
<p>We take the partial derivative of the augmented cost with respect to<br />
the four unknowns and see that</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%5Cfrac%7B%5Cpartial%7BL%7D%7D%7B%5Cpartial%7Bq_x%7D%7D%20%3D%20-2%28p_x%20-%20q_x%29%20%2B%20%5Cfrac%7B2%20%5Clambda%20q_x%7D%7Ba%5E2%7D%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' \frac{\partial{L}}{\partial{q_x}} = -2(p_x - q_x) + \frac{2 \lambda q_x}{a^2} ' title=' \frac{\partial{L}}{\partial{q_x}} = -2(p_x - q_x) + \frac{2 \lambda q_x}{a^2} ' class='latex' /><br />
.<br />
<img src='http://s.wordpress.com/latex.php?latex=%20%5Cfrac%7B%5Cpartial%7BL%7D%7D%7B%5Cpartial%7Bq_y%7D%7D%20%3D%20-2%28p_y%20-%20q_y%29%20%2B%20%5Cfrac%7B2%20%5Clambda%20q_y%7D%7Bb%5E2%7D%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' \frac{\partial{L}}{\partial{q_y}} = -2(p_y - q_y) + \frac{2 \lambda q_y}{b^2} ' title=' \frac{\partial{L}}{\partial{q_y}} = -2(p_y - q_y) + \frac{2 \lambda q_y}{b^2} ' class='latex' /><br />
.<br />
<img src='http://s.wordpress.com/latex.php?latex=%20%5Cfrac%7B%5Cpartial%7BL%7D%7D%7B%5Cpartial%7Bq_z%7D%7D%20%3D%20-2%28p_z%20-%20q_z%29%20%2B%20%5Cfrac%7B2%20%5Clambda%20q_z%7D%7Bc%5E2%7D%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' \frac{\partial{L}}{\partial{q_z}} = -2(p_z - q_z) + \frac{2 \lambda q_z}{c^2} ' title=' \frac{\partial{L}}{\partial{q_z}} = -2(p_z - q_z) + \frac{2 \lambda q_z}{c^2} ' class='latex' /><br />
.<br />
<img src='http://s.wordpress.com/latex.php?latex=%20%5Cfrac%7B%5Cpartial%7BL%7D%7D%7B%5Cpartial%7B%5Clambda%7D%7D%20%3D%20%5Cfrac%7Bq_x%5E2%7D%7Ba%5E2%7D%20%2B%20%5Cfrac%7Bq_y%5E2%7D%7Bb%5E2%7D%20%2B%20%5Cfrac%7Bq_z%5E2%7D%7Bc%5E2%7D%20-%201%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' \frac{\partial{L}}{\partial{\lambda}} = \frac{q_x^2}{a^2} + \frac{q_y^2}{b^2} + \frac{q_z^2}{c^2} - 1 ' title=' \frac{\partial{L}}{\partial{\lambda}} = \frac{q_x^2}{a^2} + \frac{q_y^2}{b^2} + \frac{q_z^2}{c^2} - 1 ' class='latex' />
<p>Setting these all to zero we can solve for the following</p>
<img src='http://s.wordpress.com/latex.php?latex=%20q_x%20%3D%20%5Cfrac%7Bp_x%7D%7B%5Clambda%20%2B%20%5Cfrac%7B1%7D%7Ba%5E2%7D%7D%20%3D%20%5Cfrac%7Ba%5E2%20p_x%7D%7B%5Clambda%20%2B%201%7D%20%3D%200%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' q_x = \frac{p_x}{\lambda + \frac{1}{a^2}} = \frac{a^2 p_x}{\lambda + 1} = 0 ' title=' q_x = \frac{p_x}{\lambda + \frac{1}{a^2}} = \frac{a^2 p_x}{\lambda + 1} = 0 ' class='latex' /><br />
.<br />
<img src='http://s.wordpress.com/latex.php?latex=%20q_y%20%3D%20%5Cfrac%7Bp_y%7D%7B%5Clambda%20%2B%20%5Cfrac%7B1%7D%7Bb%5E2%7D%7D%20%3D%20%5Cfrac%7Bb%5E2%20p_y%7D%7B%5Clambda%20%2B%201%7D%20%3D%200%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' q_y = \frac{p_y}{\lambda + \frac{1}{b^2}} = \frac{b^2 p_y}{\lambda + 1} = 0 ' title=' q_y = \frac{p_y}{\lambda + \frac{1}{b^2}} = \frac{b^2 p_y}{\lambda + 1} = 0 ' class='latex' /><br />
.<br />
<img src='http://s.wordpress.com/latex.php?latex=%20q_z%20%3D%20%5Cfrac%7Bp_z%7D%7B%5Clambda%20%2B%20%5Cfrac%7B1%7D%7Bc%5E2%7D%7D%20%3D%20%5Cfrac%7Bc%5E2%20p_z%7D%7B%5Clambda%20%2B%201%7D%20%3D%200%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' q_z = \frac{p_z}{\lambda + \frac{1}{c^2}} = \frac{c^2 p_z}{\lambda + 1} = 0 ' title=' q_z = \frac{p_z}{\lambda + \frac{1}{c^2}} = \frac{c^2 p_z}{\lambda + 1} = 0 ' class='latex' />
<p>Substituting back into the fourth of the differentials we get that</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%5Cfrac%7B%5Cpartial%7BL%7D%7D%7B%5Cpartial%7B%5Clambda%7D%7D%20%3D%20%5Cfrac%7Ba%5E2%20p_x%5E2%7D%7B%5Cleft%28%5Clambda%20%2B%20a%5E2%5Cright%29%5E2%7D%20%2B%20%5Cfrac%7Bb%5E2%20p_y%5E2%7D%7B%5Cleft%28%5Clambda%20%2B%20b%5E2%5Cright%29%5E2%7D%20%2B%20%5Cfrac%7Bc%5E2%20p_z%5E2%7D%7B%5Cleft%28%5Clambda%20%2B%20c%5E2%5Cright%29%5E2%7D%20-%201%20%3D%200%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' \frac{\partial{L}}{\partial{\lambda}} = \frac{a^2 p_x^2}{\left(\lambda + a^2\right)^2} + \frac{b^2 p_y^2}{\left(\lambda + b^2\right)^2} + \frac{c^2 p_z^2}{\left(\lambda + c^2\right)^2} - 1 = 0 ' title=' \frac{\partial{L}}{\partial{\lambda}} = \frac{a^2 p_x^2}{\left(\lambda + a^2\right)^2} + \frac{b^2 p_y^2}{\left(\lambda + b^2\right)^2} + \frac{c^2 p_z^2}{\left(\lambda + c^2\right)^2} - 1 = 0 ' class='latex' />
<p>which simplifies to </p>
<img src='http://s.wordpress.com/latex.php?latex=%20%5Cfrac%7B%5Cpartial%7BL%7D%7D%7B%5Cpartial%7B%5Clambda%7D%7D%20%3D%20%5Cbegin%7Bmatrix%7D%20a%5E2%20p_x%5E2%20%5Cleft%28%20%5Clambda%20%2B%20b%5E2%20%5Cright%29%5E2%20%5Cleft%28%20%5Clambda%20%2B%20c%5E2%20%5Cright%29%5E2%20%2B%20%5C%5C%20b%5E2%20p_y%5E2%20%5Cleft%28%20%5Clambda%20%2B%20a%5E2%20%5Cright%29%5E2%20%5Cleft%28%20%5Clambda%20%2B%20c%5E2%5Cright%29%5E2%20%2B%20%5C%5C%20c%5E2%20p_z%5E2%20%5Cleft%28%20%5Clambda%20%2B%20a%5E2%20%5Cright%29%5E2%20%5Cleft%28%20%5Clambda%20%2B%20b%5E2%20%5Cright%29%5E2%20-%20%5C%5C%20%5Cleft%28%20%5Clambda%20%2B%20a%5E2%20%5Cright%29%5E2%20%5Cleft%28%20%5Clambda%20%2B%20b%5E2%20%5Cright%29%5E2%20%5Cleft%28%20%5Clambda%20%2B%20c%5E2%20%5Cright%29%5E2%20%20%3D%200%20%5Cend%7Bmatrix%7D%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' \frac{\partial{L}}{\partial{\lambda}} = \begin{matrix} a^2 p_x^2 \left( \lambda + b^2 \right)^2 \left( \lambda + c^2 \right)^2 + \\ b^2 p_y^2 \left( \lambda + a^2 \right)^2 \left( \lambda + c^2\right)^2 + \\ c^2 p_z^2 \left( \lambda + a^2 \right)^2 \left( \lambda + b^2 \right)^2 - \\ \left( \lambda + a^2 \right)^2 \left( \lambda + b^2 \right)^2 \left( \lambda + c^2 \right)^2  = 0 \end{matrix} ' title=' \frac{\partial{L}}{\partial{\lambda}} = \begin{matrix} a^2 p_x^2 \left( \lambda + b^2 \right)^2 \left( \lambda + c^2 \right)^2 + \\ b^2 p_y^2 \left( \lambda + a^2 \right)^2 \left( \lambda + c^2\right)^2 + \\ c^2 p_z^2 \left( \lambda + a^2 \right)^2 \left( \lambda + b^2 \right)^2 - \\ \left( \lambda + a^2 \right)^2 \left( \lambda + b^2 \right)^2 \left( \lambda + c^2 \right)^2  = 0 \end{matrix} ' class='latex' />
<p>Note that this is a sixth order polynomial in <img src='http://s.wordpress.com/latex.php?latex=%5Clambda&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\lambda' title='\lambda' class='latex' />. Use your favorite zero-finding algorithm (same as a root finding algorithm) to solve for the zeros of this polynomial, (of which there should only be two as there can only be one closest point, and one furthest point on an ellipsoid unless the target point is along one of the axes), and you will find the minimum and the maximum of your cost function. Once the solutions of <img src='http://s.wordpress.com/latex.php?latex=%5Clambda&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\lambda' title='\lambda' class='latex' /> are known, plug them into the equations above to solve for <img src='http://s.wordpress.com/latex.php?latex=q_x&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='q_x' title='q_x' class='latex' />, <img src='http://s.wordpress.com/latex.php?latex=q_y&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='q_y' title='q_y' class='latex' />, and <img src='http://s.wordpress.com/latex.php?latex=q_z&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='q_z' title='q_z' class='latex' />. Then plug those into the cost function, and pick the smaller of the two. </p>
<p>For the example problem used in the steepest descent code above, the polynomial looks like this:</p>
<div id="attachment_163" class="wp-caption aligncenter" style="width: 310px"><a href="http://cheshirekow.com/blog/?attachment_id=163" rel="attachment wp-att-163"><img src="http://cheshirekow.com/blog/wp-content/uploads/2009/09/ellipse_poly-300x225.png" alt="Polynomial For Legrange Multiplier" title="ellipse_poly" width="300" height="225" class="size-medium wp-image-163" /></a><p class="wp-caption-text">Polynomial For Legrange Multiplier</p></div>
<p><a href="http://cheshirekow.com/blog/wp-content/uploads/2009/09/ellipse_poly.png">Full Size</a></p>
<p>Here is a detail view:</p>
<div id="attachment_164" class="wp-caption aligncenter" style="width: 310px"><a href="http://cheshirekow.com/blog/?attachment_id=164" rel="attachment wp-att-164"><img src="http://cheshirekow.com/blog/wp-content/uploads/2009/09/ellipse_poly_detail-300x225.png" alt="Polynomial for LeGrange Multiplier Detail" title="ellipse_poly_detail" width="300" height="225" class="size-medium wp-image-164" /></a><p class="wp-caption-text">Polynomial for LeGrange Multiplier Detail</p></div>
<p><a href="http://cheshirekow.com/blog/wp-content/uploads/2009/09/ellipse_poly_detail.png">Full Size</a></p>
<p>As you can see, there are two solutions. Below is a matlab code that generates the above graphs, and solves for the minimum point using a binary search. Note that the search assumes that one of the values of lambda that makes the polynomial zero is to the left of the origin, and the other is to the right. That is true for this example buy may not be in general (I didn&#8217;t take the time to work out why that may be the case ) so you may have to modify the search to look for both roots on both sides of the origin.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
</pre></td><td class="code"><pre class="matlab" style="font-family:monospace;"><span style="color: #0000FF;">clc</span>;
<span style="color: #0000FF;">clear</span>;
&nbsp;
<span style="color: #228B22;">% define the ellipsoid parameters</span>
a   = <span style="color: #33f;">3</span>;
b   = <span style="color: #33f;">7</span>;
c   = <span style="color: #33f;">9</span>;
&nbsp;
<span style="color: #228B22;">% createa a 100 x 100 point mesh for displaying the ellipsoid</span>
x   = <span style="color: #0000FF;">linspace</span><span style="color: #080;">&#40;</span> -a, a, <span style="color: #33f;">50</span> <span style="color: #080;">&#41;</span>;
y   = <span style="color: #0000FF;">linspace</span><span style="color: #080;">&#40;</span> -b, b, <span style="color: #33f;">50</span> <span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% calculate the z coordinates</span>
<span style="color: #080;">&#91;</span>X,Y<span style="color: #080;">&#93;</span>   = <span style="color: #0000FF;">meshgrid</span><span style="color: #080;">&#40;</span>x,y<span style="color: #080;">&#41;</span>;
Zp      = c*<span style="color: #0000FF;">sqrt</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span> - X.*X/<span style="color: #080;">&#40;</span>a*a<span style="color: #080;">&#41;</span> - Y.*Y/<span style="color: #080;">&#40;</span>b*b<span style="color: #080;">&#41;</span> <span style="color: #080;">&#41;</span>;
Zm      = -Zp;
&nbsp;
<span style="color: #228B22;">% create the point we're going to calculate the closest too</span>
px = <span style="color: #33f;">3</span>;
py = <span style="color: #33f;">4</span>;
pz = <span style="color: #33f;">8</span>;
&nbsp;
lambda = -<span style="color: #33f;">160</span>:<span style="color: #33f;">0.01</span>:<span style="color: #33f;">20</span>;
a2 = a*a;
b2 = b*b;
c2 = c*c;
&nbsp;
px2 = px*px;
py2 = py*py;
pz2 = pz*pz;
&nbsp;
lpa = lambda + a*a;
lpb = lambda + b*b;
lpc = lambda + c*c;
&nbsp;
P = a2*px2*lpb.*lpb.*lpc.*lpc + <span style="color: #080;">...</span>
    <span style="">b2</span>*py2*lpa.*lpa.*lpc.*lpc + <span style="color: #080;">...</span>
    <span style="">c2</span>*pz2*lpa.*lpa.*lpb.*lpb - <span style="color: #080;">...</span>
    <span style="">lpa</span>.*lpa.*lpb.*lpb.*lpc.*lpc;
&nbsp;
x = a2*px./lpa;
y = b2*py./lpb;
z = c2*pz./lpc;
&nbsp;
<span style="color: #0000FF;">J</span> = <span style="color: #0000FF;">sqrt</span><span style="color: #080;">&#40;</span> <span style="color: #080;">&#40;</span>px-x<span style="color: #080;">&#41;</span>.*<span style="color: #080;">&#40;</span>px-x<span style="color: #080;">&#41;</span> +  <span style="color: #080;">&#40;</span>py-y<span style="color: #080;">&#41;</span>.*<span style="color: #080;">&#40;</span>py-y<span style="color: #080;">&#41;</span> +  <span style="color: #080;">&#40;</span>pz-z<span style="color: #080;">&#41;</span>.*<span style="color: #080;">&#40;</span>pz-z<span style="color: #080;">&#41;</span> <span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">close</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">figure</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">figure</span><span style="color: #080;">&#40;</span><span style="color: #33f;">1</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">plot</span><span style="color: #080;">&#40;</span> lambda, P, <span style="color:#A020F0;">'b-'</span>, <span style="color:#A020F0;">'linewidth'</span>, <span style="color: #33f;">2</span> <span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">xlabel</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'$\lambda$'</span>, <span style="color:#A020F0;">'Interpreter'</span>, <span style="color:#A020F0;">'LaTex'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">ylabel</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'$\frac{\partial L}{ \partial \lambda }$'</span>, <span style="color:#A020F0;">'Interpreter'</span>, <span style="color:#A020F0;">'LaTex'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">title</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'value of the polynomial'</span><span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">close</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">figure</span><span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">figure</span><span style="color: #080;">&#40;</span><span style="color: #33f;">2</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">plot</span><span style="color: #080;">&#40;</span> lambda, P, <span style="color:#A020F0;">'b-'</span>, <span style="color:#A020F0;">'linewidth'</span>, <span style="color: #33f;">2</span> <span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">axis</span><span style="color: #080;">&#40;</span><span style="color: #080;">&#91;</span>-<span style="color: #33f;">160</span>,<span style="color: #33f;">20</span>,<span style="color: #33f;">0</span>, 1e10<span style="color: #080;">&#93;</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">xlabel</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'$\lambda$'</span>, <span style="color:#A020F0;">'Interpreter'</span>, <span style="color:#A020F0;">'LaTex'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">ylabel</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'$\frac{\partial L}{ \partial \lambda }$'</span>, <span style="color:#A020F0;">'Interpreter'</span>, <span style="color:#A020F0;">'LaTex'</span><span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">title</span><span style="color: #080;">&#40;</span><span style="color:#A020F0;">'detail of value of the polynomial'</span><span style="color: #080;">&#41;</span>;
&nbsp;
&nbsp;
<span style="color: #228B22;">% start search by looking at the value of the polynomial at zero</span>
lambda = <span style="color: #33f;">0</span>;
&nbsp;
lpa = lambda + a*a;
lpb = lambda + b*b;
lpc = lambda + c*c;
&nbsp;
P = a2*px2*lpb.*lpb.*lpc.*lpc + <span style="color: #080;">...</span>
    <span style="">b2</span>*py2*lpa.*lpa.*lpc.*lpc + <span style="color: #080;">...</span>
    <span style="">c2</span>*pz2*lpa.*lpa.*lpb.*lpb - <span style="color: #080;">...</span>
    <span style="">lpa</span>.*lpa.*lpb.*lpb.*lpc.*lpc;
&nbsp;
<span style="color: #228B22;">% we need to store the start sign so that we know what sign we're looking</span>
<span style="color: #228B22;">% for in order to determine a zero crossing</span>
startSign = <span style="color: #0000FF;">sign</span><span style="color: #080;">&#40;</span>P<span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% start our search in one direction</span>
<span style="color: #33f;">i</span> = <span style="color: #33f;">1</span>;
&nbsp;
dLambda = <span style="color: #33f;">1</span>;
lhsLambda = <span style="color: #33f;">0</span>;
<span style="color: #228B22;">% start the forward search, we're looking for the first value we can </span>
<span style="color: #228B22;">% find that has a sign opposite that at the zero point</span>
<span style="color: #0000FF;">while</span> dLambda &lt; <span style="color: #0000FF;">realmax</span>/<span style="color: #33f;">10</span>
    rhsLambda   = dLambda;
    lpa         = rhsLambda + a*a;
    lpb         = rhsLambda + b*b;
    lpc         = rhsLambda + c*c;
&nbsp;
    P       =   a2*px2*lpb.*lpb.*lpc.*lpc + <span style="color: #080;">...</span>
                <span style="">b2</span>*py2*lpa.*lpa.*lpc.*lpc + <span style="color: #080;">...</span>
                <span style="">c2</span>*pz2*lpa.*lpa.*lpb.*lpb - <span style="color: #080;">...</span>
                <span style="">lpa</span>.*lpa.*lpb.*lpb.*lpc.*lpc;
&nbsp;
    <span style="color: #228B22;">% if we've discovered a sign change we can stop searching</span>
    <span style="color: #0000FF;">if</span><span style="color: #080;">&#40;</span> <span style="color: #0000FF;">sign</span><span style="color: #080;">&#40;</span>P<span style="color: #080;">&#41;</span> ~= startSign <span style="color: #080;">&#41;</span>
        lhsLambda = dLambda/<span style="color: #33f;">10</span>;
        <span style="color: #0000FF;">break</span>;
&nbsp;
    <span style="color: #228B22;">% if not, we need to grow the increment</span>
    <span style="color: #0000FF;">else</span>
        dLambda = dLambda * <span style="color: #33f;">10</span>;
    <span style="color: #0000FF;">end</span>
<span style="color: #0000FF;">end</span>
&nbsp;
&nbsp;
<span style="color: #228B22;">% now we can start a bisection search using the lhs and rhs that we've</span>
<span style="color: #228B22;">% just determined, which are exactly one order of magnitude apart</span>
<span style="color: #0000FF;">error</span> = <span style="color: #080;">&#40;</span>rhsLambda - lhsLambda<span style="color: #080;">&#41;</span>/lhsLambda;
<span style="color: #0000FF;">while</span><span style="color: #080;">&#40;</span> <span style="color: #0000FF;">abs</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">error</span><span style="color: #080;">&#41;</span> &gt; 1e-2<span style="color: #080;">&#41;</span>
    lambda = <span style="color: #080;">&#40;</span>lhsLambda + rhsLambda<span style="color: #080;">&#41;</span>/<span style="color: #33f;">2</span>;
    lpa         = lambda + a*a;
    lpb         = lambda + b*b;
    lpc         = lambda + c*c;
&nbsp;
    P       =   a2*px2*lpb.*lpb.*lpc.*lpc + <span style="color: #080;">...</span>
                <span style="">b2</span>*py2*lpa.*lpa.*lpc.*lpc + <span style="color: #080;">...</span>
                <span style="">c2</span>*pz2*lpa.*lpa.*lpb.*lpb - <span style="color: #080;">...</span>
                <span style="">lpa</span>.*lpa.*lpb.*lpb.*lpc.*lpc;
&nbsp;
    <span style="color: #0000FF;">if</span><span style="color: #080;">&#40;</span> <span style="color: #0000FF;">sign</span><span style="color: #080;">&#40;</span>P<span style="color: #080;">&#41;</span> ~= startSign <span style="color: #080;">&#41;</span>
        rhsLambda = lambda;
    <span style="color: #0000FF;">else</span>
        lhsLambda = lambda;
    <span style="color: #0000FF;">end</span>
&nbsp;
    <span style="color: #0000FF;">error</span> = <span style="color: #080;">&#40;</span>lhsLambda - rhsLambda<span style="color: #080;">&#41;</span>/lhsLambda;
<span style="color: #0000FF;">end</span>
&nbsp;
<span style="color: #228B22;">% store the found value</span>
lambda1 = <span style="color: #080;">&#40;</span>lhsLambda + rhsLambda<span style="color: #080;">&#41;</span>/<span style="color: #33f;">2</span>;
&nbsp;
<span style="color: #228B22;">% now we search in the other direction;</span>
dLambda = <span style="color: #33f;">1</span>;
rhsLambda = <span style="color: #33f;">0</span>;
<span style="color: #228B22;">% start the forward search, we're looking for the first value we can </span>
<span style="color: #228B22;">% find that has a sign opposite that at the zero point</span>
<span style="color: #0000FF;">while</span> dLambda &lt; <span style="color: #0000FF;">realmax</span>/<span style="color: #33f;">10</span>
    lhsLambda   = -dLambda;
    lpa         = lhsLambda + a*a;
    lpb         = lhsLambda + b*b;
    lpc         = lhsLambda + c*c;
&nbsp;
    P       =   a2*px2*lpb.*lpb.*lpc.*lpc + <span style="color: #080;">...</span>
                <span style="">b2</span>*py2*lpa.*lpa.*lpc.*lpc + <span style="color: #080;">...</span>
                <span style="">c2</span>*pz2*lpa.*lpa.*lpb.*lpb - <span style="color: #080;">...</span>
                <span style="">lpa</span>.*lpa.*lpb.*lpb.*lpc.*lpc;
&nbsp;
    <span style="color: #228B22;">% if we've discovered a sign change we can stop searching</span>
    <span style="color: #0000FF;">if</span><span style="color: #080;">&#40;</span> <span style="color: #0000FF;">sign</span><span style="color: #080;">&#40;</span>P<span style="color: #080;">&#41;</span> ~= startSign <span style="color: #080;">&#41;</span>
        rhsLambda = -dLambda/<span style="color: #33f;">10</span>;
        <span style="color: #0000FF;">break</span>;
&nbsp;
    <span style="color: #228B22;">% if not, we need to grow the increment</span>
    <span style="color: #0000FF;">else</span>
        dLambda = dLambda * <span style="color: #33f;">10</span>;
    <span style="color: #0000FF;">end</span>
<span style="color: #0000FF;">end</span>
&nbsp;
<span style="color: #228B22;">% now we can start a bisection search using the lhs and rhs that we've </span>
<span style="color: #228B22;">% just determined, which are exactly one order of magnitude apart</span>
<span style="color: #0000FF;">error</span> = <span style="color: #080;">&#40;</span>rhsLambda - lhsLambda<span style="color: #080;">&#41;</span>/lhsLambda;
<span style="color: #0000FF;">while</span><span style="color: #080;">&#40;</span> <span style="color: #0000FF;">abs</span><span style="color: #080;">&#40;</span><span style="color: #0000FF;">error</span><span style="color: #080;">&#41;</span> &gt; 1e-2<span style="color: #080;">&#41;</span>
    lambda = <span style="color: #080;">&#40;</span>lhsLambda + rhsLambda<span style="color: #080;">&#41;</span>/<span style="color: #33f;">2</span>;
    lpa         = lambda + a*a;
    lpb         = lambda + b*b;
    lpc         = lambda + c*c;
&nbsp;
    P       =   a2*px2*lpb.*lpb.*lpc.*lpc + <span style="color: #080;">...</span>
                <span style="">b2</span>*py2*lpa.*lpa.*lpc.*lpc + <span style="color: #080;">...</span>
                <span style="">c2</span>*pz2*lpa.*lpa.*lpb.*lpb - <span style="color: #080;">...</span>
                <span style="">lpa</span>.*lpa.*lpb.*lpb.*lpc.*lpc;
&nbsp;
    <span style="color: #0000FF;">if</span><span style="color: #080;">&#40;</span> <span style="color: #0000FF;">sign</span><span style="color: #080;">&#40;</span>P<span style="color: #080;">&#41;</span> ~= startSign <span style="color: #080;">&#41;</span>
        lhsLambda = lambda;
    <span style="color: #0000FF;">else</span>
        rhsLambda = lambda;
    <span style="color: #0000FF;">end</span>
&nbsp;
    <span style="color: #0000FF;">error</span> = <span style="color: #080;">&#40;</span>lhsLambda - rhsLambda<span style="color: #080;">&#41;</span>/lhsLambda;
<span style="color: #0000FF;">end</span>
&nbsp;
<span style="color: #228B22;">% store the found value</span>
lambda2 = <span style="color: #080;">&#40;</span>lhsLambda + rhsLambda<span style="color: #080;">&#41;</span>/<span style="color: #33f;">2</span>;
&nbsp;
x1 = a2*px/<span style="color: #080;">&#40;</span>lambda1+a2<span style="color: #080;">&#41;</span>;
y1 = b2*py/<span style="color: #080;">&#40;</span>lambda1+b2<span style="color: #080;">&#41;</span>;
z1 = c2*pz/<span style="color: #080;">&#40;</span>lambda1+c2<span style="color: #080;">&#41;</span>;
&nbsp;
x2 = a2*px/<span style="color: #080;">&#40;</span>lambda2+a2<span style="color: #080;">&#41;</span>;
y2 = b2*py/<span style="color: #080;">&#40;</span>lambda2+b2<span style="color: #080;">&#41;</span>;
z2 = c2*pz/<span style="color: #080;">&#40;</span>lambda2+c2<span style="color: #080;">&#41;</span>;
&nbsp;
J1 = <span style="color: #0000FF;">sqrt</span><span style="color: #080;">&#40;</span> <span style="color: #080;">&#40;</span>px-x1<span style="color: #080;">&#41;</span>*<span style="color: #080;">&#40;</span>px-x1<span style="color: #080;">&#41;</span> + <span style="color: #080;">&#40;</span>py-y1<span style="color: #080;">&#41;</span>*<span style="color: #080;">&#40;</span>py-y1<span style="color: #080;">&#41;</span> + <span style="color: #080;">&#40;</span>py-y1<span style="color: #080;">&#41;</span>*<span style="color: #080;">&#40;</span>py-y1<span style="color: #080;">&#41;</span> <span style="color: #080;">&#41;</span>;
J2 = <span style="color: #0000FF;">sqrt</span><span style="color: #080;">&#40;</span> <span style="color: #080;">&#40;</span>px-x2<span style="color: #080;">&#41;</span>*<span style="color: #080;">&#40;</span>px-x2<span style="color: #080;">&#41;</span> + <span style="color: #080;">&#40;</span>py-y2<span style="color: #080;">&#41;</span>*<span style="color: #080;">&#40;</span>py-y2<span style="color: #080;">&#41;</span> + <span style="color: #080;">&#40;</span>py-y2<span style="color: #080;">&#41;</span>*<span style="color: #080;">&#40;</span>py-y2<span style="color: #080;">&#41;</span> <span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #228B22;">% print a little report</span>
message = <span style="color: #0000FF;">sprintf</span><span style="color: #080;">&#40;</span> <span style="color: #080;">&#91;</span><span style="color:#A020F0;">'found zero crossings at lambda = %f and %f'</span>, <span style="color: #080;">...</span>
                    <span style="color:#A020F0;">'which corresponds to the points [%f, %f, %f]'</span>, <span style="color: #080;">...</span>
                    <span style="color:#A020F0;">'and [%f, %f, %f] with costs of %f and %f'</span><span style="color: #080;">&#93;</span>, <span style="color: #080;">...</span>
                   <span style="">lambda1</span>, lambda2, x1, y1, z1, x2, y2, z2, J1, J2 <span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>message<span style="color: #080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">if</span><span style="color: #080;">&#40;</span> J1 &lt; J2 <span style="color: #080;">&#41;</span>
    message = <span style="color: #0000FF;">sprintf</span><span style="color: #080;">&#40;</span> <span style="color:#A020F0;">'the point of minimum distance is [%f, %f, %f]'</span>, <span style="color: #080;">...</span>
                        <span style="">x1</span>, y1, z1 <span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">else</span>
    message = <span style="color: #0000FF;">sprintf</span><span style="color: #080;">&#40;</span> <span style="color:#A020F0;">'the point of minimum distance is [%f, %f, %f]'</span>, <span style="color: #080;">...</span>
                        <span style="">x2</span>, y2, z2 <span style="color: #080;">&#41;</span>;
<span style="color: #0000FF;">end</span>
&nbsp;
<span style="color: #0000FF;">disp</span><span style="color: #080;">&#40;</span>message<span style="color: #080;">&#41;</span>;</pre></td></tr></table></div>

<p>The output of this script is</p>
<p><code><br />
found zero crossings at lambda = 11.801758 and -155.810547which corresponds to the points [1.297967, 3.223591, 6.982626]and [-0.183910, -1.835025, -8.661880] with costs of 2.025472 and 8.844903<br />
the point of minimum distance is [1.297967, 3.223591, 6.982626]<br />
</code></p>
<p>Which matches with the previous method. Sweet.</p>
<p>As a brief note, if the target point is inside the ellipse and along one of it&#8217;s axes, there may be an infinite number of solutions (all points on a ring around the ellipse located at the coordinate of the target point will be the same distance away). If this is a possibility in your application, make sure you watch out for it and decide what the &#8220;right&#8221; solution is. </p>
<p>I hope this helps. Sorry I didn&#8217;t write the code in c++ but it took long enough to generate the results without doing that. Hopefully you can figure out from the matlab code exactly what you need to. Matlab script isn&#8217;t too different from C++. </p>
<p>-Cheshirekow</p>
]]></content:encoded>
			<wfw:commentRss>http://cheshirekow.com/blog/?feed=rss2&amp;p=86</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Instanciate Objects of Unknown Type from Their Parent Interface</title>
		<link>http://cheshirekow.com/blog/?p=74</link>
		<comments>http://cheshirekow.com/blog/?p=74#comments</comments>
		<pubDate>Sat, 15 Aug 2009 00:13:36 +0000</pubDate>
		<dc:creator>cheshirekow</dc:creator>
				<category><![CDATA[C++ Discoveries and Notes]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://cheshirekow.com/blog/?p=74</guid>
		<description><![CDATA[This is based on my previous two posts on Static Interfaces in C++ and Keep Track of and Enumerate All Sub-classes of a Particular Interface. The idea is that I want my code to be extensible in the feature without requiring any re-writing of the current code base. The code base operates on generic objects [...]]]></description>
			<content:encoded><![CDATA[<img style='float: left; margin-right: 10px; border: none;' src='http://www.gravatar.com/avatar.php?gravatar_id=b30a23a04ca0f61ac513426b4d50907f&amp;default=http://use.perl.org/images/pix.gif' alt='No Gravatar' width=40 height=40/><p>This is based on my previous two posts on <a href="http://cheshirekow.com/blog/?p=55">Static Interfaces in C++</a> and <a href="http://cheshirekow.com/blog/?p=40">Keep Track of and Enumerate All Sub-classes of a Particular Interface</a>. The idea is that I want my code to be extensible in the feature without requiring any re-writing of the current code base. The code base operates on generic objects via their interfaces, so as long as newly-coded classes properly extend those interfaces, the program should know how to handle them. The problem is, how can we write the program in such a manner that a user interface can enumerate available options for implementations of a particular interface, and how can we instantiate those objects? </p>
<p>In <a href="http://cheshirekow.com/blog/?p=40">Keep Track of and Enumerate All Sub-classes of a Particular Interface</a> I showed how to maintain a registry of classes deriving from a given interface, which handles the first problem, but there is a limitation in that all of these classes must provide a factory method that takes no parameters (void input). I decided that, for my project, this was not acceptable and I needed a way to define the creation parameters as part of the factory methods, whereas the creation parameters may be different for particular interfaces. </p>
<p>In <a href="http://cheshirekow.com/blog/?p=40">Keep Track of and Enumerate All Sub-classes of a Particular Interface</a> I showed how we can enforce the requirement of a static method in derived classes with a particular signature using a template interface. </p>
<p>In this post I will combine the two so that we can create a registry of classes that inherit from a particular interface, and provide a static factory method for creating objects of that interface, using a particular creation method signature unique to that interface. The registry will pair class names with function pointers that match the specific signature of the interface the class is being registered for.</p>
<p>Disclaimer: I do not claim this is the &#8220;best&#8221; way to handle this issue. This is just what I came up with. It happens to be pretty involved and overly indirect, which means it&#8217;s probably bad design. It is, however, an extremely interesting exercise in generic programming. </p>
<p>Prequil: the code will require these later so there they are:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #ff0000; font-style: italic;">/**
 *  \file          RegistryTest.cpp
 *  \date:      Aug 14, 2009
 *  \brief:
 *
 *  detail:
 */</span>
&nbsp;
&nbsp;
<span style="color: #339900;">#include &lt;set&gt;</span>
<span style="color: #339900;">#include &lt;map&gt;</span>
<span style="color: #339900;">#include &lt;string&gt;</span>
<span style="color: #339900;">#include &lt;iostream&gt;</span>
&nbsp;
<span style="color: #0000ff;">using</span> <span style="color: #0000ff;">namespace</span> std<span style="color: #008080;">;</span></pre></td></tr></table></div>

<p>Ok, so lets begin. First let&#8217;s define a couple of interfaces that we&#8217;re interested in.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>16
17
18
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">class</span> InterfaceA<span style="color: #008000;">&#123;</span><span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
<span style="color: #0000ff;">class</span> InterfaceB<span style="color: #008000;">&#123;</span><span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
<span style="color: #0000ff;">class</span> InterfaceC<span style="color: #008000;">&#123;</span><span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></td></tr></table></div>

<p>Now we create a template class whose sole purpose is to create a per-interface <code>typedef</code> of the function signature that is necessary for instantiating and object of that class. Is it really possible that all sub-objects can be instantiated with the same parameters? If that&#8217;s the case, shouldn&#8217;t they all be combined into a single class that just contains that information as private members? Probably, but in my case these parameters are more like a &#8220;bare minimum&#8221; for instantiation, and then many more parameters are set by the user. It makes sense to me, I promise. If it doesn&#8217;t to you, you don&#8217;t have to use this.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>19
20
21
22
23
24
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">template</span><span style="color: #000080;">&lt;</span> <span style="color: #0000ff;">typename</span> InterfaceType <span style="color: #000080;">&gt;</span>
<span style="color: #0000ff;">class</span> Factory
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
        <span style="color: #0000ff;">typedef</span> InterfaceType<span style="color: #000040;">*</span><span style="color: #008000;">&#40;</span><span style="color: #000040;">*</span>Creator<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></td></tr></table></div>

<p><code>Creator</code> is now a <code>typedef</code> that aliases a function pointer that takes no parameters. Wait, isn&#8217;t that what we had before? Yes, but now we make a couple of template specializations to define the different signatures for our specific interfaces. These specializations would normally be in the file that contained the interface declaration.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>25
26
27
28
29
30
31
32
33
34
35
36
37
38
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #666666;">/// specializations can define other creators, this one requires an int</span>
<span style="color: #0000ff;">template</span><span style="color: #000080;">&lt;&gt;</span> <span style="color: #0000ff;">class</span> Factory<span style="color: #000080;">&lt;</span>InterfaceB<span style="color: #000080;">&gt;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
        <span style="color: #0000ff;">typedef</span> InterfaceB<span style="color: #000040;">*</span><span style="color: #008000;">&#40;</span><span style="color: #000040;">*</span>Creator<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #666666;">/// specializations can define other creators, this one requires an int, a</span>
<span style="color: #666666;">/// bool, and a char</span>
<span style="color: #0000ff;">template</span><span style="color: #000080;">&lt;&gt;</span> <span style="color: #0000ff;">class</span> Factory<span style="color: #000080;">&lt;</span>InterfaceC<span style="color: #000080;">&gt;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
        <span style="color: #0000ff;">typedef</span> InterfaceC<span style="color: #000040;">*</span><span style="color: #008000;">&#40;</span><span style="color: #000040;">*</span>Creator<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span>,<span style="color: #0000ff;">bool</span>,<span style="color: #0000ff;">char</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></td></tr></table></div>

<p>Cool. Now we create a static interface that enforces it&#8217;s derivative classes to contain a static method called <code>createNew</code> which can be used to instantiate a new object of that interface. We can use the typedef we just created to make the function signature generic for this template (or specific to individual instantiations of it).</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>39
40
41
42
43
44
45
46
47
48
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">template</span><span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> InterfaceType, <span style="color: #0000ff;">typename</span> ClassType<span style="color: #000080;">&gt;</span>
<span style="color: #0000ff;">class</span> IStaticFactory
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
        IStaticFactory<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0000ff;">typename</span> Factory<span style="color: #000080;">&lt;</span>InterfaceType<span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">Creator</span> check <span style="color: #000080;">=</span> ClassType<span style="color: #008080;">::</span><span style="color: #007788;">createNew</span><span style="color: #008080;">;</span>
            check <span style="color: #000080;">=</span> check<span style="color: #008080;">;</span>
        <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></td></tr></table></div>

<p>Still following? Good. Now we define the registry class template, which maps the class name of a derived class to a function pointer with an interface-specific signature that serves as a static factory for objects of the derived class, returning a pointer to that object of the type of the interface. See my previous post for details on this class.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> InterfaceType<span style="color: #000080;">&gt;</span>
<span style="color: #0000ff;">class</span> Registry
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">private</span><span style="color: #008080;">:</span>
        std<span style="color: #008080;">::</span><span style="color: #007788;">map</span><span style="color: #000080;">&lt;</span> std<span style="color: #008080;">::</span><span style="color: #007788;">string</span>, <span style="color: #0000ff;">typename</span> Factory<span style="color: #000080;">&lt;</span>InterfaceType<span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">Creator</span> <span style="color: #000080;">&gt;</span> m_creatorMap<span style="color: #008080;">;</span>
&nbsp;
&nbsp;
        Registry<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#123;</span><span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
&nbsp;
        <span style="color: #0000ff;">static</span> Registry<span style="color: #000040;">&amp;</span> getInstance<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
        <span style="color: #0000ff;">bool</span> registerClass<span style="color: #008000;">&#40;</span> <span style="color: #0000ff;">const</span> std<span style="color: #008080;">::</span><span style="color: #007788;">string</span><span style="color: #000040;">&amp;</span> name,
                             <span style="color: #0000ff;">typename</span> Factory<span style="color: #000080;">&lt;</span>InterfaceType<span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">Creator</span> creator <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
        std<span style="color: #008080;">::</span><span style="color: #007788;">set</span><span style="color: #000080;">&lt;</span>std<span style="color: #008080;">::</span><span style="color: #007788;">string</span><span style="color: #000080;">&gt;</span>  getClassNames<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
        <span style="color: #0000ff;">typename</span>
        Factory<span style="color: #000080;">&lt;</span>InterfaceType<span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">Creator</span>
        Registry<span style="color: #000080;">&lt;</span>InterfaceType<span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">getCreator</span><span style="color: #008000;">&#40;</span>
                std<span style="color: #008080;">::</span><span style="color: #007788;">string</span> className <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
&nbsp;
<span style="color: #666666;">// A convient macro to compact the registration of a class</span>
<span style="color: #339900;">#define RegisterWithInterface( CLASS, INTERFACE )                   \
namespace                                                           \
{                                                                   \
    bool dummy_ ## CLASS =                                          \
    Registry&lt;INTERFACE&gt;::getInstance().registerClass(     \
            #CLASS, CLASS::createNew );                               \
}</span>
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
<span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> InterfaceType <span style="color: #000080;">&gt;</span>
Registry<span style="color: #000080;">&lt;</span>InterfaceType<span style="color: #000080;">&gt;</span><span style="color: #000040;">&amp;</span> Registry<span style="color: #000080;">&lt;</span>InterfaceType<span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">getInstance</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">static</span> Registry<span style="color: #000080;">&lt;</span>InterfaceType<span style="color: #000080;">&gt;</span>    registry<span style="color: #008080;">;</span>
    <span style="color: #0000ff;">return</span> registry<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
<span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> InterfaceType <span style="color: #000080;">&gt;</span>
<span style="color: #0000ff;">bool</span> Registry<span style="color: #000080;">&lt;</span>InterfaceType<span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">registerClass</span><span style="color: #008000;">&#40;</span> <span style="color: #0000ff;">const</span> std<span style="color: #008080;">::</span><span style="color: #007788;">string</span><span style="color: #000040;">&amp;</span> name,
                        <span style="color: #0000ff;">typename</span> Factory<span style="color: #000080;">&lt;</span>InterfaceType<span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">Creator</span> creator <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    m_creatorMap<span style="color: #008000;">&#91;</span>name<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> creator<span style="color: #008080;">;</span>
    <span style="color: #0000ff;">return</span> <span style="color: #0000ff;">true</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
<span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> InterfaceType <span style="color: #000080;">&gt;</span>
std<span style="color: #008080;">::</span><span style="color: #007788;">set</span><span style="color: #000080;">&lt;</span>std<span style="color: #008080;">::</span><span style="color: #007788;">string</span><span style="color: #000080;">&gt;</span>  Registry<span style="color: #000080;">&lt;</span>InterfaceType<span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">getClassNames</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    std<span style="color: #008080;">::</span><span style="color: #007788;">set</span><span style="color: #000080;">&lt;</span>std<span style="color: #008080;">::</span><span style="color: #007788;">string</span><span style="color: #000080;">&gt;</span>   keys<span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #0000ff;">typename</span>
    std<span style="color: #008080;">::</span><span style="color: #007788;">map</span><span style="color: #000080;">&lt;</span> std<span style="color: #008080;">::</span><span style="color: #007788;">string</span>, InterfaceType<span style="color: #000040;">*</span> <span style="color: #008000;">&#40;</span><span style="color: #000040;">*</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">iterator</span> pair<span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #0000ff;">for</span><span style="color: #008000;">&#40;</span> pair <span style="color: #000080;">=</span> m_creatorMap.<span style="color: #007788;">begin</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> pair <span style="color: #000040;">!</span><span style="color: #000080;">=</span> m_creatorMap.<span style="color: #007788;">end</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> pair<span style="color: #000040;">++</span><span style="color: #008000;">&#41;</span>
        keys.<span style="color: #007788;">insert</span><span style="color: #008000;">&#40;</span> pair<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>first <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #0000ff;">return</span> keys<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
<span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> InterfaceType <span style="color: #000080;">&gt;</span>
<span style="color: #0000ff;">typename</span>
Factory<span style="color: #000080;">&lt;</span>InterfaceType<span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">Creator</span>
Registry<span style="color: #000080;">&lt;</span>InterfaceType<span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">getCreator</span><span style="color: #008000;">&#40;</span>
        std<span style="color: #008080;">::</span><span style="color: #007788;">string</span> className <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">return</span> m_creatorMap<span style="color: #008000;">&#91;</span>className<span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>The difference between this and the Registry in my previous post, is that this time the registry uses the generic <code>Factory&lt;InterfaceType&gt;::Creator</code> typedef to define the function pointer. This way, that pointer is forced to have the specific signature. Sweet!</p>
<p>Now lets write some derived classes of those interfaces.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">class</span>   DerivedA <span style="color: #008080;">:</span> <span style="color: #0000ff;">public</span> InterfaceA,
                    <span style="color: #0000ff;">public</span> IStaticFactory<span style="color: #000080;">&lt;</span>InterfaceA, DerivedA<span style="color: #000080;">&gt;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
        <span style="color: #0000ff;">static</span> InterfaceA<span style="color: #000040;">*</span>  createNew<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> <span style="color: #008000;">&#40;</span>InterfaceA<span style="color: #000040;">*</span><span style="color: #008000;">&#41;</span><span style="color: #0000dd;">1</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
RegisterWithInterface<span style="color: #008000;">&#40;</span>DerivedA, InterfaceA<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
&nbsp;
<span style="color: #0000ff;">class</span>   DerivedB <span style="color: #008080;">:</span> <span style="color: #0000ff;">public</span> InterfaceB,
                    <span style="color: #0000ff;">public</span> IStaticFactory<span style="color: #000080;">&lt;</span>InterfaceB, DerivedB<span style="color: #000080;">&gt;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
        <span style="color: #0000ff;">static</span> InterfaceB<span style="color: #000040;">*</span>  createNew<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> a<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> <span style="color: #008000;">&#40;</span>InterfaceB<span style="color: #000040;">*</span><span style="color: #008000;">&#41;</span><span style="color: #0000dd;">2</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
RegisterWithInterface<span style="color: #008000;">&#40;</span>DerivedB, InterfaceB<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
&nbsp;
&nbsp;
<span style="color: #0000ff;">class</span>   DerivedC <span style="color: #008080;">:</span> <span style="color: #0000ff;">public</span> InterfaceC,
                    <span style="color: #0000ff;">public</span> IStaticFactory<span style="color: #000080;">&lt;</span>InterfaceC, DerivedC<span style="color: #000080;">&gt;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
        <span style="color: #0000ff;">static</span> InterfaceC<span style="color: #000040;">*</span>  createNew<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> a, <span style="color: #0000ff;">bool</span> b, <span style="color: #0000ff;">char</span> c<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> <span style="color: #008000;">&#40;</span>InterfaceC<span style="color: #000040;">*</span><span style="color: #008000;">&#41;</span><span style="color: #0000dd;">3</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
&nbsp;
RegisterWithInterface<span style="color: #008000;">&#40;</span>DerivedC, InterfaceC<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></pre></td></tr></table></div>

<p>These classes are basically dummies, but inheriting from <code>IStaticFactory...</code> the compiler will enforce that they contain the static method <code>createNew</code> with the proper signature. Notice that <code>InterfaceA</code> uses the default template so the static factory in <code>DerivedA</code> takes no parameters, while <code>InterfaceB</code> and <code>InterfaceC</code> have specializations so the static factories in <code>DerivedB</code> and <code>DerivedC</code> have their respective parameters. Since this is just an example, the methods don&#8217;t actually create new objects they just return pointers, but in reality this is where we would use <code>new DerivedA(...)</code> and so on.</p>
<p>Well that&#8217;s it. Pretty cool huh? The compiler will enforce all this stuff for us so we can actually say to ourselves when we write new implementations months from now &#8220;If it compiles, it will be compatible.&#8221; </p>
<p>Lastly, here&#8217;s a little test case to run</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    DerivedA    a<span style="color: #008080;">;</span>
    DerivedB    b<span style="color: #008080;">;</span>
    DerivedC    c<span style="color: #008080;">;</span>
&nbsp;
    InterfaceA<span style="color: #000040;">*</span> pA<span style="color: #008080;">;</span>
    InterfaceB<span style="color: #000040;">*</span> pB<span style="color: #008080;">;</span>
    InterfaceC<span style="color: #000040;">*</span> pC<span style="color: #008080;">;</span>
&nbsp;
    Factory<span style="color: #000080;">&lt;</span>InterfaceA<span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">Creator</span> makesObjectOfA <span style="color: #000080;">=</span>
            Registry<span style="color: #000080;">&lt;</span>InterfaceA<span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">getInstance</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>.<span style="color: #007788;">getCreator</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;DerivedA&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    pA <span style="color: #000080;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #000040;">*</span>makesObjectOfA<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
    Factory<span style="color: #000080;">&lt;</span>InterfaceB<span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">Creator</span> makesObjectOfB <span style="color: #000080;">=</span>
            Registry<span style="color: #000080;">&lt;</span>InterfaceB<span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">getInstance</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>.<span style="color: #007788;">getCreator</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;DerivedB&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    pB <span style="color: #000080;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #000040;">*</span>makesObjectOfB<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
    Factory<span style="color: #000080;">&lt;</span>InterfaceC<span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">Creator</span> makesObjectOfC <span style="color: #000080;">=</span>
            Registry<span style="color: #000080;">&lt;</span>InterfaceC<span style="color: #000080;">&gt;</span><span style="color: #008080;">::</span><span style="color: #007788;">getInstance</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>.<span style="color: #007788;">getCreator</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;DerivedC&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    pC <span style="color: #000080;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #000040;">*</span>makesObjectOfC<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #0000dd;">1</span>,<span style="color: #0000ff;">false</span>,<span style="color: #FF0000;">'a'</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;pA: &quot;</span> <span style="color: #000080;">&lt;&lt;</span> pA <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #008080;">;</span>
    <span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;pB: &quot;</span> <span style="color: #000080;">&lt;&lt;</span> pB <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #008080;">;</span>
    <span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;pC: &quot;</span> <span style="color: #000080;">&lt;&lt;</span> pC <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<div id="attachment_79" class="wp-caption aligncenter" style="width: 289px"><img src="http://cheshirekow.com/blog/wp-content/uploads/2009/08/registry2.jpg" alt="Output of the Test Program" title="registry2" width="279" height="74" class="size-full wp-image-79" /><p class="wp-caption-text">Output of the Test Program</p></div>
]]></content:encoded>
			<wfw:commentRss>http://cheshirekow.com/blog/?feed=rss2&amp;p=74</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Static Interfaces in C++</title>
		<link>http://cheshirekow.com/blog/?p=55</link>
		<comments>http://cheshirekow.com/blog/?p=55#comments</comments>
		<pubDate>Thu, 13 Aug 2009 20:09:12 +0000</pubDate>
		<dc:creator>cheshirekow</dc:creator>
				<category><![CDATA[C++ Discoveries and Notes]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://cheshirekow.com/blog/?p=55</guid>
		<description><![CDATA[I remember looking around a few weeks ago for how to make a &#8220;static interface&#8221; in c++. Basically, I wanted a way to use the compiler to enforce that a class had certain static functions. Almost all of the internet resources I found basically said &#8220;Why would you ever want to do that; you don&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<img style='float: left; margin-right: 10px; border: none;' src='http://www.gravatar.com/avatar.php?gravatar_id=b30a23a04ca0f61ac513426b4d50907f&amp;default=http://use.perl.org/images/pix.gif' alt='No Gravatar' width=40 height=40/><p>I remember looking around a few weeks ago for how to make a &#8220;static interface&#8221; in c++. Basically, I wanted a way to use the compiler to enforce that a class had certain static functions. Almost all of the internet resources I found basically said &#8220;Why would you ever want to do that; you don&#8217;t really want to do that; you probably have bad design&#8221; and so on&#8230; continuously begging the question. Of course, they were right: the design was bad and that wasn&#8217;t really what I wanted to do. Well, never the less, I still managed to think of a way to create a sort of static interface using a template class. </p>
<p>The strategy is to define a template class that uses the static methods of the template parameter class. That way, as long as the template is instantiated, the compiler will complain unless we have provided those static functions. We can ensure that the template is instantiated and enforce the inheritance idea by making the derived class extend from the template class we wrote to enforce those static methods. </p>
<p>Here is an example. We can create the static interface by declaring a class template that uses the functions we want to enforce as part of the interface.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span> <span style="color: #0000ff;">typename</span> T <span style="color: #000080;">&gt;</span>
<span style="color: #0000ff;">class</span> StaticInterface
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
        StaticInterface<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0000ff;">int</span><span style="color: #008000;">&#40;</span><span style="color: #000040;">*</span>fooCheck<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span><span style="color: #008000;">&#41;</span>     <span style="color: #000080;">=</span> T<span style="color: #008080;">::</span><span style="color: #007788;">foo</span><span style="color: #008080;">;</span>
            <span style="color: #0000ff;">bool</span><span style="color: #008000;">&#40;</span><span style="color: #000040;">*</span>barCheck<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">bool</span><span style="color: #008000;">&#41;</span>   <span style="color: #000080;">=</span> T<span style="color: #008080;">::</span><span style="color: #007788;">bar</span><span style="color: #008080;">;</span>
        <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></td></tr></table></div>

<p>By assigning <code>T::foo</code> and <code>T::bar</code> to function pointers, we are saying, implicitly, that whatever class is provided as a parameter to this template must have a static method called <code>foo</code> and a static method called <code>bar</code> and, furthermore, that those static methods must have<br />
the same signature as the function pointers we stuff them into. </p>
<p>By putting this code inside the constructor of the class, we know that this method of the template will be instantiated, even if we don&#8217;t explicitly use it later in the code, as long as we derive from this class somewhere. So then, the last question is, where can we derive from it?</p>
<p>Well, in the class that we want to inherit the interface of course!</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>11
12
13
14
15
16
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">class</span> DerivedClass <span style="color: #008080;">:</span> <span style="color: #0000ff;">public</span> StaticInterface<span style="color: #000080;">&lt;</span>DerivedClass<span style="color: #000080;">&gt;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
        <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">int</span> foo<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span>  param<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">10</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span>
        <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">bool</span> bar<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">bool</span> param<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">20</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></td></tr></table></div>

<p>The <code>DerivedClass</code> constructor implicitly calls the <code> StaticInterface<DerivedClass> </code> constructor, which assigns the function pointers <code>fooCheck</code> and <code>barCheck</code> to the address of the functions <code>DerivedClass::foo</code> and <code>DerivedClass::bar</code>. As a result, if we forget the <code>bar</code> function in the <code>DerivedClass</code> the compiler will choke with an error. g++ says the following:</p>
<p><code><br />
src/poc/test/StaticInterfaceTest.cpp: In constructor `StaticInterface<T>::StaticInterface() [with T = DerivedClass]':<br />
src/poc/test/StaticInterfaceTest.cpp:41:   instantiated from here<br />
src/poc/test/StaticInterfaceTest.cpp:20: error: `bar' is not a member of `DerivedClass'<br />
</code></p>
<p>Pretty cool huh?</p>
<p>As a final note, please consider this &#8220;an interesting observation&#8221; and not necessarily a &#8220;great design choice&#8221;. As I said, I decided against actually trying to utilize this idea in my project, and I urge you think carefully before about yours before trying to use it yourself. </p>
]]></content:encoded>
			<wfw:commentRss>http://cheshirekow.com/blog/?feed=rss2&amp;p=55</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
