Arduino Class

Download as pdf or txt
Download as pdf or txt
You are on page 1of 61

instructables classes

ARDUINO CLASS
4 Lessons Beginner Level

This class will introduce you to the Arduino world. You'll learn the basics, build your rst project, and
so much more. Each lesson builds on your skills, infusing new knowledge and techniques along the
way.
You'll start simple with exercises that demonstrate basic breadboard wiring and coding inputs and
outputs. Then you'll level up to soldering and coding addressable NeoPixel LED strip and start
planning your own projects with your fun new hobby.
This class will launch your Arduino journey and give you the skills and con dence to take on almost
any Arduino project you may nd or create in the future.
Wa nt t o s e e a n Arduino proje ct ha ppe n in re a l-t ime ? Check out a full video of my
webinar on creating an Easy In nity Mirror, on the Instructables Facebook page!
If you've made an awesome project that uses Arduino, try writing an Instructable about it and enter
it in an Instructables contest to win some great prizes!

Class Author:
bekathwia
Becky Stern has authored hundreds of tutorials in everything from wearable electronics to knitting. Before joining Instructables as
a content creator, Becky worked as a senior video producer for MAKE Magazine and then as the director of wearable electronics
at Adafruit Industries. She lives in New York City and enjoys riding her motorcycle, making YouTube videos, and collecting new
hobbies. Her work has been featured by VICE, the BBC, The Late Show with Stephen Colbert, Engadget, CNN, Business
Insider, Forbes, and Science Friday.

Arduino Class: Page 1


Lessons

Lesson 1: What You'll Learn


This lesson contains a detailed list of everything you need
to complete this class, and shows you how to set up the
Arduino software.

Lesson 2: Your First Experiments


Learn how to use a solderless breadboard and wire/code
up your first few LED-controlling circuits! This lesson
covers the basics of the Arduino software/hardware
workflow.

Lesson 3: Input/Output
Now that you've got the basics, let's add some
interactivity and learn about inputs! This lesson walks you
through using pushbuttons, the serial monitor, analog
inputs with a potentiometer, and using small motors.

Lesson 4: Skills Infusion & Going Further


This lesson shows you how to solder, use code libraries
and control addressable LEDs, write your own code
functions, and calculate your circuit's power needs.

Arduino Class: Page 2


Lesson 1: What You'll Learn

Have you ever wanted to tinker with technology? Arduino exists to help
creative people and techno-beginners build projects with electronics. As a
platform, it fast-tracks users to success by helping ease the setup burden and
learning curve usually associated with electrical engineering and computer
science.
Arduino is the best way to get started with microcontroller programming and
building your own circuits that sense and react to the world around them. In
this class, we'll get creative with electronics and get comfortable with the
concepts you'll use to launch your long and fruitful Arduino journey.
The name Arduino de nes several layers of your experience:
s o f t w a r e - used to compose your programs and communicate with the
hardware, called an integrated development environment (Arduino IDE)
ha r d w a r e - refers to the boards themselves (e.g. Arduino Uno)
p r o g r a mmi n g l a n g ua g e - the Arduino programming language is based on C
t r a d e ma r k - Other brands may manufacture Arduino-compatible hardware, but
only some boards are o cial, and owning their trademark provides some unique
protections. For instance, it allows the hardware and software to remain open
source.

Arduino Class: Page 3


Arduino is also a huge global community, which means you'll nd vast
quantities of inspirational projects, sample code, and solutions to your
problems online.

The following lessons are designed to build your skills in Arduino


incrementally over time, leaving you with enough basic knowledge to go out
and create projects from your imagination.

Early on, you'll do breadboard experiments to increase your familiarity with key
concepts of electricity, components, and coding in the Arduino language.

Arduino Class: Page 4


Adding interactivity will be your next challenge. While you level up your
hardware skills to add buttons and knobs to control your circuits, you'll also
learn more programming concepts.

Then you'll acquire a variety of skills for building and programming, including
soldering, understanding the power requirements of your Arduino projects,
installing code libraries, and controlling a strip of addressable LEDs. You will
graduate with the con dence to take on in nite Arduino projects in the future!

Arduino Class: Page 5


Tools and Materials for Arduino

This lesson is a complete list of the supplies you'll need to complete this class.
To make it a bit easier to get everything at once, I've created an Adafruit
wishlist containing most of the components and tools. To get started with the
bare minimum, you can complete most of the core exercises with the contents
of the Adafruit Arduino Uno Budget Pack. If you're using a di erent kit, some
of the components may di er from those shown in the photos throughout this
class. You may also complete this entire class virtually, for free, using Tinkercad
Circuits!
For the basic exercises:

Arduino Class: Page 6


Computer running Arduino software
Adafruit Arduino Uno Budget Pack
Arduino Uno board
USB A-B cable
Half-sized breadboard
Breadboard wires
10K potentiometer
2 small pushbuttons
5 red di used 5mm LEDs
Bright red, green, and blue LEDs (one each or an RGB LED)
5 220-1K ohm resistors (all same value, any value within range OK)
5 10K ohm resistors

Plastic mounting plate for breadboard and Arduino


Small athead screwdriver
Small DC motor, PN2222 transistor, and 1N4 001 diode

To complete the Skills Infusion lesson (here's a great toolkit with almost
everything you need):
Soldering iron and solder
1 meter of 60/m RGBW NeoPixel strip
Small needlenose pliers
Flush diagonal cutters
Wire strippers
Multimeter (optional but very handy)
Tweezers
Third hand tool
Desoldering braid or solder sucker

Recommended vendors for Arduino components & accessories:


Adafruit (& distributors) (worldwide)
Arduino.cc store (worldwide)

Understanding the Tools

Arduino Class: Page 7


Arduino Uno - This board is built around the Atmega328 microcontroller, with
supporting components to make it easy to connect up your own circuits. The
Uno connects to your computer with a USB A to B cable, which is commonly
used for printers (boxy connector). For this class, it is acceptable to use a
compatible stand-in for the Arduino Uno, such as a Sparkfun RedBoard or
Seeeduino V4.2, just make sure you have the right USB cable.

Solderless breadboard - This device has strips of metal inside and many holes
that allow you to connect components quickly and easily. A mounting plate is
recommended, to keep the breadboard and Arduino Uno together. You'll
connect to the Arduino with wires (breadboard wires are great but you can
also use solid core hookup wire).

Arduino Class: Page 8


Electronic components - You'll create circuits by plugging LEDs and other
components into your breadboard. This class introduces each new component
with a basic exercise showing you how to wire it up and write an appropriate
Arduino program. Components used: 5mm LEDs, resistors, a pushbutton
switch, a potentiometer, and a small DC motor (with its own diode and
transistor). Lessons cover the basics with an emphasis on writing code to
interact with the components. For more in-depth information beyond what's
covered here, please check out Randy Sarafan's Electronics class or LEDs &
Lighting class.

Soldering tools - The Skills Infusion lesson teaches you how to connect wires to
LED strip with a soldering iron, which heats the components enough to ow
solder (an easy melting alloy) between them. Any basic iron will do! Wire
strippers remove insulation to expose the conductor inside, pliers and
tweezers help you position components, and a third hand tool helps keep
everything steady. Flush snips do a great job trimming excess wires and
component leads after soldering. Wear protective eyewear when soldering and
clipping wires, and solder in a well-ventilated area.

Arduino Class: Page 9


RGBW NeoPixel strip - This digitally addressable strip contains WS2812b chips
controlling compound LEDs in red, green, blue, and white. NeoPixel is the
Adafruit brand name but you can also nd this strip by searching for
"WS2812b RGBW strip" on your favorite supplier's site. The sample code
provided in this class w ill no t w o rk w it h RGB (no w hit e ) s t rip, a na lo g
LED s t rip, o r w it h a ny o t he r kind o f dig it a l co nt ro l chip (like
APA10 4 a ka Do t St a r) .

Arduino Class: Page 10


Software Setup

