Professional Documents
Culture Documents
ARDUINO CLASS
LESSON 2: Your First Experiments
with bekathwia
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.
Supplies
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.
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!
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.
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.
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
metal) and post (smaller piece of metal). The anvil is usually the cathode, but as you can see in the
above video, not all LEDs observe the same polarity conventions. The only way to be totally certain
of its polarity is to test it. To learn more in-depth about resistors and LEDs, check out the LEDs
lesson in the Instructables LEDs & Lighting Class.
Plug in your USB cable and the LED should immediately start to blink! It's programmed to blink
whatever's connected to pin 13. That includes the onboard LED you saw in your software setup as
well as the one you just wired up.
If your LED isn't blinking, unplug your USB cable, then reverse your LED and replug your USB;
maybe the LED was just plugged in backwards (which won't damage it, but won't light it up, either).
Or perhaps one of your other wires or resistor aren't connected correctly. Double check your
connections against the diagram of the circuit:
https://www.tinkercad.com/embed/heWjQPZNfIg?zoom=false
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
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.
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
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
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).
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, 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.
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.
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 Tinkercad Circuits module
(Arduino pins 3-5 to the remaining LEDs' positive leads).
https://www.tinkercad.com/embed/6XeW1sjPzXN?zoom=false
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. 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).
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:
The circuit:
* LEDs from pins 3 through 7 to ground
created 2006
by David A. Mellis
modified 30 Aug 2011
by Tom Igoe
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:
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!
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.
Attachments
Download
http://www.instructables.com/ORIG/FAL/YLM1/J1V7XOEX/FALYLM1J1V7XOEX.ino
…
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://www.tinkercad.com/embed/bo3zmg7hInW?zoom=false
Plug in and upload the sketch to your Arduino Uno board and observe your LED fade on and off.
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. 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 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 three 5mm LEDs in
your kits. In the Adafruit kit recommended for this class, these three LEDs have clear lenses, so we'll
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://www.tinkercad.com/embed/jTfaA3ssc6S
Wire up the other two LEDs with 1K resistors to pins 10 and 11, as shown in the diagram. Download
and open the code from the Tinkercad Circuits module or copy and paste it into a new empty Arduino
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(); .
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, which
allows for 256 distinct patterns.
https://www.tinkercad.com/embed/bclfJGFygLR?zoom=false