Getting Started With Arduino
by bekathwia in Circuits > Arduino
42314 Views, 340 Favorites, 0 Comments
Getting Started With Arduino
This instructable is a lesson in my free Arduino Class. To enroll, click here.
Roll up your sleeves and let's dig in! In this lesson, we're getting started with Arduino. 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 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.
To keep up with what I'm working on, follow me on YouTube, Instagram, Twitter, Pinterest, and subscribe to my newsletter.
Supplies
To follow along with this lesson you will need:
- Computer running Arduino software
- Some of the items from a standard Arduino/compatible starter kit (Arduino | Adafruit | Sparkfun | Amazon):
- Arduino Uno or compatible board (Arduino | Adafruit | Sparkfun | Amazon)
- USB A-B cable
- Half-sized breadboard
- Breadboard wires
- 5 red diffused 5mm LEDs
- Bright red, green, and blue LEDs (one each or an RGB LED)
- 5 220-1K ohm resistors (all same value, any value within range OK)
- Plastic mounting plate for breadboard and Arduino
- Small flathead screwdriver
As an Amazon Associate I earn from qualifying purchases you make using my affiliate links.
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.
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!
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.
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.
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.
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.
Plug the other end into a row right next to the yellow wire.
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.
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:
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:
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.
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
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).
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, which describes each element and provides sample usage.
Add More LEDs
Now that you've got the basic idea of how to control a single LED, let's add some more! Grab the rest of your red LEDs and 1K resistors. Unplug your Arduino from USB/power if it wasn't already. It's smart to disconnect power any time you are changing your circuit.
Connect the two pairs of rails on your solderless breadboard: plug a wire connecting both power buses (red, +) and another wire connecting both ground buses (blue, -). This is a commonly used 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 Tinkercad Circuits module (Arduino pins 3-5 to the remaining LEDs' positive leads).
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. 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:
/* For Loop Iteration Demonstrates the use of a for() loop. Lights multiple LEDs in sequence, then in reverse. The circuit: * LEDs from pins 3 through 7 to ground created 2006 by David A. Mellis modified 30 Aug 2011 by Tom Igoe This example code is in the public domain. <a href="http://www.arduino.cc/en/Tutorial/ForLoop"> <a href="http://www.arduino.cc/en/Tutorial/ForLoop"> http://www.arduino.cc/en/Tutorial/ForLoop </a> </a> */
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!
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.
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.
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.
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.
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 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.
Wire up the other two LEDs with 1K resistors to pins 10 and 11, as shown in the diagram. Download and open the code from the Tinkercad Circuits module or copy and paste it into a new empty Arduino sketch. Upload it to your Arduino Uno board and see if you can match up the lines of code to the activity you see in the LEDs, as we have done together so far.
The unfamiliar part of this code is the function setColor();
. It's a custom function, 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, which allows for 256 distinct patterns.
Now download and open the code from this more complex RGB project, or copy and paste the code into a new blank Arduino sketch. Read its comments to learn more about how this program works. It does some math to convert a 0-100 range to the necessary range the LEDs need, so you can think in percentages instead of 0-255. It uses collections of variables called arrays to store colors, and three user-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. Take a picture of one of your circuits from this lesson and post it in the Class Project module at the bottom of the lesson, so I can give you a virtual high five!