The Arduino IDE (software for composing code and sending it to your board)
runs on Windows, Mac OS X, and Linux. Head to the download page and click
the option that best describes your system. While the software is downloading,
connect your Arduino board to your computer with a USB A to B cable ( at to
boxy, typically used for printers). The green LED next to the label ON should
turn on, and the orange LED next to the label L should begin blinking.
Depending on your operating system, your software installation procedure
will vary. On Windows, run the installer, which will also install the necessary
drivers (provided your Arduino board is plugged in). On OS X, drag the
Arduino app into your Applications folder (no drivers necessary). For more help
with Windows if the installation doesn't go smoothly, refer to Arduino's
detailed instructions. If you prefer not to download software, most of the class
can also be completed using the Arduino Web Editor.

Open the Arduino application and load up the rst code example by selecting
File -> Examples -> 01.Basics -> Blink.

Arduino Class: Page 11


Next it's time to tell the software what kind of Arduino board we intend to
program. Select Tools -> Board -> Arduino/Genuino Uno.

Then we need to select the communication port connected to the Arduino


board. Select Tools -> Port, then whichever port name is labeled "
(Arduino/Genuino Uno)." If none of your ports are labeled, try unplugging
your board, checking the Ports menu, then replugging your board and
checking the Ports menu again. Whichever port name disappears then
reappears is likely to be your Arduino board. On Windows your port will likely
be called "COM3" (or higher numbers) and on OS X it's likely to be something
like "/dev/cu.usbmodem1461."

Now click the Upload button to transfer the Blink example code to the Arduino
board. The LEDs labeled RX and TX will ash, and the software will show a
message "Done uploading." Moments later the LED labeled L will begin
blinking as it did when you rst plugged it in.

Congratulations, you're ready to begin the next lesson, where we'll dig into the
code you just uploaded, as well as build your rst few LED circuits and discover
how to control them using basic Arduino programming concepts.
If your port doesn't appear, or you get an error when trying to upload, refer to
Arduino's detailed troubleshooting guide, which covers many other common
issues.

Arduino History

Arduino Class: Page 12


The origin story of Arduino is long and complicated, with more characters than
Game of Thrones. I'll attempt to summarize it here, with a focus on the
evolution of the hardware and community.
In the early 2000s, students and professors at the Interaction Design Institute
Ivrea (IDII) in Italy developed a new microcontroller board for use speci cally
by artists and designers. They held workshops and seminars using the boards
throughout di erent iterations, which were programmed using Wiring, a
creative coding platform developed by Hernando Barragán. Wiring easily
allowed creators to program microcontrollers by providing a supportive
software environment, a bootloader for easily uploading programs to the
board, and a comprehensive online reference including add-on libraries and
forums.
Some other members of IDII partnered with a manufacturer to develop a
version of the hardware that used an Atmega8 microcontroller, and Arduino
was born. The original Arduino team members' names can be found on the
Arduino NG board pictured above: Massimo Banzi, David Cuartielles, Tom Igoe,
Gianluca Martino, and David Mellis.

The Arduino Uno we'll use in this class is the agship development board of
the Arduino brand, and it is the latest iteration in a long line of boards with a
mission to make it easier for non-engineers to use.

Arduino Class: Page 13


Features accrued over time, and DIY upgrade tutorials also were published,
when applicable. I recall hand-soldering a capacitor to two pads on my
Arduino NG in order to take advantage of a new Diecimila update. The pin
layout was consistent between boards (with some more pins added in later
models) so that add-on shields could be backwards compatible. There's a full
chronology about the board that became the Uno on the Arduino site.

Other boards with specialized functions have been released in the Arduino
product line. Need more inputs and outputs? Use an Arduino Mega. Want a
smaller circuit board and USB keyboard functionality? Use an Arduino Micro.
And so forth. O cial Arduino boards are all natively supported by the Arduino
software.

Arduino Class: Page 14


For the enthusiast, it's possible to develop your own hardware that works with
the Arduino software, too. Because Arduino is an ecosystem of open source
hardware and software, it's possible to develop your own hardware that works
with the Arduino software. It is also possible to build on the circuit to create a
version to suit a more speci c function, and manufacture and sell those
designs. Because the plans have been freely available online, you'll see
hundreds of Arduino-compatible boards designed by corporations and
individuals alike, ranging wildly in function and complexity. Some are
designed to be pin-compatible with the Arduino Uno, like the Sparkfun
Redboard or Adafruit Metro. More compact boards for building tidy small
circuits like the Pro Trinket and Pro Mini make it easy to translate your
breadboard prototype to a nished project. Complex boards like the Huzzah
(wi ), Touch Board (capacitive touch + audio playback), and Circuit Playground
(beginner lessons baked into the board) empower beginners to accomplish
very sophisticated projects with ease.

Arduino Class: Page 15


Lesson 2: Your First Experiments

Roll up your sleeves and let's dig in! In this lesson, we'll conduct some basic
breadboard experiments to introduce you to the basic Arduino concepts and
work ow.

Arduino Class: Page 16


