<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sam Bald on Medium]]></title>
        <description><![CDATA[Stories by Sam Bald on Medium]]></description>
        <link>https://medium.com/@sam.bald?source=rss-a28b543805d9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*gWRQI90z6osLtD_s.</url>
            <title>Stories by Sam Bald on Medium</title>
            <link>https://medium.com/@sam.bald?source=rss-a28b543805d9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 21:38:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sam.bald/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Arduino & Processing]]></title>
            <link>https://medium.com/@sam.bald/arduino-processing-3de6655e878e?source=rss-a28b543805d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3de6655e878e</guid>
            <category><![CDATA[arduino]]></category>
            <category><![CDATA[iot]]></category>
            <dc:creator><![CDATA[Sam Bald]]></dc:creator>
            <pubDate>Sun, 09 Apr 2017 06:55:16 GMT</pubDate>
            <atom:updated>2017-04-09T07:37:44.140Z</atom:updated>
            <content:encoded><![CDATA[<p>An Introduction to the Arduino Platform</p><p><a href="https://medium.com/@sam.bald/arduino-whats-it-good-for-61373e6e4aa0">Part 1</a> | <a href="https://medium.com/@sam.bald/arduino-advancing-to-analog-1a6babfe236b">Part 2</a> | <a href="https://medium.com/@sam.bald/arduino-communicating-with-other-devices-b4fc204cb63c">Part 3</a> | <strong><em>Part 4</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*0o6BwAlM7aSYIAh0ikLZ4A.png" /><figcaption>By Processing Foundation [GPLv2 (<a href="https://www.gnu.org/licenses/old-licenses/gpl-2.0.html">https://www.gnu.org/licenses/old-licenses/gpl-2.0.html</a>)], via Wikimedia Commons</figcaption></figure><p>In my <a href="https://medium.com/@sam.bald/arduino-communicating-with-other-devices-b4fc204cb63c">last post</a> I demonstrated how you can use the Arduino to communicate with other devices. This time we’ll learn how to communicate bidirectionally with a computer program. In other words, we’ll write a piece of software that will control the Arduino, and at the same time use the Arduino to control the software.</p><h3>What is Processing?</h3><p>Processing is a programming language geared towards artists and learning how to code in a more visual way. In fact, the Processing language and IDE was used as a foundation to create the Arduino platform. As such, they share a lot of similarities, and lend themselves well to communication between each other.</p><p>Just like Arduino, each program is called a “sketch”. The structure of a sketch is similar as well. You begin with your declarations and a <strong>setup()</strong> function. There is a looping function as well which works just like <strong>loop()</strong>, except you call it <strong>draw()</strong>.</p><h3>What We’re Building</h3><p>To start off, we’ll play an MP3 in Processing. The amplitude of the song (how loud it is at any given moment) will be sent to the Arduino, which will use that value to control the brightness of an LED. In turn, the position of a knob will control the current position within the song, allowing you to jump to different points.</p><h3>The Arduino Code</h3><h4>Declarations</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*zViFp_o_BkpijrSBwG9FBA.png" /></figure><p>First we declare which pins our LED and knob are connected to. Of course, you can choose any pins you like, as long as the LED is connected to one of the PWM-enabled pins so we can control the brightness.</p><p>Rather than constantly updating the knob’s position, we only care if it’s been moved, so we need variables to store both the <em>current</em> position as well as the <em>previous</em> position.</p><p>Lastly, for our purposes it will be easiest if we send the desired song position as a <strong>byte </strong>data type, which can hold a number between 0 and 255.</p><h4>Setup Code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*z6jnhDXLx8ksrIEpHk5W-g.png" /></figure><p>The setup code is pretty straightforward: first, serial communication is enabled and the LED pin is set to output mode. Then the “previous” knob value is set to match the current knob value. This prevents the song position from immediately jumping to whatever the knob happens to be set to at the very start — naturally, we would at least want the song to <em>start</em> at the beginning.</p><h4>Looping Code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*cKqza75AUtbyVgzFjIm-ow.png" /></figure><p>To start off the <strong>loop()</strong> function, we immediately read the position of the knob. Next, we convert that to a value between 0 and 127 and send it to the Processing sketch:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*3nSxZbZuxOwWbejP6FngMw.png" /></figure><p>To prevent any potential error in the knob reading we use an “<strong>if</strong>”<strong> </strong>statement to make sure that the value has changed by at least 5 (which, in the range of 0 to 1023 that <strong>analogRead()</strong> returns, is still miniscule).</p><p>Then we use the <strong>map()</strong> function to convert the knob value to a number between 0 and 127. Remember that we’re storing the song position in a <strong>byte</strong> data type, which can store values between 0 and 255. The reason we’re only using half that range is that the <strong>byte</strong> data type in the Processing language actually stores values between -128 and 127 (we could still use the full range, but the later code should be easier to understand this way).</p><p>After that, we send the song position to the Processing sketch with the <strong>Serial.write()</strong> function and update the “previous” knob value.</p><p>Now that the knob is taken care of, we can work out the brightness of the LED:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*GdOm1gmNGcNyOne7LMVgag.png" /></figure><p>First we check whether there’s any input coming from the Processing sketch. <strong>Serial.available()</strong> returns the number of bytes that have been received from the serial port since the last reading, so if that number is above 0, we’ve received input.</p><p>In the Processing code we’ll make sure that the value we’re reading here is already in the range of 0 to 255, so all we have to do is send that value directly to the LED. Lastly, to allow the analog-to-digital converter in the Arduino to stabilize before the next call to <strong>analogRead()</strong> we add a 2-millisecond delay (otherwise we might run into problems) and then close the <strong>loop()</strong> function. That’s it for the Arduino code!</p><h3>The Processing Code</h3><h4>Declarations</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*YmOesm_j12xM45RyoMY99A.png" /></figure><p>There’s a little more to the declarations here. To work with the serial communication and sound-related functions, we have to import their libraries. Then we declare objects to hold the port the Arduino is connected to, the MP3 file, and the amplitude readings. Lastly, we declare variables to hold the song position and total length, as well as the brightness of the LED from 0 to 255 (why this is declared as a <strong>float</strong> I’ll explain later).</p><h4>Setup Code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*xCNDrrHeAkWtiBXCg-BJ4g.png" /></figure><p>Before we can send any data to the Arduino, we need to know which port it’s connected to. One way to find this out is in the Arduino IDE: by clicking the <strong>Tools</strong> menu, if the board is connected the name of the port should be displayed next to the <strong>Port</strong> menu item. In the setup code here, <strong>Serial.list()</strong> returns an array of all the available serial ports on the system, and <strong>println()</strong> will print them to the console. In my case, the Arduino always connects to the “COM5” port, and <strong>Serial.list()</strong> shows that as the second element in the list.</p><p>To get a reference to the port, we create a new <strong>Serial</strong> object, which takes three parameters. The first parameter is typically always “<strong>this</strong>” (the explanation is a little complicated — if you’re curious, see <a href="http://stackoverflow.com/a/25283548">this answer</a>). The second parameter is the port you’d like to connect to. Use the <strong>Serial.list()</strong> function again and reference the element of the array that contains the correct port. Again, in my case it’s the second element, so I reference index 1. The last parameter is the desired bit rate to use for communication, which we’ve set as 9600 in the Arduino sketch, so we need to make sure we use the same value here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*opFIyYeBILF0pcuCzT1ZsA.png" /></figure><p>To complete the <strong>setup() </strong>function, we initialize a <strong>SoundFile</strong> object and give it the name of the MP3 file. The file referenced here needs to be stored inside a folder called “<strong>data</strong>” in the sketch’s directory.</p><p>In order to jump to a location in the song, we need to know the full length of the song, so we use the <strong>duration() </strong>function, which returns the total number of seconds as a decimal value. Then the <strong>play()</strong> function starts playing the song from the beginning.</p><p>To be able to get the amplitude later on, we need to initialize an <strong>Amplitude</strong> object, and use the <strong>input()</strong> function to pair it with the sound file. This code only works if you put it <em>after</em> the <strong>play()</strong> function.</p><h4>Looping Code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*_-eg6i2OM1WVTZqXOtnTAg.png" /></figure><p>To start the <strong>draw()</strong> function, we get the current amplitude of the song and send it to the Arduino. The <strong>analyze()</strong> function returns the amplitude as a decimal number between 0 and 1. Because we need this to be a value between 0 and 255, we convert this using the <strong>map()</strong> function, which works exactly like the same function in Arduino, except for one detail: rather than returning an <strong>int</strong> data type, it returns a decimal <strong>float</strong> value (this is why we declared the <strong>ledBrightness</strong> variable as a <strong>float</strong>).</p><p>We’ll run into some problems if we don’t convert the decimal value to an integer at this point, so we use the <strong>int()</strong> function to convert from <strong>float</strong> to <strong>int</strong>, and then use <strong>Serial.write()</strong> to send the value to the Arduino.</p><p>Those two lines are all we need to take care of the LED. The code to handle the knob is quite a bit more complicated though, so let’s take it a bit at a time.</p><p>There are a couple of challenges we’ll have to take into account. First off, it takes almost half a second to jump to another position in the song. This becomes a problem when you take into account the fact that the Arduino will be outputting a huge amount of values as we turn the knob. Even though we’re only outputting data when the position changes by at least 5, that’s still a range of over 200 values across the entire knob, which can be coming in very quickly depending on how much and how fast it’s turned. The program will normally jump to each one of those positions in sequence, one at a time, which could potentially take over a minute for a full sweep of the knob.</p><p>To handle that, rather than reading and processing every value one at a time, we can read all the values we’ve received since the last update into an array and only act on the most <em>recent</em> one, ignoring the rest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*2YApu-fs0t2WTiI19cjdFg.png" /></figure><p><strong>Serial.available()</strong> works just like it did in the Arduino sketch and returns the number of bytes received since the last update, which we use to check whether we’ve received any data. The next line initializes an array that will store the bytes we receive from the Arduino. The other key function here is <strong>readBytes()</strong>. It works differently depending on the number and type of arguments you give it, but in this case we give it the array that we just initialized. This way it reads all the bytes we’ve received since the last reading and stores them each in the given array, and it returns the number of bytes received. If we subtract 1 from the number of bytes, we get the index of the last byte received, which we store in <strong>lastByteIndex</strong>.</p><p>Note the lack of a closing brace — we’re not done yet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*aGd554FUQjRqsE5zTUC3Zg.png" /></figure><p>The last byte received — which, if you’ll remember, will be a number between 0 and 127 — gets stored in the <strong>songPos</strong> variable. We then use <strong>map()</strong> to convert that range to a range between 0 and the length of the song, and pass the result to the <strong>SoundFile.jump()</strong> function, which will jump to that position in the song.</p><p>To finish off the sketch:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*VSl_0AbskoQ-Cu8tt_8EAQ.png" /></figure><p>For some reason, whenever you jump to another position, the pairing between the <strong>Amplitude</strong> object and the sound file is broken, so you have to reestablish that here. Another odd behaviour is that the <strong>SoundFile.jump()</strong> function doesn’t like getting repeatedly called again too soon before it finishes performing the jump, which tends to crash the program. For me, adding a delay of half a second kept it from crashing no matter how haphazardly I turned the knob— however, that number might vary depending on the system you’re running.</p><p>The two curly braces at the end close the “<strong>if</strong>” statement and the <strong>draw()</strong> function, which completes the Processing code.</p><h3>Running the Sketches</h3><p>Make sure the Arduino code is uploaded to the board, and then go ahead and start the Processing sketch. You should see the LED happily flickering along to the music, and turning the knob — although it might feel rather choppy because of the speed of the <strong>jump()</strong> function and the delay we built in — should accurately jump to any position in the song. Mission accomplished!</p><p>Using the same principles, you could change the code to control the playback speed instead of the song position, and you could hook up an array of LEDs rather than a single one to create a more traditional-looking sound metre.</p><p>Check out the <a href="https://processing.org/">Processing site</a> to find out more about this versatile language. They have a very extensive set of examples you can run online to see what else is possible with Processing alone. Of course, using it together with an Arduino opens up the possibility for much more interesting applications, but that’s up to you (or whatever examples and tutorials you can find on the Internet — of which there are many)!</p><p>I hope this series of posts has served as a helpful introduction to the Arduino platform. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3de6655e878e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arduino: Communicating With Other Devices]]></title>
            <link>https://medium.com/@sam.bald/arduino-communicating-with-other-devices-b4fc204cb63c?source=rss-a28b543805d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4fc204cb63c</guid>
            <category><![CDATA[arduino]]></category>
            <category><![CDATA[iot]]></category>
            <dc:creator><![CDATA[Sam Bald]]></dc:creator>
            <pubDate>Sat, 18 Mar 2017 22:36:08 GMT</pubDate>
            <atom:updated>2017-04-09T07:01:34.002Z</atom:updated>
            <content:encoded><![CDATA[<h4>An Introduction to the Arduino Platform</h4><p><a href="https://medium.com/@sam.bald/arduino-whats-it-good-for-61373e6e4aa0">Part 1</a> <strong>|</strong> <a href="https://medium.com/@sam.bald/arduino-advancing-to-analog-1a6babfe236b">Part 2</a> <strong>|</strong> <strong><em>Part 3 | </em></strong><a href="https://medium.com/@sam.bald/arduino-processing-3de6655e878e">Part 4</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*9Lh8b_LhuoJRpdh3.jpg" /></figure><p>While an Arduino board and an electronic circuit alone can have amazing functionality, sending messages to other devices can unlock a whole new world of functionality. Arduino boards include the capability to send and receive data through the USB port to a computer, as well as through digital pins 0 and 1.</p><h3>Sending Text</h3><p>The Arduino has the capability to output data in either a binary format, or more simply, as a string of plain text. Text strings are usually useless to other devices, so they are mostly used to send data to the Arduino IDE for analysis or debugging, which itself can be very useful.</p><p>Text output is sent using the <strong>Serial.print() </strong>and <strong>Serial.println() </strong>functions. Like most other languages, these work identically to each other except for the fact that <strong>println()</strong> ends the text with a new line.</p><p>To enable data input and output, you must first activate serial communication as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*ySGtQuN4E8GrkLQRUbFv5g.png" /></figure><p>The <strong>Serial.begin() </strong>function is typically called from within the <strong>setup() </strong>function, along with any other setup code that’s required. The number given as an argument specifies the desired bit rate for communication. The number you chose here essentially doesn’t matter, but it’s very important that you select the same number within the Serial Monitor in the Arduino IDE (which we’ll talk about shortly). 9600 is the default value in the Serial Monitor, so it’s good number to go with for now.</p><h4>Example: Reading a Knob</h4><p>Imagine that for this example we have a knob connected to analog input A0. As covered in <a href="https://medium.com/@sam.bald/arduino-advancing-to-analog-1a6babfe236b">part 2</a> of this series, calling <strong>analogRead() </strong>on that input will return a value between 0 and 1023, depending on the position of the knob. Now, within the <strong>loop() </strong>function you can print the value of the knob as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*z_V6YMP-BVYAa4dinsoFdA.png" /></figure><p>First, the value of the knob is stored in <strong>knobValue</strong>. Then we print a string of text followed by the knob value. Notice that we’re using <strong>print()</strong> for the first part of the line to ensure that the <strong>println()</strong> statement continues on the same line (string concatenation is slightly more complicated here than other programming languages, so not worth using in this case).</p><p>To see the output of this code, run the program on the Arduino and click the <strong>Serial Monitor </strong>icon in the upper-left corner of the IDE (or select it from the <strong>Tools</strong> menu). Now if you move the knob you should see a constantly updating series of strings like this (notice the “9600 baud” setting in the lower-right, as mentioned earlier):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ly0hQQy5uGCeJA8eujSqZQ.png" /></figure><p>Another interesting tool in the <strong>Tools</strong> menu is the <strong>Serial Plotter</strong>. This will take any numerical value sent from the Arduino and plot it on a graph in real-time, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L63-VIWPcUuSQ8Gpim_yNA.png" /></figure><p>This will work for multiple values at the same time and will graph each value as a separate line.</p><h3>Sending Binary Data</h3><p>If you want to work with other devices or software, you will most likely need to work with binary data rather than plain text. For this, we can use the <strong>Serial.write()</strong> function. It can take an integer or hexadecimal value representing a single byte as an argument, or it can take a string or array and convert them in to a series of bytes. Viewing data sent with the <strong>write()</strong> function in the <strong>Serial Monitor/Plotter</strong> is unlikely to work well, and so it typically only used to communicate with other devices and software.</p><h4>The MIDI Protocol</h4><p>As an example, let’s send a series of <strong>MIDI </strong>messages to an electric piano. MIDI is a protocol used by electronic musical instruments and accessories to send messages between each other. It allows a device to switch notes on or off, change effects, and manipulate sounds in many other ways. In this case will will repeatedly cycle through all the notes on the keyboard.</p><p>Each MIDI message is composed of two parts: a <strong>command byte</strong>, followed by one or more <strong>data bytes</strong>. The command byte specifies the type of message being sent, and the data bytes complete the message by specifying the exact instruction to send. To differentiate command bytes from data bytes, command bytes are always represented as a number from 128 to 255, and data bytes are a number from 0 to 127 (in other words, the first bit in a command byte is “1”, and the first bit in a data byte is “0”). Although these are normally represented in hexadecimal format, it won’t matter to us, so for the sake of simplicity we’ll use integers.</p><p>The messages we will be sending are <strong>“note on”</strong> and <strong>“note off”</strong>. “Note on” simply plays a specific note, and “note off” stops playing that note. You can send a note to one of 16 channels, and you must specify which one of those channels you wish to send to. In our case, it doesn’t matter which channel we send to, but let’s use channel 1.</p><h4>The Code</h4><p>To start off, we enable serial communication as usual:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*qaggYZpzLCFO8jsncriZWA.png" /></figure><p>We’re using a bit rate of 31,250 simply because that’s the standard bit rate specified in the MIDI protocol, although it shouldn’t matter if we use a different bit rate.</p><p>Next, we can define a <strong>noteOn()</strong> and <strong>noteOff() </strong>function. Like any other programming language, we’re not just limited to the standard <strong>setup()</strong> and <strong>loop()</strong> functions; we can define our own.</p><p>A “note on” message is comprised of three parts:</p><ul><li>The “note on” control byte, which is <strong>144</strong> for channel one.</li><li>A specific note from <strong>0 </strong>to<strong> 127</strong>.</li><li>A velocity from <strong>0 </strong>to <strong>127</strong>, which specifies how hard the key was pressed, and usually corresponds to the loudness of the note.</li></ul><p>Similarly, a “note off” message is comprised of:</p><ul><li>The “note off” control byte, which is <strong>128</strong> for channel one.</li><li>A specific note from <strong>0 </strong>to<strong> 127</strong>.</li><li>A velocity from <strong>0</strong> to <strong>127</strong>, which specifies how quickly the key was released. This is rarely used, and most devices that send the “note off” message just use the number <strong>64</strong> no matter what.</li></ul><p>We can write the <strong>noteOn()</strong> function like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*Srbqa_DYxI5e0gJybUFlWA.png" /></figure><p>This sends the “note on” control byte 144, which is followed by a variable note number and a velocity of 127.</p><p>For the <strong>noteOff()</strong> function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*BHhgd07oiQmzTSeKO2r9mQ.png" /></figure><p>This sends the “note off” control byte 128, which is followed by a variable note number and a velocity of 64.</p><p>Now for the main part of the code, the <strong>loop()</strong> function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*CyaQOsDL3ENJxOInXI2frw.png" /></figure><p>Here we create a <strong>for</strong> loop to cycle through all the notes from 0 to 127. For each note, we call the <strong>noteOn()</strong> function to play the note, pause for 250 milliseconds, and then turn off the note with <strong>noteOff()</strong>.</p><h4>The Hardware</h4><p>On the hardware side, the Arduino connects to a female MIDI jack. Rather than using the USB cable to send data, it is sent through <strong>digital pin 1</strong>, which doubles as a data output pin. So far in this series I haven’t talked much about wiring in order to focus on the programming side, but if you’re interested in seeing how everything is connected, this is a diagram of a <a href="https://www.arduino.cc/en/Tutorial/Midi">similar example</a> from the official Arduino website:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/0*yFTFDTRFZa_RNj2Q.png" /><figcaption>By Arduino (<a href="https://www.arduino.cc/en/Tutorial/Midi">https://www.arduino.cc/en/Tutorial/Midi</a>)</figcaption></figure><p>As soon as you have everything connected and powered, the piano should immediately start playing all the notes. And that’s all there is to it! You can experiment with many different MIDI messages. The MIDI association provides a handy set of <a href="https://www.midi.org/specifications/category/reference-tables">reference tables</a> you can use as a guide.</p><p>Of course, there is an endless variety of other devices you can communicate with, and each one will send and receive different kinds of messages. The <strong>Processing</strong> programming language is a popular method for communication between an Arduino and a computer. Take a look at the <a href="https://www.arduino.cc/en/Tutorial/BuiltInExamples#communication">communication tutorials</a> on the Arduino web site to learn more about this and other methods for serial communication, or continue on to part 4!</p><p><a href="https://medium.com/@sam.bald/arduino-processing-3de6655e878e"><em>Continue to part 4: </em><strong><em>Arduino &amp; Processing</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4fc204cb63c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arduino: Advancing to Analog]]></title>
            <link>https://medium.com/@sam.bald/arduino-advancing-to-analog-1a6babfe236b?source=rss-a28b543805d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a6babfe236b</guid>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[arduino]]></category>
            <dc:creator><![CDATA[Sam Bald]]></dc:creator>
            <pubDate>Thu, 23 Feb 2017 03:59:23 GMT</pubDate>
            <atom:updated>2017-04-09T06:58:33.458Z</atom:updated>
            <content:encoded><![CDATA[<h4>An Introduction to the Arduino Platform</h4><p><a href="https://medium.com/@sam.bald/arduino-whats-it-good-for-61373e6e4aa0">Part 1</a> <strong>|</strong> <strong><em>Part 2 | </em></strong><a href="https://medium.com/@sam.bald/arduino-communicating-with-other-devices-b4fc204cb63c">Part 3</a> <strong>|</strong> <a href="https://medium.com/@sam.bald/arduino-processing-3de6655e878e">Part 4</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*14ZRj3U3Si3n6hYR.jpg" /></figure><p>In my <a href="https://medium.com/@sam.bald/arduino-whats-it-good-for-61373e6e4aa0">last post</a> I introduced the Arduino platform and demonstrated a very simple project using the digital pins. This time I’ll delve a little deeper into some specific details and demonstrate a slightly more advanced project using the analog input pins.</p><h3>Breakdown of the Board</h3><p>The Arduino board has three main sections of pins. The digital pins (at the top of the diagram below) can each be set as either input or output pins. As an input pin, they can tell you whether they’re receiving power or not (although not <em>how much</em>). As an output pin, they can only output full voltage (5 volts) or none at all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*iWeZOzxvMboOrsqMfVOaNQ.png" /><figcaption>By Arduino (arduino.cc) [CC BY-SA 3.0 (<a href="http://creativecommons.org/licenses/by-sa/3.0">http://creativecommons.org/licenses/by-sa/3.0</a>)], via Wikimedia Commons</figcaption></figure><p>In contrast, the analog input pins function the same way as the digital input pins, except they give you a value between 0 and 1023 that corresponds to the power level that they receive. These can be useful to receive input from components such as knobs or, as we’ll be using later, photoresistors (a kind of light sensor).</p><p>Beside the analog pins are the power pins. The only pins here that we care about at this point are the <strong>5V </strong>and <strong>GND </strong>pins. If you’d like to understand this in more depth, I’d suggest looking up the basics of electronic circuits, but for now just know that every electronic component has at least one connection going to a power source (the “positive” end) and another going to “ground” (the “negative” end). The <strong>5V </strong>pin outputs full voltage just like the digital output pins do, and would be connected to the positive end of a component. The <strong>GND </strong>pin acts as the ground, and would be connected to the negative end of a component. Notice that there is also a ground pins next to the digital pins.</p><h4>Pulse Width Modulation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*WRADJFM_aeYvPOc7.gif" /><figcaption>By The arduino.cc team (<a href="http://arduino.cc/it/Tutorial/PWM">http://arduino.cc/it/Tutorial/PWM</a>) [CC BY-SA 3.0 (<a href="http://creativecommons.org/licenses/by-sa/3.0">http://creativecommons.org/licenses/by-sa/3.0</a>)], via Wikimedia Commons</figcaption></figure><p>One of the limiting factors of the digital pins is that they can only output an “on” or “off” value. This means if you want to, for example, have an LED repeatedly fade in and out, it would seem impossible. However, if you can switch the LED on and off rapidly enough that the human eye can’t perceive the blinking, you can essentially fake different brightness values. A 50% brightness value can be achieved by switching the light on and off at an equal rate, or a 25% brightness value can be achieved by having the light switched on only 25% of the time. This is the concept of pulse width modulation (PWM), and is available to every digital pin that has a “~” symbol next to it. I’ll demonstrate this in the example below.</p><h3>Example: Ambient Light-Sensitive LED</h3><p>In this example, we’ll connect an LED and a photoresistor to the Arduino board. A photoresistor responds to the amount of light it receives by blocking the current of electricity running through it. The less light it receives, the less electricity it allows through, and vice versa. Our aim will be to have the LED shine brighter in brighter surroundings, and darker in darker surroundings. The LED will be connected to digital pin 13, and the photoresistor will be connected to analog input pin 0.</p><p>To start off, let’s declare our variables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*KLLzji4RI1m0GtwC7DrSrQ.png" /></figure><p>The first two lines allow us to later refer to the digital pin 13 as <strong>ledPin</strong>, and analog pin A0 as <strong>sensorPin</strong>, just for clarity. Next, <strong>sensorValue</strong> will store the reading of the photoresistor, and <strong>ledVal</strong> will store the value to be sent to the LED pin.</p><p>Next, our setup code is as simple as it gets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*m3TpL5xeVLWmCRbDLvFmRQ.png" /></figure><p>This simply sets the LED pin to be in “output” mode. And finally, the interesting part:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*9naP0SCHA8Df6_7TcXkLQw.png" /></figure><p>The first line in the function uses the <strong>analogRead</strong> function to read the value from the pin the photoresistor is connected to, and stores it in <strong>sensorVal</strong>. We can’t output that value to the LED pin, because <strong>analogRead </strong>stores values from 0 to 1023, and <strong>analogWrite</strong> (the function used to send values to the PWM digital pins) sends values from 0 to 255. So, the <strong>map</strong> function on the second line converts the larger range to the smaller range. The first argument specifies the initial value to convert, the second and third arguments specify the lower and upper bounds of the input value, and the fourth and fifth arguments specify the lower and upper bounds of the output value. So, a reading of 1023 should return 255, a halfway reading of 512 should return 128, and so on.</p><p>Next, the <strong>analogWrite</strong> function takes the new value stored in <strong>ledValue</strong> and sends it to the LED pin, causing it to shine brightly or darkly depending on the environment. And lastly, the last line simply limits the frequency of updates to once every 10 milliseconds.</p><h4>Alternative Mappings</h4><p>Rather than using the <strong>map</strong> function, we could have simply divided the sensor value by four to get the desired value. However, the <strong>map</strong> function allows for other scenarios — you can switch the last two arguments around the get the LED to respond in the opposite way: brighter for darker rooms, and darker for brighter rooms. Or, perhaps the sensor will never experience a pitch-black room, in which case you could change the range from 0–1023 to something like 100–1023. Overall, this function allows for a lot of flexibility.</p><p>Armed with only the few functions covered in this and my last post, there are already a surprising amount of interesting contraptions that can be built. And while I’ve only focused on the Arduino UNO board, there are a multitude of different Arduino boards with different pin layouts, faster processors or smaller form factors. Check out the <a href="https://www.arduino.cc/">Arduino site</a> to learn more!</p><p><a href="https://medium.com/@sam.bald/arduino-communicating-with-other-devices-b4fc204cb63c"><em>Continue to part 3: </em><strong><em>Communicating With Other Devices</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a6babfe236b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arduino: What’s It Good For?]]></title>
            <link>https://medium.com/@sam.bald/arduino-whats-it-good-for-61373e6e4aa0?source=rss-a28b543805d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/61373e6e4aa0</guid>
            <dc:creator><![CDATA[Sam Bald]]></dc:creator>
            <pubDate>Sat, 28 Jan 2017 21:50:38 GMT</pubDate>
            <atom:updated>2017-04-09T06:58:10.092Z</atom:updated>
            <content:encoded><![CDATA[<h4>An Introduction to the Arduino Platform</h4><p><strong><em>Part 1 | </em></strong><a href="https://medium.com/@sam.bald/arduino-advancing-to-analog-1a6babfe236b">Part 2</a> <strong>| </strong><a href="https://medium.com/@sam.bald/arduino-communicating-with-other-devices-b4fc204cb63c">Part 3</a> <strong>|</strong> <a href="https://medium.com/@sam.bald/arduino-processing-3de6655e878e">Part 4</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*AvquwL1ynmBUVKwugvza3A.jpeg" /><figcaption>Source: <a href="http://www.arduino.org/products/boards/arduino-uno">http://www.arduino.org/products/boards/arduino-uno</a></figcaption></figure><p>What is the Arduino platform, and why is it so great? If I could boil the answer down to one sentence it would be this: Arduino makes building cool electronic gadgets <em>easy</em>.</p><p>What is it really, though? Basically, it’s a tiny computer called a microcontroller. A microcontroller is an extremely basic computer that can be used as a part of an electronic circuit so it can control the other components it’s connected to. The key is that it’s <em>programmable</em>. You can program instructions onto it, and based on those instructions it will control the circuit accordingly. For example, you can do something as simple as blinking an LED in a certain pattern, or something as complex as controlling a robot.</p><p>Microcontrollers have already been around for a long time, though. What makes the Arduino so special is the entire Arduino <em>platform</em>. It’s not just a microcontroller. On the hardware side, Arduino boards combine the microcontroller with a set of output pins to send power to other electronic components, and a set of input pins to read power levels from other devices. On top of that, it comes with a convenient USB input as an easy way to send programming instructions and power the board. There’s a little more to the board than that, but those are the important parts.</p><p>On the software side, the Arduino platform also consists of its own IDE, where you can program the board using a set of C/C++ functions. This is one of the biggest advantages, because typically you would program a microcontroller with a very low-level language, such as assembly. You don’t even need to learn the entire C language — you can already do a whole lot with just a few basic functions. You can also send data from the Arduino board to the IDE to, for example, see a live graph of the ambient noise level in a room. Sending a program to the board is as easy as clicking one button.</p><p>Altogether, what this means is that someone with no prior knowledge of electronics or programming can already start designing and building their own basic gadgets within just a few hours. And with some more training they can design things that would have otherwise required months or years of education. As a result, some of the more creative types who wouldn’t have otherwise invested the time and energy into learning about electronics and programming are now able to turn their ideas into reality.</p><p>Here are just a few examples of other people’s Arduino projects shared on Instructables.com:</p><ul><li><a href="http://www.instructables.com/id/Led-Cube-8x8x8/">LED Cube 8x8x8</a></li><li><a href="http://www.instructables.com/id/Twitter-Mood-Light-The-Worlds-Mood-in-a-Box/">Twitter Mood Light - The World&#39;s Mood in a Box</a></li><li><a href="http://www.instructables.com/id/turn-signal-biking-jacket/">turn signal biking jacket</a></li></ul><h3>A Simple Example</h3><p>To give you a rough idea of how an Arduino project is made, let me present a simple example (I’m assuming some basic programming experience). The wiring is as simple as possible: one side of an LED is connected to the pin labelled “13”, and the other side is connected to a “ground” pin. On the programming side, we’ll make the LED blink in a very specific pattern: 3 short blinks followed by a one second pause…and repeat, forever.</p><p>Every Arduino “sketch” (the Arduino IDE’s name for a project) typically contains three parts: declarations, a <strong>setup()</strong> function, and a <strong>loop()</strong> function. First you declare any variables and constants. Then you put any setup code that needs to run before anything else in the <strong>setup()</strong> function. The bulk of the code goes inside the <strong>loop()</strong> function, which will loop endlessly as long as the Arduino is powered.</p><p>Let’s start by declaring a constant:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*amQklquxlycS85P1NMvT-g.png" /></figure><p>This allows us to refer to pin 13 as “LED” for clarity. Next we write our setup code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*ODMcnOmUPyCmde7KljWWCA.png" /></figure><p>This designates the LED pin (13) as an output pin. Most of the Arduino board’s pins can be designated as either output or input pins. Output pins will send power through electronic components, and input pins will receive power levels that can be read by your code.</p><p>Then comes the real work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*wFJv3JpGNi3piaM2r9IG1w.png" /></figure><p>As I mentioned before, this code will repeat indefinitely. First we have a <strong>for</strong> loop set up to repeat 3 times. Inside the <strong>for</strong> loop we have two occurrences of the <strong>digitalWrite()</strong> function. This function takes two arguments: a pin, and one of two possible power levels. “HIGH” will send the maximum possible power level (5 volts), and “LOW” will send no power. These basically work as on and off switches (<strong>analogWrite()</strong> is a another available function, which allows you to send different power levels). We also have a <strong>delay()</strong> function, which will cause the program to pause for the specified amount of milliseconds.</p><p>So the entire sequence of the <strong>for</strong> loop is:</p><ol><li>Turn the LED on</li><li>Wait for 1/10th of a second</li><li>Turn the LED off</li><li>Wait for 1/10th of a second</li></ol><p>After this repeats three times, we call another <strong>delay()</strong> function that pauses the program for another second. Then, the entire <strong>loop()</strong> function repeats the whole thing again…and again, forever and ever.</p><p>The last step to get the code to run is to connect the Arduino to your computer with a USB cable and press the “Upload” button in the IDE. In a few seconds, your LED will start blinking in the exact pattern we specified!</p><h3>What’s Next</h3><p>That was, of course, about as simple as you can get with Arduino programming. You can take things to the next level by using input pins to make an interactive project that responds to input from, say, buttons, sound, or light. There are a plethora of projects posted on the Internet along with detailed instructions. And with a little bit of practice, you can start designing your own contraptions — and the possibilities are endless.</p><p><a href="https://medium.com/@sam.bald/arduino-advancing-to-analog-1a6babfe236b"><em>Continue to part 2: </em><strong><em>Advancing to Analog</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61373e6e4aa0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>