Вы находитесь на странице: 1из 69

ARDUINO CLASS

4 Lessons Beginner Level

This class will introduce you to the Arduino world. You'll learn the basics, build your first 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 confidence to take on
almost any Arduino project you may find or create in the future.
Want to see an Arduino project happen in real-time? Check out a full video of my webinar on
creating an Easy Infinity Mirror (https://www.instructables.com/id/Easy-Infinity-Mirror-With-
Arduino-Gemma-NeoPixels/), on the Instructables Facebook page
(https://www.facebook.com/instructables/videos/10155489151836913/)!
Enter an Instructables contest!
If you've made an awesome project that uses Arduino, try writing an instructable about it and
entering it in our Wireless (https://www.instructables.com/contest/wireless2017/), Make it Move
(https://www.instructables.com/contest/mim2017/), or LED
(https://www.instructables.com/contest/led2017/) contests to win some great prizes!

Class Author:
bekathwia (/member/bekathwia/)
Becky Stern (https://www.instructables.com/member/bekathwia/) 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 (https://www.youtube.com/c/beckystern), 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 defines several layers of your experience:

software - used to compose your programs and communicate with the hardware, called an integrated
development environment (Arduino IDE)
hardware - refers to the boards themselves (e.g. Arduino Uno)

programming language - the Arduino programming language is based on C


trademark - Other brands may manufacture Arduino-compatible hardware, but only some boards are official,
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 find 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.

Arduino Class: Page 4


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 5


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.

Arduino Class: Page 6


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 confidence to take on infinite Arduino projects in the future!

Arduino Class: Page 7


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
(https://www.adafruit.com/wishlists/410578). 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
(https://www.adafruit.com/products/193). If you're using a different kit, some of the components may differ
from those shown in the photos throughout this class.

For the basic exercises:

Computer running Arduino software (https://www.arduino.cc/en/Main/Software)

Adafruit Arduino Uno Budget Pack (https://www.adafruit.com/products/193)


Arduino Uno board (https://www.adafruit.com/products/50)

USB A-B cable (https://www.adafruit.com/products/62)


Half-sized breadboard (https://www.adafruit.com/products/64)

Breadboard wires (https://www.adafruit.com/products/153)

10K potentiometer (https://www.adafruit.com/products/356)

Arduino Class: Page 8


2 small pushbuttons (https://www.adafruit.com/products/367)
5 red diffused 5mm LEDs (https://www.adafruit.com/products/299)

Bright red (https://www.adafruit.com/products/297), green

(https://www.adafruit.com/products/300), and blue (https://www.adafruit.com/products/301) LEDs


(one each or an RGB LED (https://www.adafruit.com/products/159))

5 220-1K ohm resistors (https://www.adafruit.com/products/2780) (all same value, any value


within range OK)

5 10K ohm resistors (https://www.adafruit.com/products/2784)

Plastic mounting plate for breadboard and Arduino (https://www.adafruit.com/products/275)

Small flathead screwdriver (https://www.adafruit.com/products/424)


Small DC motor (https://www.adafruit.com/products/711), PN2222 transistor

(https://www.adafruit.com/product/756), and 1N4001 diode (https://www.adafruit.com/products/755)

To complete the Skills Infusion lesson (here's a great toolkit with almost everything you need
(https://www.adafruit.com/products/136)):

Soldering iron (https://www.amazon.com/dp/B01DUPRXCE/?tag=instructabl09-20) and solder

(https://www.adafruit.com/product/145)
1 meter of 60/m RGBW NeoPixel strip (https://www.adafruit.com/products/2837)

Small needlenose pliers (https://www.adafruit.com/product/146)


Flush diagonal cutters (https://www.amazon.com/dp/B00FZPDG1K/?tag=instructabl09-20)

Wire strippers (https://www.amazon.com/dp/B00FZPHMUG/?tag=instructabl09-20)

Multimeter (https://www.adafruit.com/products/2034) (optional but very handy)


Tweezers (https://www.amazon.com/dp/B01HB46J8E/?tag=instructabl09-20)

Third hand tool (https://www.amazon.com/dp/B010C504NK/?tag=instructabl09-20)


Desoldering braid (https://www.adafruit.com/products/149) or solder sucker

(https://www.amazon.com/dp/B002MJMXD4/?tag=instructabl09-20)

Recommended vendors for Arduino components & accessories:

Adafruit (https://www.adafruit.com/category/17) (& distributors (https://www.adafruit.com/distributors))

(worldwide)
Arduino.cc store (https://store.arduino.cc/) (worldwide)

Understanding the Tools

Arduino Class: Page 9


Arduino Uno (https://www.arduino.cc/en/Main/ArduinoBoardUno) - 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 (https://www.sparkfun.com/products/12757) or Seeeduino V4.2
(https://www.seeedstudio.com/Seeeduino-V4.2-p-2517.html), just make sure you have the right USB
cable.

Arduino Class: Page 10


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

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
(https://www.instructables.com/class/Electronics-Class/) or LEDs & Lighting class
(https://www.instructables.com/class/LEDs-and-Lighting-Class/).

Arduino Class: Page 11


Soldering tools (https://www.adafruit.com/products/136) - The Skills Infusion lesson teaches you how to
connect wires to LED strip with a soldering iron, which heats the components enough to flow solder
(https://www.adafruit.com/product/145) (an easy melting alloy) between them. Any basic iron
(https://www.adafruit.com/products/180) will do! Wire strippers (https://www.adafruit.com/products/147)
remove insulation to expose the conductor inside, pliers (https://www.adafruit.com/product/146) and
tweezers (https://www.adafruit.com/products/421)help you position components, and a third hand tool
(https://www.adafruit.com/products/291) helps keep everything steady. Flush snips
(https://www.adafruit.com/product/152) 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 12


RGBW NeoPixel strip (https://www.adafruit.com/products/2837) - 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 find this strip by searching for "WS2812b RGBW strip" on your favorite supplier's
site. The sample code provided in this class will not work with RGB (no white) strip, analog LED strip,
or with any other kind of digital control chip (like APA104 aka DotStar).

Arduino Class: Page 13


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 (https://www.arduino.cc/en/Main/Software) 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 (flat 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
(https://www.arduino.cc/en/Guide/ArduinoUno). If you prefer not to download software, most of the class
can also be completed using the Arduino Web Editor (https://create.arduino.cc/editor).

Open the Arduino application and load up the first code example by selecting File -> Examples ->
01.Basics -> Blink.
Arduino Class: Page 14
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 flash, and the software will show a message "Done uploading." Moments later the LED
labeled L will begin blinking as it did when you first 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 first 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 (https://www.arduino.cc/en/Guide/Troubleshooting), which covers many other
common issues.

Arduino Class: Page 15


Arduino History

The origin story of Arduino (https://en.wikipedia.org/wiki/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 specifically by artists and designers. They held workshops and
seminars using the boards throughout different iterations, which were programmed using Wiring, a creative
coding platform developed by Hernando Barragán (https://arduinohistory.github.io/). 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 (https://www.arduino.cc/en/Main/ArduinoBoardUno) we'll use in this class is the flagship
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 16


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 (https://www.arduino.cc/en/Main/Boards).

Other boards with specialized functions have been released in the Arduino product line. Need more inputs
and outputs? Use an Arduino Mega (https://www.arduino.cc/en/Main/ArduinoBoardMega2560). Want a
smaller circuit board and USB keyboard functionality? Use an Arduino Micro

Arduino Class: Page 17


(https://www.arduino.cc/en/Main/ArduinoBoardMicro). And so forth. Official Arduino boards are all natively
supported by the Arduino software.

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 specific 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 (https://www.sparkfun.com/products/12757) or Adafruit
Metro (https://www.adafruit.com/products/2488). More compact boards for building tidy small circuits like
the Pro Trinket (https://www.adafruit.com/products/2000) and Pro Mini
(https://www.sparkfun.com/products/11113) make it easy to translate your breadboard prototype to a
finished project. Complex boards like the Huzzah (https://www.adafruit.com/products/2821) (wifi), Touch
Board (http://www.bareconductive.com/shop/touch-board/) (capacitive touch + audio playback), and Circuit
Playground (https://www.adafruit.com/products/3000) (beginner lessons baked into the board) empower
beginners to accomplish very sophisticated projects with ease.

Arduino Class: Page 18


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 workflow.

First, set yourself up for success by affixing your Arduino Uno board and solderless breadboard to a
mounting plate. Trust me on this one—it provides a huge benefit of holding your prototypes together and
Arduino Class: Page 19
keeping them out of trouble! The solderless breadboard has a sticker back you can peel off (peel off 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 fit. 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 (https://www.arduino.cc/en/Main/Software)


Some of the items from the Adafruit Arduino Uno Budget Pack (https://www.adafruit.com/products/193):

Arduino Uno board (https://www.adafruit.com/products/50)

USB A-B cable (https://www.adafruit.com/products/62)

Half-sized breadboard (https://www.adafruit.com/products/64)

Breadboard wires (https://www.adafruit.com/products/153)


5 red diffused 5mm LEDs (https://www.adafruit.com/products/299)

Bright red (https://www.adafruit.com/products/297), green

(https://www.adafruit.com/products/300), and blue (https://www.adafruit.com/products/301) LEDs

(one each or an RGB LED (https://www.adafruit.com/products/159))

5 220-1K ohm resistors (https://www.adafruit.com/products/2780) (all same value, any value


within range OK)

Plastic mounting plate for breadboard and Arduino (https://www.adafruit.com/products/275)

Small flathead screwdriver (https://www.adafruit.com/products/424)

Arduino Class: Page 20


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 flow
between the things you plug into it.

Arduino Class: Page 21


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 find yourself referring back to the
photo of the inside of the breadboard frequently; that's perfectly normal!

Arduino Class: Page 22


Blink Circuit

The first 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 23


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 configuration 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 24


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 first circuit, all of your connections should be composed on the half of the
breadboard closest to the Arduino board.

Arduino Class: Page 25


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 26


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

Arduino Class: Page 27


Now grab a red LED (light emitting diode). 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.

https://player.vimeo.com/video/192704689

Another way to guess the polarity of an LED is by looking inside the lens at the anvil (bigger piece of

Arduino Class: Page 28


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
(https://www.instructables.com/lesson/LEDs-Lesson/) in the Instructables LEDs & Lighting Class
(https://www.instructables.com/class/LEDs-and-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:

https://circuits.io/circuits/2932781-blink/embed#breadboard

Click "Start Simulation" to run the Arduino emulator, which has the "blink" sample program loaded up. We'll
use Autodesk 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
Editor" button to see the program, called an Arduino sketch. It looks like this:

https://create.arduino.cc/editor/Bekathwia/4735007d-fb84-4464-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 find 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 first code, which can cause confusing errors. The examples come in handy is
when you want to fix up your own not-working code (called debugging). Comparing your work to definitive
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 comment, meant to help humans understand the program. In Arduino programs, comments
are signified with two slashes; anything on a single line after the slashes is discarded when it comes time
to compile (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.

Arduino Class: Page 29


int led = 13;

Next up is a variable declaration. You can think of a variable as a bucket for some information. Variables,
like buckets, have sizes and shapes to hold different kinds of information. Variables also have names, like
a mandatory label on the bucket. This line of code defines 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!

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 configurations 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 setup, a
section of code that runs once per session. Code inside the setup executes one time when your board first
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 function, 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 arguments. 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 (off) state. These pieces of information passed to functions are called arguments.
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

is another one of Arduino's built-in functions. It pauses the program for an amount of time, written in
delay();

milliseconds. This line of code pauses the program for 1000ms, or one second.

Arduino Class: Page 30


digitalWrite(led, LOW); // turn the LED off by making the voltage LOW

As earlier, digitalWrite(); can turn an output pin on or off. This time it sets pin 13 LOW (off).

delay(1000); // wait for a second


}

This line pauses the program for one second, and the curly brace signifies the end of the loop, which
begins again immediately. So to summarize, the program turns an LED on and off 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 modified 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 (https://www.arduino.cc/en/Reference/HomePage), which describes each element and
provides sample usage.

Arduino Class: Page 31


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.

Arduino Class: Page 32


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 configuration,
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.

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 difference 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 polarity and only light up when electricity flows 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 Autodesk Circuits module (Arduino
pins 3-5 to the remaining LEDs' positive leads).

https://circuits.io/circuits/2932830-for-loop-iteration/embed#breadboard

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 Editor" button to see
the code, and then click the "Download Code" button. 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
.zip file to expand it, and double click on the "ForLoopIteration.ino" file to open it.

Click OK if you see a prompt to put the program in its own folder. If your resulting file 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 (https://www.arduino.cc/en/Main/Software). If you prefer, you may also select and copy the code

Arduino Class: Page 33


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).

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.

http://www.arduino.cc/en/Tutorial/ForLoop
*/

This first part is just a long comment. You already learned about single line comments, and now you know
about multi-line comments, signified 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 semicolon. 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 configures pins 3 through 7 as outputs using a for loop, which is a special loop that repeats a
small section of code a certain number of times based on a condition, using an increment counter. 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 first 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 efficiency! You could just as easily accomplish the pin configurations with the
following setup:

Arduino Class: Page 34


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 for loop 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 off 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 final 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://cdn.instructables.com/ORIG/FAL/YLM1/J1V7XOEX/FALYLM1J1V7XOEX.ino)
http://www.instructables.com/ORIG/FAL/YLM1/J1V7XOEX/FALYLM1J1V7XOEX.ino

(https://cdn.instructables.com/ORIG/FAL/YLM1/J1V7XOEX/FALYLM1J1V7XOEX.ino)

Arduino Class: Page 35


Fade

Turning LEDs on and off 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 first LED from your breadboard,
and move its yellow wire connection to Arduino pin 9.

https://circuits.io/circuits/2932897-fade/embed#breadboard

Copy/download the code from the Autodesk 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 off.

Arduino Class: Page 36


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 different parts of the code.

https://create.arduino.cc/example/builtin/01.Basics%5CFade/Fade/preview?embed

Lines 16 through 18 declare three variables used in the program. The setup configures 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 statement to check if
brightness using comparison operators (https://www.arduino.cc/en/Reference/If). 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 effect. Try changing the value of
fadeAmount and upload the code to your board. How does changing this variable affect 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 off using pulse width modulation (PWM). The
LED flashes on and off very quickly, and your eye interprets a dimmer light. The ratio of time the LED
spends on vs. off 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

Additive (light-based) color (https://en.wikipedia.org/wiki/RGB_color_model) 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 final 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
Arduino Class: Page 37
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 different kit, just find 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 find the red one on the first try, set it aside and repeat the process to
determine the color of the the other two LEDs.

https://circuits.io/circuits/2932972-super-simple-rgb-led/embed#breadboard

Arduino Class: Page 38


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 Autodesk 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, defined below the loop() has
ended.

void setColor(int red, int green, int blue)


{
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}

A function definition declares a name, and what type of arguments the function will take, which you can think of as the
configurable 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 defined using one byte
(https://web.stanford.edu/class/cs101/bits-bytes.html), which allows for 256 distinct patterns.

https://circuits.io/circuits/2933014-color-cross-fading-rgb-led/embed#breadboard

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 (https://www.arduino.cc/en/Reference/Array)
to store colors, and three user-defined 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 first it's time to celebrate all you've achieved so far.

Arduino Class: Page 39


LESSON 3: INPUT/OUTPUT

So far you've learned to control LEDs with code, which is one use of Arduino's outputs. This lesson builds
on outputs by adding inputs. 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 switch, and an analog
input circuit with a potentiometer (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 (https://www.instructables.com/lesson/Switches/) in the Instructables Electronics class
(https://www.instructables.com/class/Electronics-Class/).

A variable resistor 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 (https://learn.adafruit.com/force-sensitive-resistor-fsr/overview?
view=all#overview) aka FSR), light dependent resistors (https://learn.adafruit.com/photocells/overview?
view=all) (LDR aka photoresistor), and analog temperature sensors (https://learn.adafruit.com/tmp36-
temperature-sensor/overview?view=all).

Arduino Class: Page 40


Supplies

To follow along with this lesson you will need:

Computer running Arduino software (https://www.arduino.cc/en/Main/Software)

Some of the items from the Adafruit Arduino Uno Budget Pack (https://www.adafruit.com/products/193)

Arduino Uno board (https://www.adafruit.com/products/50)

USB A-B cable (https://www.adafruit.com/products/62)

Half-sized breadboard (https://www.adafruit.com/products/64)

Breadboard wires (https://www.adafruit.com/products/153)


10K potentiometer (https://www.adafruit.com/products/356)

1 small pushbutton (https://www.adafruit.com/products/367)

1 red diffused 5mm LED (https://www.adafruit.com/products/299)

1 220-1K ohm resistor (https://www.adafruit.com/products/2780) (any value within range OK)

1 10K ohm resistor (https://www.adafruit.com/products/2784)

Plastic mounting plate for breadboard and Arduino (https://www.adafruit.com/products/275)


Small DC motor (https://www.adafruit.com/products/711)

(https://www.adafruit.com/products/711)PN2222 transistor (https://www.adafruit.com/product/756)

(https://www.adafruit.com/product/756)1N4001 diode (https://www.adafruit.com/products/755)

Arduino Class: Page 41


Digital Input

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.

Arduino Class: Page 42


First, connect the LED to Arduino pin 13 like you did in your first 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.

Arduino Class: Page 43


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 44


Connect the switch's diagonal lead to ground.

https://circuits.io/circuits/2933067-button/embed#breadboard

Click "Start Simulation" in the Autodesk Circuits module and try clicking the pushbutton to see what the
code does. Click the "Code Editor" button to see the sketch.

You can find 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 off whenever you press the pushbutton.
Arduino Class: Page 45
Follow along as we explore the code in more detail.

https://create.arduino.cc/example/builtin/02.Digital%5CButton/Button/preview?embed

The first lines of this program introduce constants, 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
configures 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
(https://www.arduino.cc/en/Reference/If), not to be confused with = , which is an assignment operator
(https://www.arduino.cc/en/Reference/Assignment)). 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 (https://www.arduino.cc/en/Reference/Else).

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

Arduino Class: Page 46


resistor is "pulling the pin up" to 5V, and so it's called a pull-up resistor. Without one, pin 2 would be not
connected to anything until the button is pressed. This is called "floating", 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-down resistor.

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 off.

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 47


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

https://circuits.io/circuits/2933173-digital-read-serial/embed#breadboard

This circuit uses the same button configuration as the previous digital input circuit, but just doesn't use the
LED. Load up the code from this module or find 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.

Arduino Class: Page 48


To create a serial connection, you should use Serial.begin(); inside your setup. The number 9600 is the baud
rate, 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
(https://www.arduino.cc/en/Reference/Serial).

Arduino Class: Page 49


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
(https://en.wikipedia.org/wiki/Kilobyte). Grab one of the blue potentiometers from your kit and plug it into
three rows on your breadboard (with your USB disconnected).

https://circuits.io/circuits/2933191-analog-in-serial-out/embed#breadboard

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.

Arduino Class: Page 50


You can get the code from the Autodesk Circuits module as you have for previous lessons, or find 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 first 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:

This sketch uses the map(); function on line 39, which takes one range of numbers and massages it into
another range. It takes five 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
Arduino Class: Page 51
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() (https://www.arduino.cc/en/Reference/Map); work. Keep this
in mind when composing and troubleshooting your own sketches!

Arduino Class: Page 52


A Moment for Motors

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 motor. 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 transistor (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 flow
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.

https://circuits.io/circuits/3034234-analog-in-serial-out-dc-motor/embed#breadboard

Unplug your USB cable and build the circuit according to the diagram, minding the flat 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 different NPN transistor (like the 2N2222), your transistor pin
connections may be different 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 effect 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):

https://circuits.io/circuits/3652300-analog-in-serial-out-dc-motor-with-external-power/embed#breadboard

To learn more about transistors and use them in a project, check out the transistors lesson
(https://www.instructables.com/lesson/Transistors/) in the Instructables Electronics Class
(https://www.instructables.com/class/Electronics-Class/). To learn more about motors and use them to
build several fun robots, check out the Instructables Robots Class
(https://www.instructables.com/class/Robots-Class/).

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 53


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.

Arduino Class: Page 54


Supplies

To follow along with this lesson you will need:

Soldering iron (https://www.adafruit.com/products/180) and solder (https://www.adafruit.com/product/145)

1 meter of 60/m RGBW NeoPixel strip (https://www.adafruit.com/products/2837) (or other WS2812b RGBW

LED strip)

Breadboard wires (https://www.adafruit.com/products/153)

Small needlenose pliers (https://www.adafruit.com/product/146)


Flush diagonal cutters (https://www.adafruit.com/product/152)

Wire strippers (https://www.adafruit.com/products/147)

Multimeter (https://www.adafruit.com/products/2034) (optional but very handy)

Tweezers (https://www.adafruit.com/products/421)

Third hand tool (https://www.adafruit.com/products/291)

Desoldering braid (https://www.adafruit.com/products/149) or solder sucker

(https://www.adafruit.com/products/148)

Small pushbutton (https://www.adafruit.com/products/367)

Arduino Uno board (https://www.adafruit.com/products/50) and solderless breadboard

(https://www.adafruit.com/products/64) on a mounting plate (https://www.adafruit.com/products/275)

USB A-B cable (https://www.adafruit.com/products/62)

Arduino Class: Page 55


Soldering

Soldering 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 off (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
tinning the soldering iron. Repeat this cleaning and tinning procedure regularly while using the soldering
iron to prevent buildup of excess solder and oxidation.

Arduino Class: Page 56


Soldering works by heating up the metal components to be joined, then allowing low temperature alloy
solder to melt and flow 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 flux (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 flux 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 cold solder, which prevents
electrons from flowing 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 caffeine 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.

Prep three of your breadboard wires by cutting off 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 flush 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,
Arduino Class: Page 57
and reheat the two components at the same time. The solder on each should flow 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 find it difficult or too hot to hold the wire with your fingers,
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)!

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
copper desoldering braid 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 flow. Set this pushbutton aside for the
final project.

Arduino Class: Page 58


Addressable LEDs and Code Libraries

Now that the strip is soldered, we'll need to program the Arduino to turn the LEDs on. NeoPixel is the
Adafruit brand name for WS2812 addressable "smart" LED strip (as opposed to analog LED strip
(https://www.instructables.com/lesson/LED-Strips/)). 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 code library. 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...

Arduino Class: Page 59


When the Library Manager opens, search for "NeoPixel" in the upper right field. 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.

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 first 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.

Arduino Class: Page 60


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.

https://circuits.io/circuits/2932683-rgbw-strand-test/embed#breadboard

Download/copy the code from the Autodesk Circuits module 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 61


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 first section instantiates the NeoPixel strip and sets up the configurable 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.

Arduino Class: Page 62


void setup() {

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

is used any time you want the pixels to change. Setting the pixel colors and showing the latest
strip.show();

changes are broken up into two separate commands.

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(); , defined 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 definition starts with what type of data the function will return, or send back to the main
program. In this case the function returns nothing, so the word void is used at the start of the definition.
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 local variables 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.

Arduino Class: Page 63


Write Your Own Functions

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

// 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
(https://www.arduino.cc/en/Reference/Random) 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 find an effect 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 definition:

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 64


Arduino Class: Page 65
Arduino Class: Page 66
Learning to Fish

You've made it to the end! What follows are some parting words of advice for venturing off 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 first.
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.

Google with gusto - 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 (https://forum.arduino.cc/) and Adafruit
(https://forums.adafruit.com/) forums, where most beginner roadblocks are solved many times over. Say it
with me: "I bet I can find someone online who's had this question before; I just have to find it."

Sharing (code) is caring - Arduino is built on open source ideas. Innovation flourishes when technology is
shared! You'll find 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.

Document your process - 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 find yourself wanting to look back at previous iterations to avoid making the same mistakes twice.
Additionally, you'll find 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.

Protect the power supply - 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
fire.

Strain relief - 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
(https://www.instructables.com/class/Hand-Sewing-Class/). For connections that will bend repeatedly, use
stranded wire instead of solid-core.

Arduino Class: Page 67


Know your adhesives - 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
(http://www.amazon.com/dp/B0002UEPVI/?tag=instructabl09-20) 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 infinity mirror project in this class, but it stinks for durability. Instead I highly
recommend E6000 craft adhesive (http://www.amazon.com/dp/B0018NBWVO/?tag=instructabl09-20), or
its cousin Quick Hold. These take longer to dry but stick to everything (except silicone) and dry clear and
flexible. To learn more about adhesives, check out our Glue class
(https://www.instructables.com/class/Glue-Class/)!

Humidity & moisture - 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 find 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 and temperature fluctuation exposure - 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 fields 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 68


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 Infinity Mirror with Arduino Gemma
(https://www.instructables.com/id/Easy-Infinity-Mirror-With-Arduino-Gemma-NeoPixels/). You may also
find many of the early code examples to be great starting points when building your own sketches. For your
next class, consider Internet of Things (https://www.instructables.com/class/Internet-of-Things-Class/),
Electronics (https://www.instructables.com/class/Electronics-Class/), Wearable Electronics
(https://www.instructables.com/class/Wearable-Electronics-Class/), or Robots
(https://www.instructables.com/class/Robots-Class/), 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


Word Clock (https://www.instructables.com/id/The-Word-Clock-Arduino- (https://www.instructables.com/id/Secret-Knock-
version/) by drj113 Detecting-Door-Lock/) by Grathio

HC-SR04 Distance Sensor Instagram Inspired DIY Photo-Booth


(https://www.instructables.com/id/Simple-Arduino- (https://www.instructables.com/id/Instagram-
and-HC-SR04-Example/) by jsvester Inspired-DIY-Photo-Booth/) by alexandermorris

Self-Watering Plant Existential Emergency Phone


(https://www.instructables.com/id/Self-Watering- (https://www.instructables.com/id/Existential-
Plant/) by randofo 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 69

Вам также может понравиться