First, set yourself up for success by a xing your Arduino Uno board and
solderless breadboard to a mounting plate. Trust me on this one—it provides a
huge bene t of holding your prototypes together and keeping them out of
trouble! The solderless breadboard has a sticker back you can peel o (peel o
the mounting plate's paper backing as well), and the Arduino Uno attaches
with screws from the underside. It doesn't matter which way your Arduino is
facing in relation to the breadboard. A small screwdriver is handy here, so you
can hold a nylon nut in place on the top of the board and drive the screw from
the bottom. Only two diagonally-placed screw/nut combos are required for a
secure t. Rubber feet (included with plate) help the whole assembly stable
while you work and now your circuit is also more portable and protected from
any wire bits that might be strewn around your work surface.

Supplies

To follow along with this lesson you will need:


Computer running Arduino software
Some of the items from the Adafruit Arduino Uno Budget Pack:
Arduino Uno board
USB A-B cable
Half-sized breadboard
Breadboard wires
5 red di used 5mm LEDs
Bright red, green, and blue LEDs (one each or an RGB LED)
5 220-1K ohm resistors (all same value, any value within range OK)

Plastic mounting plate for breadboard and Arduino


Small athead screwdriver

Arduino Class: Page 17


Solderless Breadboards

Solderless breadboards are for prototyping circuits quickly and easily. You can
think of it as akin to a dry-erase board, great for speedy brainstorming and
experimentation. Breadboards allow you to connect components using multi-
port metal sockets. The conductive parts of the breadboard allow electrons to
ow between the things you plug into it.

Arduino Class: Page 18


On the right you can see inside a breadboard to observe how these sockets are
connected. Two long rails run down each side, marked with red and blue lines
on the front. These long connectors are typically used for power and ground
connections, which are used quite often. The small horizontal rows that
comprise the middle of the board are for plugging in wires and components.
Notice the divider down the middle of the board-- this exists to provide chips a
place to straddle, providing independent access to each of its pins.

It takes some practice to get the hang of using a solderless breadboard,


mainly because it's hard to remember which spots are connected to which
other spots. You may nd yourself referring back to the photo of the inside of
the breadboard frequently; that's perfectly normal!

Arduino Class: Page 19


Blink Circuit

The rst circuit we'll build on the solderless breadboard connects a red LED to
the Arduino Uno board. Let's start out slowly, with one wire connection at a
time. Follow along with the same colored wires to make it easier on us both.
Double check that your USB cable is disconnected before doing any wiring to
your board. Grab a red wire and plug one end into the pin marked 5V on the
Arduino board. Plug the other end of the red wire into the breadboard rail
marked with a red line— this will be your power bus.

Arduino Class: Page 20


Similarly, grab a blue wire and plug it into one of the pins marked GND, right
next to the red wire. There are three ground pins on an Arduino Uno, and
they're all wired to the same ground as the chip and the rest of the board, so it
doesn't matter which one you choose. Plug the other end of your blue wire to
the blue ground bus on your breadboard. This is a common con guration you
will use again and again, and should be your go-to setup for new breadboards,
even if you aren't using both buses immediately. Circuits in this lesson will
connect to the ground bus, and in the next lesson you'll use some components
that will connect to the 5V power bus.

Arduino Class: Page 21


Next, plug a yellow wire into Arduino pin 13. Plug the other end into any
horizontal row on your breadboard (row 10 shown above). For this rst circuit,
all of your connections should be composed on the half of the breadboard
closest to the Arduino board.

Connect another blue wire from any pin on your ground rail to another
horizontal row on your breadboard (row 18 shown above).

Now grab a 1K resistor (stripes are brown-black-red-gold), and plug one of its
wire leads (doesn't matter which) into the same row as the blue wire. Resistors
all look similar, except for the stripes used to indicate their value.

Arduino Class: Page 22


Plug the other end into a row right next to the yellow wire.

Arduino Class: Page 23


Now grab a red LED (lig ht e m it t ing dio de ) . See how one of its wire leads
is longer than the other? That's the positive lead (anode), and the shorter lead
is negative (cathode). In the circuit we're building, positive charge comes from
the Arduino pin and goes through the LED and resistor to ground, so you
should connect the positive (longer) lead to the yellow wire and the negative
(shorter) lead to the resistor. A resistor helps limit the current going through
an LED, which doesn't do a great job of limiting itself.

ht t ps://player.vimeo.com/video/192704 689

Another way to guess the polarity of an LED is by looking inside the lens at the
anvil (bigger piece of metal) and post (smaller piece of metal). The anvil is
usually the cathode, but as you can see in the above video, not all LEDs
observe the same polarity conventions. The only way to be totally certain of its
polarity is to test it. To learn more in-depth about resistors and LEDs, check out
the LEDs lesson in the Instructables LEDs & Lighting Class.

Plug in your USB cable and the LED should immediately start to blink! It's
programmed to blink whatever's connected to pin 13. That includes the
onboard LED you saw in your software setup as well as the one you just wired
up.
If your LED isn't blinking, unplug your USB cable, then reverse your LED and
replug your USB; maybe the LED was just plugged in backwards (which won't
damage it, but won't light it up, either). Or perhaps one of your other wires or
resistor aren't connected correctly. Double check your connections against the
diagram of the circuit:

ht t ps://www.t inkercad.com/embed/heWjQPZNfIg?zoom=false

Find this circuit on Tinkercad


Click "Start Simulation" to run the Arduino emulator, which has the "blink"
sample program loaded up. We'll use Tinkercad Circuits modules like this one
throughout the class to help you build along. They contain wiring diagrams for
your breadboard experiments as well as the code you'll need for each. Click the
"Code" button to see the program, called an Arduino s ke t ch . It looks like
this:

Arduino Class: Page 24


ht t ps://creat e.arduino.cc/edit or/Bekat hwia/4 735007d-fb84 -4 4 64 -a67b-c51edbb3d3d6/preview?embed

You'll use the Arduino IDE to manipulate programs like this one and send
them to your Arduino board to run. You've already loaded this sketch onto
your Arduino board in the software setup from the previous lesson, but a
refresher can't hurt: you can nd this sketch and many other examples used in
this class through the Arduino software menu (File -> Examples -> Basics ->
Blink).

Example sketches make great starting points for experimentation and your
own projects down the line. These examples are invaluable to your Arduino
learning experience; use them! It's common to make lots of typos when writing
your rst code, which can cause confusing errors. The examples come in handy
is when you want to x up your own not-working code (called de bug g ing ).
Comparing your work to de nitive examples of working code can be one
helpful strategy to help debug your code.
Let's take a closer look at the elements of this basic Arduino sketch. First up is a
little note:
// Pin 13 has an LED connected on most Arduino boards.
// give it a name:

This is just a co m m e nt , meant to help humans understand the program. In


Arduino programs, comments are signi ed with two slashes; anything on a
single line after the slashes is discarded when it comes time to co m pile (build
this code into the machine-readable version that will run on the Arduino
board). Therefore comments don't contribute to your program's size, so
comment away! You may easily forget what each section of your program is
supposed to accomplish; I strongly recommend you to get into the habit of
heavily commenting your code, and reading the comments in each of the
examples we use in this class.
int led = 13;

Next up is a v a ria ble declaration. You can think of a variable as a bucket for
some information. Variables, like buckets, have sizes and shapes to hold
di erent kinds of information. Variables also have names, like a mandatory
label on the bucket. This line of code de nes a variable of type int , which
means integer. Remember back to primary school math class, when you might
have learned that integers are whole numbers (positive or negative). So we
have a bucket that can hold an integer. It's label is led but could just as easily
be "MyLEDPin" or any single word (letters and numbers only, case sensitive)
because this part of the variable declaration is up to you. I strongly advise
using descriptive names for your variables so you can keep track of what your
program is doing!

Arduino Class: Page 25


After the line of code above, any time we see "led" in the program will be
swapped out for the number 13. This is handy for con gurations like ours,
where we want a way to reference which pin the LED is connected to, over and
over, but if the wiring changes we'll only have to update it on one place in the
code.
// the setup routine runs once when you press reset:
void setup() {

As the comment suggests, anything between this line and the closing curly
brace } is part of the s e t up , a section of code that runs once per session.
Code inside the setup executes one time when your board rst powers up, or
when you press the Arduino's reset button.
// initialize the digital pin as an output.
pinMode(led, OUTPUT);
}

Pins 0-13 on your Arduino board are digital i/o pins, which means they can be
either inputs or outputs. pinMode(); is a f unct io n , a shorthand way to refer to
subset of commands "under the hood," so to speak. Arduino shows you it
recognizes certain elements of code by changing its text color. If ever a
keyword isn't changing color as you type it in Arduino, you probably have a
misspelling, capitalization error, or other typo. These pieces of information
passed to functions are called a rg um e nt s . Since the variable led will serve up
its contents anytime you type it, the pin number passed to pinMode(); is 13, and
the state is OUTPUT. This sets up pin 13 to control an LED, and the curly brace
closes the setup.
// the loop routine runs over and over again forever:
void loop() {

This is the main part of an Arduino sketch, where actions like checking input
pins and controlling output pins usually happen. Everything between this line
and its closing curly brace } will occur on repeat until the board loses power.

digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)

First up in the loop is a function called digitalWrite(); , which takes two pieces of
information: a pin number, and a HIGH (on) or LOW (o ) state. These pieces of
information passed to functions are called a rg um e nt s . Since the variable led
will serve up its contents anytime you type it, the pin number passed to
digitalWrite(); is 13, and the state is HIGH (on). This line of code causes the LED in

your circuit to turn on.


delay(1000); // wait for a second

delay(); is another one of Arduino's built-in functions. It pauses the program for
an amount of time, written in m illis e co nds . This line of code pauses the
program for 1000ms, or one second.
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW

Arduino Class: Page 26


As earlier, digitalWrite(); can turn an output pin on or o . This time it sets pin 13
LOW (o ).
delay(1000); // wait for a second
}

This line pauses the program for one second, and the curly brace signi es the
end of the loop, which begins again immediately. So to summarize, the
program turns an LED on and o at one second intervals. Let's try switching
up that interval. Modify the number of milliseconds in one or both of your
delay(); statements. For instance you could create a more uneven blink:

void loop() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
delay(2000); // wait for two seconds
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
delay(500); // wait for a half second
}

Try uploading your modi ed blink sketch to your Arduino board. Did it behave
as you expected it would?
Well done! That was a lot of information. It's ok if you don't quite understand
every little thing yet. Like learning any language, the Arduino programming
language has its own syntax and structure you must navigate, which will
become more familiar with regular practice. The most important thing to
remember is that you can work with code without knowing everything about
programming. As you go through the exercises in this class, I encourage you to
leave a window open loaded with the Arduino language reference page, which
describes each element and provides sample usage.

Arduino Class: Page 27


Add More LEDs

Now that you've got the basic idea of how to control a single LED, let's add
some more! Grab the rest of your red LEDs and 1K resistors. Unplug your
Arduino from USB/power if it wasn't already. It's smart to disconnect power
any time you are changing your circuit.

