Arduino - Your First Experiments
Arduino - Your First Experiments
Enroll
Your First
(/) Experiments
with bekathwia (/member/bekathwia/) in ARDUINO CLASS (/class/Arduino-Class/)
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 Enroll
First, set yourself up for success by af 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 off (peel off the mounting plate's paper
backing as well), and the Arduino Uno attaches with screws from the underside. It
Arduino Class Enroll
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:
(https://www.adafruit.com/products/159))
5 220-1K ohm resistors (https://www.adafruit.com/products/2780) (all same
Solderless Breadboards
Arduino Class Enroll
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 Enroll
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!
Blink Circuit
Arduino Class Enroll
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 Enroll
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 Enroll
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.
Arduino Class Enroll
Connect another blue wire from any pin on your ground rail to another horizontal row
on your breadboard (row 18 shown above).
Arduino Class Enroll
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 Enroll
Plug the other end into a row right next to the yellow wire.
Arduino Class Enroll
Arduino Class Enroll
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
Arduino Class Enroll
resistor helps limit the current going through an LED, which doesn't do a great job of
limiting itself.
00:08
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
(https://www.instructables.com/lesson/LEDs-Lesson/) in the Instructables LEDs &
Lighting Class (https://www.instructables.com/class/LEDs-and-Lighting-Class/).
Arduino Class Enroll
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:
Arduino Class Enroll
Blink Iniciar simulação Código
Texto
Click "Start Simulation" to run the Arduino emulator, which has the "blink" sample
program loaded up. We'll use Tinkercad Circuits (https://www.tinkercad.com/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 sketch. It looks
like this:
Arduino Class Enroll
Blink by Bekathwia
Blink.ino ReadMe.adoc
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 debugging). 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
Arduino Class Enroll
note:
This is just a comment, 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 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.
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 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!
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.
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 rst powers up, or when you press the Arduino's
reset button.
Arduino Class
// initialize the digital pin as an output. Enroll
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.
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.
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(); is another one of Arduino's built-in functions. It pauses the program for an
amount of time, written in milliseconds. This line of code pauses the program for
1000ms, or one second.
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).
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 (https://www.arduino.cc/en/Reference/HomePage),
which describes each element and provides sample usage.
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 Enroll
Connect the two pairs of rails on your solderless breadboard: plug a wire connecting
Arduino Class Enroll
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.
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.
Arduino Class Enroll
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.
Arduino Class Enroll
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
ows in one particular direction through them.
Arduino Class Enroll
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.
Arduino Class Enroll
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).
Finishing
Find this circuit on Tinkercad (https://www.tinkercad.com/things/6XeW1sjPzXN-for-
Arduino Class Enroll
loop-iteration)
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
(https://www.arduino.cc/en/Main/Software). 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 Enroll
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
The circuit:
* LEDs from pins 3 through 7 to ground
created 2006
by David A. Mellis
modified 30 Aug 2011
by Tom Igoe
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.
Arduino Class Enroll
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 con gures 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 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 ef ciency! You could just as easily
accomplish the pin con gurations with the following setup:
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() {
Arduino Class Enroll
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.
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.
ForLoopIteration.ino
Download (https://cdn.instructables.com/ORIG/FAL/YLM1/J1V7XOEX/FALYLM1J1V7XOEX.ino)
(https://cdn.instructables.com/ORIG/FAL/YLM1/J1V7XOEX/FALYLM1J1V7XOEX.ino)
Fade
Arduino Class Enroll
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 rst LED from your breadboard, and move its yellow wire connection to
Arduino pin 9.
Arduino Class Enroll
Fade Iniciar simulação Código
Finishing
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 off.
Arduino Class Enroll
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.
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 ashes 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 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 different 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.
Arduino Class Enroll
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.
Finishing
Find this circuit on Tinkercad (https://www.tinkercad.com/things/jTfaA3ssc6S-super-
Arduino Class Enroll
simple-rgb-led)
Arduino Class Enroll
Wire up the other two LEDs with 1K resistors to pins 10 and 11, as shown in the
Arduino Class Enroll
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.
A function de nition 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 (https://web.stanford.edu/class/cs101/bits-bytes.html),
Arduino Class Enroll
which allows for 256 distinct patterns.
Finishing
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-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.
Class Project
Share a photo of your finished project with the class!
I Made It!
Arduino Class
« Previous (/lesson/Tools-and-Materials-for-Arduino/) Next » (/lesson/InputOutput/)
Enroll
Ask a Question
Connection Error?
Connection Error?
Answered 1 Answer
Error message?
Answered 1 Answer
Autodesk Circuits?
Answered 1 Answer
connection?
Answered 1 Answer
different board?
Answered 2 Answers
F
More Questions
Categories About
Us
Technology (/technology/)
Workshop (/workshop/) Who We
Craft (/craft/) Are
Home (/home/) (/about/)
Food (/food/) Why
Play (/play/) Publish?
Outside (/outside/) (/create/)
Costumes (/costumes/) Jobs
(/topics/Positions-
available-
at-
Instructables/)
Contact
(/contact/)
Resources Find Us
Community
(/topics/)
Sitemap (http://www.instagram.com/instructables/)
(/sitemap/)
Help (/id/how-to-
(http://www.pinterest.com/instructables)
write-a-great-
instructable/)
(http://www.facebook.com/instructables)
(http://www.twitter.com/instructables)