4ae79c87c9555209581f12a8522bad6cec8189ee — Zeke Medley 9 days ago 4909e47
Add writeup about lab 2
2 files changed, 179 insertions(+), 0 deletions(-)

M public/index.html
A public/lab-2.html
M public/index.html => public/index.html +1 -0
@@ 27,6 27,7 @@
	<li><a href="/1-thursday.html">Arduino communication guide</a></li>
	<li><a href="/serial-visualization.html">Plotting data with your Arduino</a></li>
	<li><a href="/lab-2.html">Lab 2 Code Walkthrough</a></li>

A public/lab-2.html => public/lab-2.html +178 -0
@@ 0,0 1,178 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang xml:lang>
  <meta charset="utf-8" />
  <meta name="generator" content="pandoc" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
  <title>Lab 2 Code Walkthrough</title>
    code{white-space: pre-wrap;}
    span.smallcaps{font-variant: small-caps;}
    span.underline{text-decoration: underline;}
    div.column{display: inline-block; vertical-align: top; width: 50%;}
    div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
    ul.task-list{list-style: none;}
    pre > code.sourceCode { white-space: pre; position: relative; }
    pre > code.sourceCode > span { display: inline-block; line-height: 1.25; }
    pre > code.sourceCode > span:empty { height: 1.2em; }
    code.sourceCode > span { color: inherit; text-decoration: inherit; }
    div.sourceCode { margin: 1em 0; }
    pre.sourceCode { margin: 0; }
    pre { font-size: 130%; }
    @media screen {
    div.sourceCode { overflow: auto; }
    @media print {
    pre > code.sourceCode { white-space: pre-wrap; }
    pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
    pre.numberSource code
      { counter-reset: source-line 0; }
    pre.numberSource code > span
      { position: relative; left: -4em; counter-increment: source-line; }
    pre.numberSource code > span > a:first-child::before
      { content: counter(source-line);
        position: relative; left: -1em; text-align: right; vertical-align: baseline;
        border: none; display: inline-block;
        -webkit-touch-callout: none; -webkit-user-select: none;
        -khtml-user-select: none; -moz-user-select: none;
        -ms-user-select: none; user-select: none;
        padding: 0 4px; width: 4em;
        color: #aaaaaa;
    pre.numberSource { margin-left: 3em; border-left: 1px solid #aaaaaa;  padding-left: 4px; }
      {   }
    @media screen {
    pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
    code span.al { color: #ff0000; font-weight: bold; } /* Alert */
    code span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
    code span.at { color: #7d9029; } /* Attribute */
    code span.bn { color: #40a070; } /* BaseN */
    code span.bu { } /* BuiltIn */
    code span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
    code span.ch { color: #4070a0; } /* Char */
    code span.cn { color: #880000; } /* Constant */
    code span.co { color: #60a0b0; font-style: italic; } /* Comment */
    code span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
    code span.do { color: #ba2121; font-style: italic; } /* Documentation */
    code span.dt { color: #902000; } /* DataType */
    code span.dv { color: #40a070; } /* DecVal */
    code span.er { color: #ff0000; font-weight: bold; } /* Error */
    code span.ex { } /* Extension */
    code span.fl { color: #40a070; } /* Float */
    code span.fu { color: #06287e; } /* Function */
    code span.im { } /* Import */
    code span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
    code span.kw { color: #007020; font-weight: bold; } /* Keyword */
    code span.op { color: #666666; } /* Operator */
    code span.ot { color: #007020; } /* Other */
    code span.pp { color: #bc7a00; } /* Preprocessor */
    code span.sc { color: #4070a0; } /* SpecialChar */
    code span.ss { color: #bb6688; } /* SpecialString */
    code span.st { color: #4070a0; } /* String */
    code span.va { color: #19177c; } /* Variable */
    code span.vs { color: #4070a0; } /* VerbatimString */
    code span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
  <link rel="stylesheet" href="/style.css">
  <!--[if lt IE 9]>
    <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
  <a href="/">home</a>
<h1 id="a-lab-2-code-walkthrough">A Lab 2 Code Walkthrough</h1>
<p>In Lab 2 we’ll be stepping our programming game up a bit. In this writeup I’ll walk through the code that we’ll be using for the lab with the goal of making it less intimidating.</p>
<h2 id="part-1---fading">Part 1 - Fading</h2>
<p>This first part of the lab uses an example program that can be found in <code>File -&gt; Examples -&gt; Basics -&gt; Fade</code>. The preamble ought to be reasonably familiar from your lab 1 experience. The author starts by defining some variables and then moves on to setting their output pin to <code>OUTPUT</code> mode.</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode cpp"><code class="sourceCode cpp"><span id="cb1-1"><a href="#cb1-1"></a><span class="dt">int</span> led = <span class="dv">9</span>;</span>
<span id="cb1-2"><a href="#cb1-2"></a><span class="dt">int</span> brightness = <span class="dv">0</span>;</span>
<span id="cb1-3"><a href="#cb1-3"></a><span class="dt">int</span> fadeAmount = <span class="dv">5</span>;</span>
<span id="cb1-4"><a href="#cb1-4"></a></span>
<span id="cb1-5"><a href="#cb1-5"></a><span class="dt">void</span> setup() {</span>
<span id="cb1-6"><a href="#cb1-6"></a>  pinMode(led, OUTPUT);</span>
<span id="cb1-7"><a href="#cb1-7"></a>}</span></code></pre></div>
<p>Having done that there are some new things in the <code>loop</code> function. The <code>analogWrite</code> function is used to write a value between 0 and 255 inclusive to the LED pin. Under the hood the Arduino is using pulse width modulation to accomplish this. For all practical purposes though you can think of <code>0</code> being the same as <code>LOW</code> and <code>255</code> the same as <code>HIGH</code> from the first lab with the other values filling in the missing space.</p>
<p>A requirement for using <code>analogWrite</code> is that the pin that it is being used on is prefixed by a <code>~</code> symbol on your Arduino board. For example, if you take a look at your Arduino Uno from the top you’ll notice that the <code>8</code> just has a number while the <code>9</code> pin is written as <code>~9</code>. This means that pin 9 supports <code>analogWrite</code>.</p>
<p>Another funny looking part of the loop function is this:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode cpp"><code class="sourceCode cpp"><span id="cb2-1"><a href="#cb2-1"></a><span class="cf">if</span> (brightness &lt;= <span class="dv">0</span> || brightness &gt;= <span class="dv">255</span>) {</span>
<span id="cb2-2"><a href="#cb2-2"></a>  fadeAmount = -fadeAmount;</span>
<span id="cb2-3"><a href="#cb2-3"></a>}</span></code></pre></div>
<p>If you’ve never worked with the C++ language before the condition inside of our if statement might look a little strange. In a language like python it would <em>roughly</em> translate to something like this:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb3-1"><a href="#cb3-1"></a><span class="cf">if</span> brightness <span class="op">&lt;=</span> <span class="dv">0</span> <span class="kw">or</span> brightness <span class="op">&gt;=</span> <span class="dv">255</span>:</span>
<span id="cb3-2"><a href="#cb3-2"></a>  fadeAmount <span class="op">=</span> <span class="op">-</span>fadeAmount</span></code></pre></div>
<p>In this case the <code>||</code> symbol means “or”. If either side of the “conditional statement” evaluate to true the “body” of the if statement will be evaluated. I have attempted to draw a picture of this with my keyboard below.</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode cpp"><code class="sourceCode cpp"><span id="cb4-1"><a href="#cb4-1"></a><span class="co">//  /-------&gt;  conditional statement</span></span>
<span id="cb4-2"><a href="#cb4-2"></a><span class="co">//  |    |</span></span>
<span id="cb4-3"><a href="#cb4-3"></a><span class="co">//  v    v</span></span>
<span id="cb4-4"><a href="#cb4-4"></a><span class="cf">if</span> (a || b) {</span>
<span id="cb4-5"><a href="#cb4-5"></a>    <span class="dv">36</span> + <span class="dv">6</span>;  <span class="co">// &lt;-- body</span></span>
<span id="cb4-6"><a href="#cb4-6"></a>}</span></code></pre></div>
<h2 id="part-2---fading-3-leds">Part 2 - Fading 3 LEDs</h2>
<p>This part of the lab largely builds upon concepts that we have some grasp of from the fist lab and the fade example. The code is long but if you tackle it in a reasonably slow fashion it might be readable.</p>
<p>There are two new concepts introduced here that we have not seen in previous labs. The first is writing to the serial console. Lucky for you we already have <a href="/1-thursday.html">a tutorial</a> on that. The second is the introduction of a new <code>const</code> keyword in the preamble.</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode cpp"><code class="sourceCode cpp"><span id="cb5-1"><a href="#cb5-1"></a><span class="at">const</span> <span class="dt">int</span> redPin = <span class="dv">9</span>;</span></code></pre></div>
<p>What this keyword does is prevent you from accidentally changing the <code>redPin</code> variable later in your code. For example, doing something like the following would result in an error:</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode cpp"><code class="sourceCode cpp"><span id="cb6-1"><a href="#cb6-1"></a><span class="dt">void</span> loop() {</span>
<span id="cb6-2"><a href="#cb6-2"></a>  redPin = sin(redPin)</span>
<span id="cb6-3"><a href="#cb6-3"></a>}</span></code></pre></div>
<p>When you are writing code for your Arduino you may want to consider prefixing values that you do not expect to change with this <code>const</code> keyword.</p>
<h2 id="intermission">Intermission</h2>
<p>If you’re feeling overwhelmed by all these new programming things please do not. Working with Arduinos is a genuinely difficult task. To help put into perspective how hard what you’re doing is, <a href="https://en.cppreference.com/w/cpp/language/cv">here</a> is the official documentation about the <code>const</code> keyword.</p>
<p>By using it in your program you are doing something complicated and cool. Congrats.</p>
<h2 id="part-3---serial-communications">Part 3 - Serial Communications</h2>
<p>This part of the lab is a pretty reasonable extension of the last part that adds some user interaction into the mix. If you have not I’d recommend understanding our serial communications <a href="/1-thursday.html">tutorial</a> before tackling this section of the lab.</p>
<p>The big new part of this code is the following conditional statement in the <code>loop</code> function which we’ll walk through.</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode cpp"><code class="sourceCode cpp"><span id="cb7-1"><a href="#cb7-1"></a>  <span class="co">// clear the string</span></span>
<span id="cb7-2"><a href="#cb7-2"></a>  memset(serInString, <span class="dv">0</span>, <span class="dv">100</span>);</span>
<span id="cb7-3"><a href="#cb7-3"></a>  <span class="co">//read the serial port and create a string out of what you read</span></span>
<span id="cb7-4"><a href="#cb7-4"></a>  readSerialString(serInString);</span>
<span id="cb7-5"><a href="#cb7-5"></a></span>
<span id="cb7-6"><a href="#cb7-6"></a>  colorCode = serInString[<span class="dv">0</span>];</span>
<span id="cb7-7"><a href="#cb7-7"></a>  <span class="cf">if</span>( colorCode == <span class="ch">&#39;r&#39;</span> || colorCode == <span class="ch">&#39;g&#39;</span> || colorCode == <span class="ch">&#39;b&#39;</span> ) {</span>
<span id="cb7-8"><a href="#cb7-8"></a>    colorVal = atoi(serInString+<span class="dv">1</span>);</span>
<span id="cb7-9"><a href="#cb7-9"></a>    Serial.print(<span class="st">&quot;setting color &quot;</span>);</span>
<span id="cb7-10"><a href="#cb7-10"></a>    Serial.print(colorCode);</span>
<span id="cb7-11"><a href="#cb7-11"></a>    Serial.print(<span class="st">&quot; to &quot;</span>);</span>
<span id="cb7-12"><a href="#cb7-12"></a>    Serial.print(colorVal);</span>
<span id="cb7-13"><a href="#cb7-13"></a>    Serial.println();</span>
<span id="cb7-14"><a href="#cb7-14"></a>    serInString[<span class="dv">0</span>] = <span class="dv">0</span>;                   <span class="co">// indicates we&#39;ve used this string</span></span>
<span id="cb7-15"><a href="#cb7-15"></a>    <span class="cf">if</span>(colorCode == <span class="ch">&#39;r&#39;</span>)</span>
<span id="cb7-16"><a href="#cb7-16"></a>      analogWrite(redPin, colorVal);</span>
<span id="cb7-17"><a href="#cb7-17"></a>    <span class="cf">else</span> <span class="cf">if</span>(colorCode == <span class="ch">&#39;g&#39;</span>)</span>
<span id="cb7-18"><a href="#cb7-18"></a>      analogWrite(greenPin, colorVal);</span>
<span id="cb7-19"><a href="#cb7-19"></a>    <span class="cf">else</span> <span class="cf">if</span>(colorCode == <span class="ch">&#39;b&#39;</span>)</span>
<span id="cb7-20"><a href="#cb7-20"></a>      analogWrite(bluePin, colorVal);</span>
<span id="cb7-21"><a href="#cb7-21"></a>  }</span></code></pre></div>
<p>The first question that you might ask about this is what <code>serInString</code> is. It is defined in the preamble as follows:</p>
<div class="sourceCode" id="cb8"><pre class="sourceCode cpp"><code class="sourceCode cpp"><span id="cb8-1"><a href="#cb8-1"></a><span class="dt">char</span> serInString[<span class="dv">100</span>];</span></code></pre></div>
<p>This sort of syntax can be hard to read so lets take it left to right.</p>
<ol type="1">
<li>A <code>char</code> is much like an <code>int</code> except that instead of holding a number it holds a letter.</li>
<li><code>serInString</code> is a variable.</li>
<li><code>[100]</code> indicates that whatever precedes it is in fact a list of 100 of those things. The practical impact of this is to say that <code>serInString</code> is no regular <code>char</code> but is instead a list of <code>100</code> characters.</li>
<p>So, in summary, <code>serInString</code> is a list that has space for 100 characters.</p>
<p>Returning to our earlier code block we see that it begins with a call to <code>memset(serInString, 0, 100)</code>. <code>memset</code> is a function that takes a list and fills the first N items with a value. In this case we are asking <code>memset</code> to fill <code>serInString</code> with one hundred zeros.</p>
<p>In programming the character <code>0</code> is a special character that essentially means “nothing to see here” so this call to <code>memset</code> results in <code>serInString</code> being reset to a whole lot of “nothing to see here.”</p>
<p>Once <code>serInString</code> is reset we make a call to <code>readSerialString</code> which fills it up with whatever data the user has sent to us over the serial port. You’ll likely want to take a look at that function. The new part there is the usage of the <code>strArray[i]</code> expression. This expression yields the i-th value from <code>strArray</code>. For example:</p>
<pre><code>strArray = [1, 2, 3]</code></pre>
<pre><code>strArray[0] =&gt; 1
strArray[1] =&gt; 2
strArray[2] =&gt; 3</code></pre>
<p>Notice that the “first” item in the list is actually accessed by asking for <code>strArray[0]</code>. Forgetting about this is liable to result in some fun bugs later in the semester.</p>
<p>Returning to our <code>loop</code> function, we expect messages in the form <code>&lt;colorLetter&gt;&lt;intensity&gt;</code> so once we have the information that the user sent over we check if the <code>colorLetter</code> input is one of <code>r</code>, <code>g</code>, or <code>b</code>.</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode cpp"><code class="sourceCode cpp"><span id="cb11-1"><a href="#cb11-1"></a><span class="cf">if</span>( colorCode == <span class="ch">&#39;r&#39;</span> || colorCode == <span class="ch">&#39;g&#39;</span> || colorCode == <span class="ch">&#39;b&#39;</span> ) {</span></code></pre></div>
<p>If it is we then need to read the intensity value and set the appropriate LED. To do this we use the <code>atoi</code> function. <code>atoi</code> is a strangely named function which takes a list of characters and converts them into an integer if possible. For example:</p>
<pre><code>atoi([&#39;1&#39;, &#39;2&#39;, &#39;3&#39;])  =&gt; 123
atoi([&#39;1&#39;, &#39;2&#39;])       =&gt; 12</code></pre>
<p>You’ll notice that we call <code>atoi(serInString+1)</code> and not <code>atoi(serInString)</code>. This is because the first item in <code>serInString</code> is a letter and not a number. In order to get the number part of the input we need to move the list over to the right by one.</p>
<pre><code>[r, 1, 2, 3] + 1 =&gt; [1, 2, 3]</code></pre>
<p>Having read in the desired brightness with <code>atoi</code> the rest of the code is very close to what we’ve seen before. Nice work making it this far.</p>