Connect the two pairs of rails on your solderless breadboard: plug a wire
connecting both power buses (red, +) and another wire connecting both
ground buses (blue, -). This is a commonly used con guration, since now you
can easily access power and ground on both edges of the breadboard. Bend
the leads of your resistors to 90 degrees and trim the ends to about a quarter
inch (6mm) from the bend.
Arduino Class: Page 28
You don't technically have to bend and trim your resistors, but they sure do
tidy up your breadboard. Replace the resistor on your breadboard with a tidier
one and see what a huge di erence it makes in the legibility of your circuit.
And you're less likely to create an accidental short circuit this way, too.

Let's add the new LEDs to the thus-far-unused half of the breadboard. Start by
connecting a tidy resistor from ground (sockets along the blue line) to a row of
the breadboard. Plug a red LED into the breadboard, connecting its shorter
(negative) lead at the same row as the resistor.

Add the remaining resistors and LEDs in the same pattern. Remember that
resistors can plug in either orientation, but LEDs have po la rit y and only light
up when electricity ows in one particular direction through them.

Move the yellow wire from Arduino pin 13 to pin 7. Connect another yellow
wire from Arduino pin 6 to the positive lead of the next neighboring LED.

Connect up more yellow wires according to the circuit diagram in the


Tinkercad Circuits module (Arduino pins 3-5 to the remaining LEDs' positive
leads).

ht t ps://www.t inkercad.com/embed/6XeW1sjPzXN?zoom=false

Find this circuit on Tinkercad


Click the "Start Simulation" button to see where we're going with the code side
of things. The program lights up one LED at a time, in order, down the line and
back again. Click the "Code" button to see the code, and then click the
download button (downward facing arrow icon). This example varies slightly
from a similar example that comes with the Arduino software, so we'll use this
downloadable version instead. Double click on the "ForLoopIteration.ino" le
to open it.

Click OK if you see a prompt to put the program in its own folder. If your
resulting le has all the code bunched up on one line, you are probably using
an old version of Arduino, and should update to the latest version. If you
prefer, you may also select and copy the code from the module above and
paste it into a new (blank) Arduino sketch (File -> New, then replace the default
contents with the code you copied from above).
Arduino Class: Page 29
Plug in and upload the code to your Arduino Uno board. You may have to
select your port again from the tools menu after replugging. Let's learn how
to code a light sequence by taking a closer look at the program elements:
/*
For Loop Iteration

Demonstrates the use of a for() loop.


Lights multiple LEDs in sequence, then in reverse.

The circuit:
* LEDs from pins 3 through 7 to ground

created 2006
by David A. Mellis
modified 30 Aug 2011
by Tom Igoe

This example code is in the public domain.

<a href="http://www.arduino.cc/en/Tutorial/ForLoop"> http://www.arduino.cc/en/Tutorial/ForLoop


</a>
*/

This rst part is just a long comment. You already learned about single line
comments, and now you know about multi-line comments, signi ed with a /*
to start and */ to stop.
int timer = 200; // The higher the number, the slower the timing.

A variable is declared! It's an integer called "timer", and this line sets it equal to
200. As you may have noticed, most lines of Arduino programs end with a
s e m ico lo n . When writing and modifying your own Arduino sketches, watch
out for missing semicolons as they will cause compiling errors that will trip you
up.
void setup() {
// use a for loop to initialize each pin as an output:
for (int thisPin = 3; thisPin < 8; thisPin++) {
pinMode(thisPin, OUTPUT);
}
}

The setup con gures pins 3 through 7 as outputs using a f o r lo o p , which is a


special loop that repeats a small section of code a certain number of times
based on a co ndit io n , using an incre m e nt co unt e r . Each time through
the mini loop, the condition is tested and if true, will continue on to execute
the code inside. So above, a variable thisPin is set to 3, the condition is that
thisPin should be less than 8, and the increment counter increases thisPin by
one each time through the loop ( thisPin++ is the same as saying thisPin = thisPin + 1 ). So
the rst time through this loop, pin 3 is set to an output. The second time
through, pin 4 is set to an output. And so forth until thisPin is 8, at which point
the condition is false and the code discontinues looping, continuing on with
the rest of the program. This may seem like a convoluted way to do a simple
thing, but programmers love e ciency! You could just as easily accomplish the
pin con gurations with the following setup:

Arduino Class: Page 30


void setup() {
// initialize each pin as an output:
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
}

You'll notice that there will usually be more than one way to accomplish the
same tasks with Arduino programming. Coding is similar to making things in
your workshop: you tend to use whatever tools you have. So lets use a for loop
for something fun... animation!
void loop() {

// loop from the lowest pin to the highest:


for (int thisPin = 3; thisPin < 8; thisPin++) {
// turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(thisPin, LOW);
}

The loop starts out with the same f o r lo o p as earlier, incrementing from the
lowest pin number to the highest. Inside the for loop, it turns on the LED at
thisPin , pauses for 200ms (set earlier as timer), then turns that LED o before
looping again with the next LED.
// loop from the highest pin to the lowest:
for (int thisPin = 7; thisPin >= 3; thisPin--) {
// turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(thisPin, LOW);
}
}

The next part of the code is another for loop, but this one starts at the highest
pin and uses thisPin-- , which means the same thing as thisPin = thisPin - 1 (itself minus
one), and exits the loop when thisPin is no longer >= 3 (greater than or equal to
three, aka 2). The nal closing curly brace closes the main loop. So this program
lights up each LED in order, then reverses the order and lights them up again.
Download
https://www.instructables.com/ORIG/FAL/YLM1/J1V7XOEX/FALYLM1J1V7XOEX.ino

Arduino Class: Page 31


Fade

Turning LEDs on and o is great and all, but now let's make an LED fade in and
out gradually using a function called analogWrite(); . Unplug your USB cable and
remove all but the rst LED from your breadboard, and move its yellow wire
connection to Arduino pin 9.

ht t ps://www.t inkercad.com/embed/bo3zmg7hInW?zoom=false

Find this circuit on Tinkercad


Copy/download the code from the Tinkercad Circuits module or open up the
example in your Arduino software examples under File -> Examples -> 01.Basics
-> Fade.

Plug in and upload the sketch to your Arduino Uno board and observe your
LED fade on and o .

Arduino Class: Page 32


Let's look at the code to learn how this fading is achieved. I have turned on line
numbers in the Arduino preferences in order to better be able to reference the
di erent parts of the code.

ht t ps://creat e.arduino.cc/example/built in/01.Basics%5CFade/Fade/preview?embed

Lines 16 through 18 declare three variables used in the program. The setup
con gures pin 9 as an output on line 23. On line 29, the function analogWrite(); sets
pin 9 to whatever the variable brightness is at the given time. On line 32,
brightness is incremented by 5 ( fadeAmount ). Line 35 uses an if s t a t e m e nt to
check if brightness using comparison operators. If brightness is less than or
equal to <= zero, or || greater than or equal to >= 255. If the statement is true,
the code inside is executed, otherwise it's just skipped. So this code increases
brightness until it reaches or exceeds 255, then sets fadeAmount to -5 and
decrements brightness until it reaches zero (or dips below zero). The delay at
the end prevents the code from running so fast that you can't see the e ect.
Try changing the value of fadeAmount and upload the code to your board.
How does changing this variable a ect the appearance of the fading?
The Arduino board is only capable of generating digital signals (HIGH and
LOW ), but analogWrite(); simulates the appearance of brightnesses between
on and o using puls e w idt h m o dula t io n ( PW M ) . The LED ashes on and
o very quickly, and your eye interprets a dimmer light. The ratio of time the
LED spends on vs. o determines how bright or dim the LED appears. Only
certain pins are capable of PWM, and they are labeled on the board with
squiggles ~ next to the pin number. PWM can also be used to control the
speed of a DC motor, which we'll do in a later lesson.

RGB LEDs
Arduino Class: Page 33
Additive (light-based) color has three primary colors: red, green, and blue.
Simultaneously controlling the brightness of one LED of each of these colors
can create almost any color of light. Color changing LEDs like those used in the
nal project work the same way, but the LEDs are all together in a very small
package called an RGB LED . Let's build our own RGB LED from three 5mm
LEDs in your kits. In the Adafruit kit recommended for this class, these three
LEDs have clear lenses, so we'll have to plug them in to determine which LED is
which. LEDs with clear lenses can be any color! If you're using a di erent kit,
just nd one red, one green, and one blue LED (clear or colored lens). Unplug
your USB cable and swap out the red LED for one of the clear-lens LEDs, then
plug the USB back in.

What color is the LED? If you nd the red one on the rst try, set it aside and
repeat the process to determine the color of the the other two LEDs.

ht t ps://www.t inkercad.com/embed/jTfaA3ssc6S

Find this circuit on Tinkercad

Arduino Class: Page 34


Wire up the other two LEDs with 1K resistors to pins 10 and 11, as shown in the
diagram. Download and open the code from the Tinkercad Circuits module or
copy and paste it into a new empty Arduino sketch. Upload it to your Arduino
Uno board and see if you can match up the lines of code to the activity you see
in the LEDs, as we have done together so far.

The unfamiliar part of this code is the function setColor(); . It's a custom function,
de ned below the loop() has ended.
void setColor(int red, int green, int blue)
{
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}

A f un c t i o n d e n i t i o n declares a name, and what type of arguments the function will take,
which you can think of as the con gurable settings you'll want to change each time you execute
the code it contains. In this simple function, three integer values are written to the three LED
pins using analogWrite(); .
setColor(255, 255, 0); // yellow

Each time this function is called in the main loop, the program executes the
code in the function before continuing through the main loop. In this case, the
arguments are used as the brightnesses of each LED. The scale for brightness
is 0-255 because each color is de ned using one byte, which allows for 256
distinct patterns.

ht t ps://www.t inkercad.com/embed/bclfJGFygLR?zoom=false

Find this circuit on Tinkercad


Now download and open the code from this more complex RGB project, or
copy and paste the code into a new blank Arduino sketch. Read its comments
to learn more about how this program works. It does some math to convert a
0-100 range to the necessary range the LEDs need, so you can think in
percentages instead of 0-255. It uses collections of variables called arrays to
store colors, and three user-de ned functions to calculate values for a smooth
fade between colors so that the loop() is nice and tidy. crossFade(red); almost reads
like English! We'll get into some of the other unfamiliar keywords in this sketch
in future lessons, but rst it's time to celebrate all you've achieved so far.

Arduino Class: Page 35


Lesson 3: Input/Output

So far you've learned to control LEDs with code, which is one use of Arduino's
o ut put s . This lesson builds on outputs by adding input s . Your Arduino
board can be programmed to listen to electrical signals and take actions based
on those inputs. We'll put together a digital input circuit with a s w it ch , and
an analog input circuit with a po t e nt io m e t e r (variable resistor).

A switch is a mechanical device that connects or breaks a circuit, often using a


lever or button. Your tiny tactile pushbutton is just one member of a very large
and diverse family. To learn much more, check out the switches lesson in the
Instructables Electronics class.
A v a ria ble re s is t o r is a component with a changing electrical resistance. In
addition to the potentiometer (knob) used in this lesson, you may seek out
other variable resistors to try, including but not limited to: pressure sensors
(force sensitive resistor aka FSR), light dependent resistors (LDR aka
photoresistor), and analog temperature sensors.

Supplies

Arduino Class: Page 36


To follow along with this lesson you will need:
Computer running Arduino software
Some of the items from the Adafruit Arduino Uno Budget Pack
Arduino Uno board
USB A-B cable
Half-sized breadboard
Breadboard wires
10K potentiometer
1 small pushbutton
1 red di used 5mm LED
1 220-1K ohm resistor (any value within range OK)
1 10K ohm resistor

Plastic mounting plate for breadboard and Arduino


Small DC motor
PN2222 transistor
1N4 001 diode

Digital Input

Arduino Class: Page 37


Let's get ready to wire up a new circuit. Grab some breadboard wires, a red
LED, 1K resistor (brown-black-red-gold), 10K resistor (brown-black-orange-
gold), and a small pushbutton from your kit. Give your 10K resistor the same
elbow+trim treatment as your other tidy resistors.

First, connect the LED to Arduino pin 13 like you did in your rst circuit, with a
wire from pin 13 to the positive lead of your LED, and a 1K resistor connecting
the LED's negative lead to ground.

Next, plug in the pushbutton so that it straddles the center dividing line of
your breadboard. It should click into place snugly. Connect the 10K resistor
from one lead of the switch to the breadboard's 5V power rail. Connect a wire
to this same row and plug it into Arduino pin 2.
Arduino Class: Page 38
Connect the switch's diagonal lead to ground.

ht t ps://www.t inkercad.com/embed/9IFe14 0QD4 3

Find this circuit on Tinkercad


Click "Start Simulation" in the Tinkercad Circuits module and try clicking (and
holding) the pushbutton to see what the code does. Click the "Code" button to
see the sketch.

You can nd this example in the Arduino software by navigating to File ->
Examples -> 02.Digital -> Button. Open it on your computer, and upload it to
your Arduino Uno board. The LED should light up, but turn o whenever you
press the pushbutton.

Arduino Class: Page 39


Follow along as we explore the code in more detail.

ht t ps://creat e.arduino.cc/example/built in/02.Digit al%5CBut t on/But t on/preview?embed

The rst lines of this program introduce co ns t a nt s , which are similar to


variables in that they store a piece of information. However as you might infer,
constants don't change throughout your program, and are therefore great for
things like pin numbers. They take up less memory space than variables. Row
39 con gures Arduino pin 2 as an input, so we can "listen" to the electrical
state of the pushbutton.
In the main loop, a function called digitalRead(); checks the state of pin 2 (which
will be either 5V aka HIGH or ground aka LOW ), and stores that state in a
variable called buttonState. Row 48 contains an if statement that checks to see
if buttonState is HIGH ( == is a comparison operator, not to be confused with = ,
which is an assignment operator). If the condition is met, the digitalWrite(ledPin, HIGH);

command is executed. If not, the code contained inside the else { is executed
instead: digitalWrite(ledPin, LOW); . If statements can exist alone, or with one or more else
statements.

Arduino Class: Page 40


Have you noticed that your pushbutton circuit performs the opposite action
from that described in the code? I did that on purpose to stretch your mental
muscles; let's discuss the switch circuit some more. At rest, the switch leads are
not connected to one another. Pin 2 is connected through a beefy 10K resistor
to 5V. When the button is pressed, the switch leads are connected, which
allows pin 2 to be connected to ground, with no resistor. Since electricity takes
the path of least resistance, the pin will sense the connection to ground
strongly, and ignore the weak (10K) connection to 5V. But when no other signal
is present (when the switch isn't being pressed), that weak connection to 5V is
all the pin can sense. So the resistor is "pulling the pin up" to 5V, and so it's
called a pull- up re s is t o r . Without one, pin 2 would be not connected to
anything until the button is pressed. This is called " oating", and can result in
random noise from static electricity and electromagnetic interference.
Similarly a resistor can be used to tie a pin to ground, which is called a pull-
do w n re s is t o r .
So to change the function of the button, you can either change the wiring of
your circuit, or change the code. The latter is less work in this case, but it's
important to remember that might not always be the case when you're
building projects on your own. Edit lines 47 (comment) and 48 (if statement) to
say LOW instead of HIGH:
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin); // check if the pushbutton is pressed.

// if it is, the buttonState is LOW:


if (buttonState == LOW) {
// turn LED on:
digitalWrite(ledPin, HIGH);
}
else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}

Upload the updated sketch to your Arduino Uno board, and check that the
button now turns the LED on instead of o .
Arduino pins have built-in pull-up resistors on many of the pins (tiny ones,
inside the chip just for this purpose), and you can access one by enabling it in
the setup:
pinMode(buttonPin, INPUT_PULLUP);

Change this line of code in your sketch and remove the resistor from your
circuit. Upload the code; its behavior should remain the same.

The Serial Monitor

Arduino Class: Page 41


Keeping track of everything going on in your program can be an uphill battle.
The serial monitor is a way to check in on di erent spots in your code by
reporting back to the computer over the USB cable.

ht t ps://www.t inkercad.com/embed/f8aWEyOM4 IE

Find this circuit on Tinkercad


This circuit uses the same button con guration as the previous digital input
circuit, but just doesn't use the LED. Load up the code from this module or
nd it in the Arduino software by navigating to File -> Examples -> 01.Basics ->
DigitalReadSerial. Upload this code to your board and click the Serial Monitor
button in the upper right of the sketch window. You can also open the virtual
serial monitor in the Tinkercad Circuits module above (button at the bottom of
the code editor).

Arduino Class: Page 42


To create a serial connection, you should use Serial.begin(); inside your setup. The
number 9600 is the ba ud ra t e , or data speed, in bits per second (bps). Inside
the main program loop, you can use Serial.print(); to send information to the serial
port. Serial.println(); does the same thing, but prints on a new line. Line 24 in our
code prints the current value of buttonState (HIGH aka 1 or LOW aka 0) to the
serial port. So with the serial monitor open, we have a live scrolling view of
whatever the Arduino senses at pin 2. The serial monitor is exceptionally handy
when troubleshooting, since you can easily compare what you think should be
happening to what the Arduino is doing. You can also use serial
communication to talk between devices and much more, which you can read
about in the Arduino reference.

Analog Input

To sense a gradually changing electrical signal, we'll use Arduino's analog


inputs, located on the left side of the board. These special pins are connected
to the Arduino's analog to digital converter (ADC), equipped to convert an
analog signal between 0V and 5V into a range of numbers from 0-1023 (zero
counts as a value). Another powers-of-two size, 1024 is 2^10 bytes, aka 1KB.
Grab one of the blue potentiometers from your kit and plug it into three rows
on your breadboard (with your USB disconnected).

Arduino Class: Page 43


ht t ps://www.t inkercad.com/embed/eTYPBoTCSGN

Find this circuit on Tinkercad


Connect the center pin of the potentiometer to Arduino analog pin A0, and
the other two pins to power and ground respectively. Move your LED's control
wire from pin 13 to pin 9, so we can use PWM.

You can get the code from the Tinkercad Circuits module as you have for
previous lessons, or nd the example by navigating to File -> Examples ->
03.Analog -> AnalogInOutSerial.

Plug in your USB cable and upload the sketch to your Arduino Uno board.
Open the serial monitor and observe it and the LED as you twist the
potentiometer.

The values read by the analog input are printed in the rst column, and the
brightness values applied to the LED are printed in the second column.

Let's take a closer look at the main loop of this program:

Arduino Class: Page 44


This sketch uses the map(); function on line 39, which takes one range of
numbers and massages it into another range. It takes ve arguments: the
value to be changed, the lower bound of the value's current range, the upper
bound of the value's current range, the lower bound of the target range, and
the upper bound of the target range. So this line of code sets a variable
outputValue to a number between 0 and 255 depending on the position of the
potentiometer.
The serial printing commands on lines 44-47 print text labels (inside quotes)
and the values incoming from the sensor and outgoing to the LED. Seeing
these numbers change together in the serial monitor can really help you
understand how functions like map(); work. Keep this in mind when
composing and troubleshooting your own sketches!

A Moment for Motors

Arduino Class: Page 45


The exact same code used to brighten and dim the LED in the previous circuit
can also be used to control the speed of a simple DC m o t o r . This basic motor
needs a few extra components to help control it: a small resistor (use your 1K
or try a 100 ohm marked brown-black-brown-gold), a NPN t ra ns is t o r (we're
using a PN2222), and a diode (1N4001). The resistor is used to protect the
Arduino pin from excessive current draw. The diode prevents the transistor
from dumping any blowback voltage anywhere it shouldn't (something
motors are prone to doing). The transistor acts like an electronic valve,
allowing current to ow between its collector and emitter (PN2222 outer pins)
in proportion to the signal it receives at the base (PN2222 center pin).
Transistors are handy for controlling a rather power hungry component with a
microcontroller pin, which can't deliver enough current directly.

ht t ps://www.t inkercad.com/embed/7l0BoHp3X7A

Find this circuit on Tinkercad


Unplug your USB cable and build the circuit according to the diagram,
minding the at side of your transistor (faces away from the Arduino in this
circuit), as well as the stripe on your diode (on the side furthest from the
transistor). If you're using a di erent NPN transistor (like the 2N2222), your
transistor pin connections may be di erent than those pictured, so look up the
datasheet to be sure you're making the following connections:
Arduino pin 9 to transistor base through resistor
5V to transistor collector through diode
Ground to transistor emitter
Motor wires to transistor collector and 5V (either orientation)

Power up your board and see what e ect turning the knob has on the speed of
the motor (use a piece of tape to make it easier to see the motor shaft
spinning).

The motor recommended for this circuit draws less than 250mA, but a larger
one could require more power than your computer's USB port can deliver. To
power bigger motors, lots of LEDs, and other circuits that use more power,
you'll need to use an external power supply, such as an AC adapter or battery
pack. Additionally, for any larger of a motor, you'd also need a larger transistor.
We'll learn how to calculate your circuit's power needs in the next lesson, but
by popular request, here's the same motor circuit powered by an external 6V
battery pack (separate power rails, common ground):

ht t ps://www.t inkercad.com/embed/9rJr3EylTCw

Find this circuit on Tinkercad


To learn more about transistors and use them in a project, check out the
transistors lesson in the Instructables Electronics Class. To learn more about
motors and use them to build several fun robots, check out the Instructables
Robots Class.
Arduino Class: Page 46
You now know the basic building blocks of most Arduino programs, and have
built a few circuits demonstrating their utility. Great work!

Arduino Class: Page 47


Lesson 4: Skills Infusion & Going Further

In this lesson, we'll cover a few important concepts you'll need to understand
to create your own Arduino projects. We'll get up to speed on soldering, code
libraries, addressable LEDs, organizing code with functions, and calculating
the power requirements of your projects.

Supplies

To follow along with this lesson you will need:

Arduino Class: Page 48


Soldering iron and solder
1 meter of 60/m RGBW NeoPixel strip (or other WS2812b RGBW LED strip)
Breadboard wires
Small needlenose pliers
Flush diagonal cutters
Wire strippers
Multimeter (optional but very handy)
Tweezers
Third hand tool
Desoldering braid or solder sucker
Small pushbutton
Arduino Uno board and solderless breadboard on a mounting plate
USB A-B cable

Soldering

Arduino Class: Page 49


S o lde ring is an extremely useful electronics construction technique, and it's
surprisingly satisfying to do. It does take practice to excel, like most
worthwhile endeavors, so take a moment to set your intention for this lesson.
Establish a goal to keep trying even if you become frustrated, and be kind to
yourself during the process. And wear eye protection— nobody wants hot bits
of metal in their eyes! While we're talking safety, work in a ventilated area and
wash your hands afterwards, especially before touching any food. Be cautious
and alert around your soldering iron; keep burnable things away from the hot
part (including your skin), and turn it o (or unplug it) rather than leave it
unattended.
We'll use soldering to attach wires onto a piece of NeoPixel strip, so we can
plug it into the solderless breadboard. A basic soldering iron like the one
recommended for this class will take you quite far, and if you do upgrade to a
temperature-adjustable soldering station like mine, you can keep your basic
iron as a spare or give it to a friend. Plug it in, turn it on, and let it heat up for a
few minutes (mine is set to 650 degrees F). Keep a damp sponge or brass
sponge nearby (many soldering iron stands come with a small sponge). When
the iron is hot, clean the tip with a few wipes across the sponge or stabs into
the brass coil sponge. Then touch the iron to your solder for a moment to
transfer a little bit of solder to the tip, called t inning the soldering iron.
Repeat this cleaning and tinning procedure regularly while using the
soldering iron to prevent buildup of excess solder and oxidation.
Soldering works by heating up the metal components to be joined, then
allowing low temperature alloy solder to melt and ow and harden between
them. Solder is not glue. If you melt solder onto the tip and then smear it
around the component leads, you will not create a good electrical connection.
Solder is used with ux (usually built right into the solder, labeled "rosin
core"), which is a substance that helps delay oxidation. It shields the immediate
area of the bonding metals, and boils/burns away as they cool. Solder fumes
are mainly tree sap, which ux is made from. If you apply molten solder to cold
components, it could potentially look soldered, but a layer of oxidation is
hidden inside, created when the solder suddenly cooled as it touched the base
component. This is called a co ld s o lde r , which prevents electrons from
owing across the solder joint. Always heat your components fully before
applying additional solder! Good solder joints will look smooth and shiny, not
blobby or dull.

A third hand tool helps immensely when it comes to stabilizing your work,
especially as you're learning to hold the iron steady. I tend to avoid ca eine
around workshop time, too. I like to put a little bit of heat shrink tubing over
the jaws of my third hand tool, to soften its bite.

Arduino Class: Page 50


Prep three of your breadboard wires by cutting o the connectors at one end
and stripping the ends to expose the bare strands of wire. Twist the strands of
each wire to keep them together, then heat up the wire with your soldering
iron and apply a small amount of solder. Remove the solder before removing
the iron, to give the molten solder one last moment to settle in. Repeat to tin
your other two wires, then set them aside.

Cut a piece of your NeoPixel strip 19 pixels long, using your ush diagonal
cutters to clip straight across the middle of the copper pads. Remove it from
the silicone sheathing and identify the input— the arrow markings on the
strip point away from it. Clip the input end it into your third hand tool with the
back of the strip facing you. Tin the center copper pad by touching your
soldering iron to it, then applying a small amount of solder. Move your tip
around the copper pad to spread the bead of solder around.

Now that your two components are tinned, it will be easier to solder them
together. Pick up a your white wire in one hand and your soldering iron in the
other. Hold the tinned wire end to the tinned copper pad, and reheat the two
components at the same time. The solder on each should ow together, if it
doesn't, you may need to apply some more. Remove your iron before letting
go of the wire, so the solder has a chance to cool, securing the wire in place. If
you nd it di cult or too hot to hold the wire with your ngers, use a pair of
tweezers or pliers.

Flip over your NeoPixel strip and similarly tin and solder wires to the other two
copper pads (red wire for 5V, black wire for GND). It doesn't really matter which
side of the copper pad you solder to, but alternating sides gives your solder
joints a little more elbow room. Trim any excess wire protruding from the
copper pad. Now you're ready to plug the strip into your breadboard and get
the LEDs glowing (we'll do that next)!

Arduino Class: Page 51


If you make a mistake, apply too much solder, or just want to disassemble your
work, you can desolder the joint by simply reheating it and pulling the wire
away. For more entangled components, you can use co ppe r de s o lde ring
bra id to remove excess solder (its highly interleaved surface area draws the
solder in with capillary action), or a suction desoldering pump.

Practice your soldering skills again by attaching wires to two diagonal leads of
a pushbutton. Tin the wires and the pushbutton leads, then reheat them to
allow the solder to ow. Set this pushbutton aside for the nal project.

Addressable LEDs and Code Libraries


Arduino Class: Page 52
Now that the strip is soldered, we'll need to program the Arduino to turn the
LEDs on. Ne o Pixe l is the Adafruit brand name for WS2812 addressable
"smart" LED strip (as opposed to analog LED strip). Each pixel has a chip inside
to communicate with the Arduino board and other pixels on its strip (it can't
light up without a controller). To control the strip, some additional Arduino
functions are required, and we can get them by installing the co de libra ry .
Arduino code libraries empower you to leverage powerful computing tools
using simple commands. Arduino recognizes these add-on modules and then
you can use their commands within your program. Arduino libraries exist for
all sorts of complex tasks, like controlling large LED panels, reading sensors,
creating sounds, and many more.

In your Arduino software, navigate to Sketch -> Include Library -> Manage
Libraries...

When the Library Manager opens, search for "NeoPixel" in the upper right
eld. Optionally select a version of the library from the dropdown menu, and
click the "Install" button. Now you're all set to use the NeoPixel library in your
Arduino sketches! You can use the library manager to install all kinds of fun
extensions to the Arduino programming language that help you interface
with sensors, motors, and more.

Take a close look at your pixel strip. Each pixel contains a very small RGB LED,
which can theoretically create any color of light. However, generating pure
white poses a challenge for RGB LEDs and often leaves users disappointed in
the tinted or poorly mixed quality of light produced. For this reason, the RGBW
strip includes a white LED inside its package as well.

Arduino Class: Page 53


Coding for these pixels will include four brightness values to describe a pixel
color: red, green, blue, and white. This is similar to analogWrite(); in the RGB
LED example from your rst exercises: you provide a number from 0-255 to
represent the brightness of the LED. The functions in the NeoPixel library take
pixel numbers and these color values as arguments, then translate them into
the commands to send along the LED strip.

Now that our NeoPixel strip has wires attached to it, let's connect it to the
breadboard. The 5V wire (red) goes to your breadboard's power bus, and the
ground wire (black) goes to the breadboard's ground bus. Connect the data
wire (white) to Arduino pin 6.

ht t ps://www.t inkercad.com/embed/jZpGsoNCnuT

Find this circuit on Tinkercad


Download/copy the code from the Tinkercad Circuits module (Code button-
>download code button) and open it in your Arduino software. Plug in your
USB cable and upload to your Arduino Uno, and watch the pixels light up and
change colors.

Arduino Class: Page 54


Let's take a look at the Arduino sketch:
#include <Adafruit_NeoPixel.h>

#define PIN 6

#define NUM_LEDS 19

#define BRIGHTNESS 50

// Parameter 1 = number of pixels in strip


// Parameter 2 = pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
// NEO_RGB Pixels are wired for RGB bitstream
// NEO_GRB Pixels are wired for GRB bitstream, correct if colors are swapped upon testing
// NEO_RGBW Pixels are wired for RGBW bitstream
// NEO_KHZ400 400 KHz bitstream (e.g. FLORA pixels)
// NEO_KHZ800 800 KHz bitstream (e.g. High Density LED strip), correct for neopixel stick
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRBW + NEO_KHZ800);

The rst section instantiates the NeoPixel strip and sets up the con gurable
bits of the program like the pins connected to the NeoPixel strip and button,
the number of pixels, and global brightness level. #define statements are similar
to variable declarations, but are used for information that does not change
while the program is running. They take up less memory than regular variable
declarations.
void setup() {

strip.setBrightness(BRIGHTNESS);
strip.begin();
strip.show(); // Initialize all pixels to 'off'
}

strip.show(); is used any time you want the pixels to change. Setting the pixel colors
and showing the latest changes are broken up into two separate commands.

Arduino Class: Page 55


void loop() {
// Some example procedures showing how to display to the pixels:
colorWipe(strip.Color(255, 0, 0), 50); // Red
colorWipe(strip.Color(0, 255, 0), 50); // Green
colorWipe(strip.Color(0, 0, 255), 50); // Blue
colorWipe(strip.Color(0, 0, 0, 255), 50); // White

whiteOverRainbow(20,75,5);

pulseWhite(5);

// fullWhite();
// delay(2000);

rainbowFade2White(3,3,1);
}

The main loop just calls other functions. Let's take a closer look at colorWipe(); ,
de ned just below the main loop, and takes two arguments: a color
( strip.Color(r, g, b, w) ), and a speed value.

// Fill the dots one after the other with a color


void colorWipe(uint32_t c, uint8_t wait) {
for(uint16_t i=0; i < strip.numPixels(); i++) {
strip.setPixelColor(i, c);
strip.show();
delay(wait);
}
}

The function de nition starts with what type of data the function will re t urn ,
or send back to the main program. In this case the function returns nothing,
so the word v o id is used at the start of the de nition. Next is the name of the
function, which is up to you. Then in parentheses are the arguments the
function takes, in this case a 32 bit unsigned integer called "c" and an 8 bit
unsigned integer called "wait." Inside the function, these lo ca l v a ria ble s are
used to reference the information you passed to it from the main loop (or from
another function). The function itself steps through all the pixels in the strip
(using a for loop and a NeoPixel function called strip.numPixels(); ), coloring and
showing each one before moving to the next. The other functions in the RGBW
strandtest program work the same way, and use clever color math to achieve
stunning light patterns.

Write Your Own Functions

You can easily modify colorWipe(); to start coding up your own unique
animation. Try copying the whole function de nition, and change the name of
the function (or copy and paste this snippet just after the closing curly brace
of your main loop).

Arduino Class: Page 56


// my first NeoPixel animation
void animationExperiment(uint32_t c, uint8_t wait) {
for(uint16_t i=0; i < strip.numPixels(); i++) {
strip.setPixelColor(i, c);
strip.show();
delay(wait);
}
}

Then start playing around with the code. Say I want to light up a random pixel
in the strip instead of lighting them up in order. I could use Arduino's built-in
random(); function to pick a pixel, which generates a random number between
the two arguments:
strip.setPixelColor(random(0,strip.numPixels()), c);

Call your new function inside your main loop:


void loop() {
animationExperiment(strip.Color(255, 0, 0), 50); // Red
}

Repeatedly upload your code experimentation to your Arduino Uno board,


making small changes each time. If you nd an e ect you like, stop editing
that function and create a new one, either by copying/pasting a function and
changing its name, or typing out the de nition:
void functionName() {
//contents
}

Congrats, that's all there is to creating functions in Arduino! They're a handy


tool to separate out a chunk of code you want to access repeatedly, and make
your code easier to read.

Arduino Class: Page 57


Learning to Fish

Arduino Class: Page 58


You've made it to the end! What follows are some parting words of advice for
venturing o into the world of Arduino on your own.
Rest assured that because of its rich community history, most of your early
questions about Arduino are already well documented online in tutorials and
forums all over the web. However you are just learning the vocabulary by
which to access this vast catalog of resources, and things may be a little rocky
at rst. Remind yourself there is a learning curve, and everything will get
easier and come more naturally after some time and repeated practice. Here
are some tips to improve the results of your self-directed learning.
G o o g le w it h g us t o - Get good at search engines! Use quotes to search for
Arduino error messages, brainstorm key words around your idea and look for
folks who've documented similar projects before. This can be handy during the
parts brainstorming step but also for learning more uses for the parts you
already have. Become a regular lurker in the Arduino and Adafruit forums,
where most beginner roadblocks are solved many times over. Say it with me: "I
bet I can nd someone online who's had this question before; I just have to nd it."
Sha ring (co de ) is ca ring - Arduino is built on open source ideas.
Innovation ourishes when technology is shared! You'll nd countless libraries,
code examples, Github repositories, and more resources to aid in your coding
education. It behooves you to read up on the history of open source, learn
about licenses commonly used for code and hardware, and credit your sources
when building on others' designs.
Do cum e nt y o ur pro ce s s - It's easy to forget to photograph your circuit
before revising it when you're in the throws of frustration over a bug. Set a
timer to remind yourself to take pictures and video while building! You may
nd yourself wanting to look back at previous iterations to avoid making the
same mistakes twice. Additionally, you'll nd a supportive community of
makers willing to help you along your way if you choose to share your projects
online in forums, your own website, or here on Instructables. Documenting
your struggles along with your successes will connect you with knowledgeable
folks around the globe, and maybe even help someone else who's just
learning Arduino.

Durability & Weatherproofing

It's quite likely you want to create Arduino projects that will function for some
time while enduring repeated movement or exposure to the elements.
Designing durability into a circuit requires some forethought of potential
failure modes, often only discovered through repeated prototyping and
improvement upon prior failure. Here are some tips on design and
construction for durability. Remember to read and follow manufacturers'
instructions and safety procedures when using any hazardous materials.
Pro t e ct t he po w e r s upply - The most important part of your circuit to
keep safe is the battery and power connections. A short circuit here could trip
a circuit breaker, permanently damage components, or cause a re.
Arduino Class: Page 59
St ra in re lie f - Remember that your circuit has both mechanical and
electrical connections. Sometimes they are one in the same, like the Arduino's
USB and power ports. However it's always a great idea to add mechanical
connections to your projects to prevent wires from tugging on their solder
joints. You can use zip ties to secure wires, and most circuit boards have
mounting holes for use with screws or hand sewing. For connections that will
bend repeatedly, use stranded wire instead of solid-core.
Kno w y o ur a dhe s iv e s - Using the right glue for the job is critical for your
circuit's durability! For instance, few things will actually stick to the silicone
sheathing that comes around LED strip. Only certain silicone adhesives will
provide a weatherproof seal in this case. Permatex 66B is my favorite for
NeoPixel strip's silicone sheathing. Any adhesive should be tested to check that
it bonds to both surfaces. Hot melt glue was convenient for the in nity mirror
project in this class, but it stinks for durability. Instead I highly recommend
E6000 craft adhesive, or its cousin Quick Hold. These take longer to dry but
stick to everything (except silicone) and dry clear and exible. To learn more
about adhesives, check out our Glue class!
Hum idit y & m o is t ure - It's important to protect your circuit from water,
which will cause shorts. If you're thinking of making an electronic costume, for
instance, did you consider that your evaporating sweat could be a factor?
Where will your circuit be located and what humidity/water conditions can you
expect there? Generally you can think of using coverings and coatings to
address this issue. You can nd completely waterproof enclosures for your
projects, cover your circuit with waterproof fabric, and use waterproof
adhesives to seal up any openings. I often use clear nail polish to protect bare
components on costumes/wearables. Clear spray paint is also a good option,
however I'm not a big fan of the new hydrophobic coatings like NeverWet.
They were designed for things like the circuit board inside your phone, and
don't function well outside that context because of their extreme physical
fragility, sensitivity to sunlight, and highly toxic nature.
However water is not a circuit's nemesis! If the battery/power supply is
removed, most circuits won't be damaged by water, so long as they dry out
before being plugged back in (and weren't left a long time to corrode).
Exceptions exist for components that water can get inside, like microphones.
But generally, it's ok to hand wash your Arduino projects after unplugging the
power and removing any batteries.
UV a nd t e m pe ra t ure uct ua t io n e xpo s ure - Over time, many plastics,
adhesives, and other protective materials break down when exposed to
sunlight. Wire sheathings may become brittle and crack open. Coatings may
break down and fail. Think about the temperatures your circuit is likely to
experience, too. Most batteries' lives are shortened by exposure to high or low
temperatures, for instance. Check the datasheets for your components to
learn their operating temperature ranges.
This is just the tip of the durability iceberg, folks. There are whole elds of
study devoted to the topic, in mechanical engineering, industrial design, and
materials science just to name a few. However for most projects, a bit of E6000
and some zip ties really go a long way towards keeping your projects alive.

Arduino Class: Page 60


Next, Try...

If you completed all the lessons in this class, you're now ready to take on
countless Arduino projects, including your own designs. Don't know where to
start? Try my Easy In nity Mirror with Arduino Gemma. You may also nd many
of the early code examples to be great starting points when building your own
sketches. For your next class, consider Internet of Things, Electronics, Wearable
Electronics, or Robots, which will all deepen your understanding of some of
the concepts from this class.
Here are some projects from the Instructables community to help inspire your
next creation:

Secret Knock Detecting Door Lock by


Word Clock by drj113 Grathio

HC-SR04 Distance Sensor by jsvester Instagram Inspired DIY Photo-Booth


by alexandermorris

Self-Watering Plant by randofo Existential Emergency Phone by


randofo

Have you made a project with Arduino you'd like to share? Please consider
writing an Instructable about it, and enter it in one of our frequent contests.
Thank you so much for taking my Arduino class! If you enjoyed your
experience, consider sharing it with a friend. And I'd like to receive your
feedback either way, so I can improve this and future classes.

Arduino Class: Page 61

You might also like