Docsity
Docsity

Prepare-se para as provas
Prepare-se para as provas

Estude fácil! Tem muito documento disponível na Docsity


Ganhe pontos para baixar
Ganhe pontos para baixar

Ganhe pontos ajudando outros esrudantes ou compre um plano Premium


Guias e Dicas
Guias e Dicas


Arduino - book3, Notas de estudo de Eletrônica

Arduino-book3

Tipologia: Notas de estudo

2017

Compartilhado em 07/11/2017

vinicius-tomaz-4
vinicius-tomaz-4 🇧🇷

4.5

(2)

14 documentos

1 / 264

Toggle sidebar

Esta página não é visível na pré-visualização

Não perca as partes importantes!

bg1
iii
Preface ........................................ vii
1. Introduction ................................... 1
Building Philosophy .......................................................... 1
Reusing Parts ................................................................ 4
Buying Components ......................................................... 6
Useful Tools ..................................................................7
Electronic Circuit Theory Review ............................................14
2. Arduino: The Brains of an Embedded
System ........................................ 17
Why Arduino? ............................................................... 17
Starting with Arduino .......................................................18
Hello World with Arduino ................................................... 22
Structure of “Hello World” ...................................................25
Arduino Uno ................................................................ 27
Arduino Nano ............................................................... 28
3. Stalker Guard ................................29
What You’ll Learn ............................................................30
Tools and Parts .............................................................. 30
Solderless Breadboard ...................................................... 31
Jumper Wire ................................................................33
Ping Ultrasonic Sensor ......................................................33
Vibration Motor ............................................................. 39
Combining Components to Make the Stalker Guard ....................... 41
Making the Motor Vibrate...................................................41
Providing Power from a Battery .............................................43
What’s Next? ................................................................ 43
Making an Enclosure ........................................................ 44
Contents
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Pré-visualização parcial do texto

Baixe Arduino - book3 e outras Notas de estudo em PDF para Eletrônica, somente na Docsity!

iii

17

Arduino: The Brains of an

Embedded System

In this chapter, you’ll compile a program you have

written onto an Arduino microcontroller, a small

computer that acts as the brains of an embedded

system. Arduino, an easy-to-learn hardware and

software development environment and prototyping

platform, is the foundation for the projects we’ll

complete in upcoming chapters.

A microcontroller is a small computer with a processor and memory that controls the functions of many everyday devices. Some microcontrollers are designed to connect easily to a computer for programming for specialized purposes. Arduino is an example of one of these easy-to-program microcontrollers.

Microcontrollers make it easier to build electronic devices because you can control their functions via code. Microcontrollers can control and interpret forms of both input and output. For example, you can flicker an LED by con- necting it to a specific Arduino pin with code that instructs it to switch the current on for one second and then off for one second. The LED is an example of an output, which you could then control using a sensor, button, switch, or any other form of input. Naturally, most programs do many other, more so- phisticated tasks. Microcontrollers enable us to solve quite complex problems step by step.

Why Arduino?

The most suitable microcontroller choices for a beginner are Basic Stamp and Arduino. Basic Stamp has existed since the early 1990s and has become popu- lar among hobbyists. It uses the Basic programming language, which is easy to use but somewhat limited compared to the C language used by Arduino.

In thIs chApter

Why Arduino? Starting with Arduino Hello World with Arduino Structure of “Hello World” Arduino Uno Arduino Nano

Starting with Arduino

18 Chapter 2

Functionally, Arduino is quite similar to Stamp, but it solves many problems that Stamp has traditionally faced. One significant feature for hobbyists is Arduino’s lower cost: the basic Arduino starting package is approximately a quarter of the price of a comparable Stamp package. And, despite its cheaper price, Arduino has a more powerful processor and more memory. Arduino is also smaller than Stamp, which is beneficial in many projects. The Arduino Uno model (see Figure 2-1, left) is slightly smaller than the Stamp, but the tiny Arduino Nano (Figure 2-1, right) is about the same size as the Stamp module that sits on the Stamp board (just above the serial port in Figure 2-2). For comparison, Figure 2-2 shows the Stamp and the Nano next to each other.

Figure 2-1. Arduino Uno (left) and Arduino Nano (right) Figure 2-2. Basic Stamp (left) and Arduino Nano (right)

One final asset is that the Arduino programming environment is based on open source code and can be installed on Windows, Mac OS X, and Linux.

Starting with Arduino Arduino is available in a few different models. This book covers the aforemen- tioned Arduino Uno and Arduino Nano. Uno is an inexpensive (around $30) and sturdy basic model, and is the most current version of the board. It was released publicly in September 2010 and is the successor to the Arduino Dieci- mila and Arduino Duemilanove. Nano is significantly smaller, but more fragile and slightly more expensive ($35). Both models are described in a bit more depth at the end of this chapter. First, you have to buy an Arduino and a compatible USB cable. Uno and Nano communicate to your computer via USB (for uploading new programs or send- ing messages back and forth). They can also take their power over USB. Uno uses a USB-B cable and Nano uses a Mini-B, and each connects to the computer with a USB-A male connector. All three connectors are shown in Figure 2-3.

Chapter 8 includes a project that uses Bluetooth. Although there is an Arduino model with built-in Bluetooth (Arduino BT), a more flexible option when you’re creating Bluetooth projects with Arduino is to use a third-party Bluetooth adapter, such as SparkFun’s Bluetooth Mate (http://www.sparkfun.com/prod- ucts/10393). This will allow you to use the Bluetooth module with differ- ent projects, or to replace Bluetooth in one of your projects with another type of wireless module such as an XBee radio.

Starting with Arduino

20 Chapter 2

b. Locate Arduino Uno in the list of devices (it should be in the section called Other Devices). Right-click it and choose Update Driver Software. c. Choose “Browse my computer for driver software.” d. Navigate to the Arduino folder you extracted, select the drivers subdi- rectory, and press Next. e. If prompted to permit the installation of this driver, choose “Install this driver software anyway.” When the driver is successfully installed, you’ll see the dialog shown in Figure 2-4.

Figure 2-4. Drivers installed

Windows XP

In general, installation for most Windows XP programs is pretty similar to Win- dows 7, but Arduino is an exception. If you have XP, start by downloading the Arduino development environment, extracting the file to a location on your computer, and connecting the Arduino to your computer as described in the previous section. Then follow these additional instructions:

  1. Windows opens the Found New Hardware Wizard.
  2. Select “Install from a list or specific location” in the window and press Next.

Arduino: The Brains of an Embedded System (^21)

Starting with Arduino

  1. Deselect the checkbox in “Search removable media” and check the box “Include this location in the search.” Navigate to the Arduino folder you extracted, select the drivers subdirectory, and press Next. If you are using an older model of Arduino, or the Nano, you may need to choose the drivers/FTDI USB Drivers subdirectory instead.
  2. Click Finish.

Ubuntu Linux

Though you can install Arduino on Ubuntu and other Linux environments using graphical user interface tools, the following steps use the Terminal (Figure 2-5) to simplify the instructions.

Open the Terminal by choosing Applications→Accessories→Terminal. The dollar sign at the beginning of the following command lines is the command prompt created by the computer; do not type the dollar sign, just the charac- ters that follow it.

We tested this installation process with Ubuntu 9.04, but it should also func- tion (with minor alterations) with other versions.

Figure 2-5. Command line

Start using the universe program repository, which includes free, open source programs, with publicly available source codes:

$ sudo software-properties-gtk --enable-component=universe

When asked by sudo, type your password. The command after sudo will be executed using root user privileges.

Before you try to install Arduino on Linux, consult the Arduino FAQ (http://arduino.cc/en/Main/ FAQ#linux) for links to the latest instructions.

Arduino: The Brains of an Embedded System (^23)

Hello World with Arduino

Linux Change directory to the Arduino folder and run Arduino: $ cd arduino- $ ./arduino

Mac OS X Double-click the Arduino icon (you’ll find it inside the Arduino folder).

Select Tools→Board→Arduino Uno, as shown in Figure 2-6. If you are using a different model of Arduino, select it instead.

Figure 2-6. Arduino board selection

Select File→Sketchbook→Examples→1. Basics→Blink. This example code flashes the LED on the Arduino pin 13 (the Uno includes an onboard LED con- nected to pin 13).

Determine which serial port Arduino is using:

Windows

Open the Start menu, right-click the computer icon, and select Properties. System Properties will open. On Windows XP, click Hardware. On Vista or Windows 7, look in the list of links to the left. Select Device Manager from the list and open the “Ports (COM & LPT)” node. See which COM port is marked as a USB COM port, as shown in Figure 2-7.

Hello World with Arduino

24 Chapter 2

Figure 2-7. Determine the correct port

Linux and Mac OS X With the Arduino unplugged from your computer, select Tools→Serial Port in the Arduino development environment, and observe the list of se- rial ports listed (such as /dev/ttyUSB0 in Linux or /dev/tty.Bluetooth-Modem in Mac OS X). Dismiss the menu by clicking elsewhere onscreen. Plug the Arduino in and choose the same menu options again (Tools→Serial Port). Observe which serial port appeared. You’ve figured out which serial port your Arduino is using. In the Arduino development environment, select Tools→Serial Port and choose the port you found in the previous step. Click the icon with the right-pointing arrow in a square box, or choose File→“Upload to I/O Board.” The Arduino transmission lights will flash briefly, and you should see the message “Done uploading.” Now you should see the yellow LED labeled L on the Arduino board flashing (see Figure 2-8). This means you have successfully installed the Arduino devel- opment environment and uploaded your first Arduino program to the micro- controller. If the light is not flashing, follow the instructions again to see where the installation went wrong. You cannot proceed if this does not work. If you continue to have problems, see the online Arduino troubleshooting guide at http://www.arduino.cc/en/Guide/Troubleshooting.

Structure of “Hello World”

26 Chapter 2

void loop() { 6 digitalWrite(13, HIGH); 7 // set the LED on delay(1000); 8 // wait for a second digitalWrite(13, LOW); 9 // set the LED off delay(1000); // wait for a second } Let’s review each section of the code. 1 A slash followed by an asterisk (/*) opens a block of comments (they are ended by a */). Two forward slashes (//) indicate that the rest of the line is a comment. Comments consist only of information for the user; Arduino does not react to them. Comments will be removed during the compiling process, and they are not uploaded into the Arduino. This comment states the title and purpose of the program (known as a sketch). Most comments describe the purpose of a specific line or block of code. 2 The setup() function executes once in the beginning of a program, where one-time declarations are made. The setup() function will be called automatically immediately after the Arduino is powered or has been programmed. Calling a function consists of a return value of a func- tion (void), the name of the function (setup), and a list of parameters in parentheses. This function does not take parameters, so there is nothing inside the parentheses. This function does not return values, so its type is void (empty). When calling a function, commands are listed within a block of code, which is enclosed in curly braces ({}). 3 This setup() function includes only one command, which sets the pin connected to the LED into output mode. It calls the pinMode() function, which is defined in the Arduino libraries. 4 OUTPUT is a constant defined within Arduino. When using digital pins on an Arduino, you must always declare them to be in either OUTPUT or INPUT mode. 5 As is required by the C language (which Arduino is based on), a line ends with a semicolon. 6 The majority of the execution time of the program will repeat the loop() function. The loop() function is called automatically (and repeatedly) after the setup() function finishes. 7 To address a digital pin that has been set to be an OUTPUT, we use the digitalWrite() function. Set digital pin 13 on HIGH (which means +5V). Digital pin 13 is unique in that Arduino has a built-in LED and resistor attached to it, specifically for debugging purposes. The LED will light up. The pin remains on HIGH until we address the pin with another call from digitalWrite(). 8 Wait 1,000 milliseconds (1,000 one-thousandths of a second, totaling one full second). The LED is lit all the time. 9 Switch the pin off (LOW) and wait again for a second. This is the last com- mand in the loop() function, which means that the execution of the loop() function ends.

An easy way to familiarize yourself with new functions is to highlight the name of the function (always in orange text), right-click, and select “Find in Reference.” Here you will find an explanation of usage, syntax, and an example.

Arduino: The Brains of an Embedded System (^27)

Arduino Uno

The program will call the loop() function over and over again automatically. The execution will continue from the first line of the loop() function, which sets the LED (ledPin) on HIGH. The execution of the program continues by repeating the loop() function until it is stopped by disconnecting power from the Arduino.

Arduino Uno

The Arduino Uno (Figure 2-9) is a good choice for your first Arduino. It is inex- pensive and reliable. The Uno will use the power provided by the USB cable when the cable is connected to a computer. If necessary, it can also be pow- ered by an external power supply such as a battery. When you upload code from your computer, the program is saved to the microcontroller itself. This means you can disconnect the Arduino and allow it to function as an indepen- dent device.

The Uno’s pins have female headers that enable you to connect wires without soldering. This speeds up the building of simple prototypes but is not a very good longer-term solution, because cables can fall off relatively easily.

Figure 2-9. Arduino Uno

29

Stalker Guard

In this project, you will build a Stalker Guard (Figure

3-1), a simple alarm device that measures the

distances of objects behind you and vibrates when

something comes too close (see Figure 3-2). You will

also learn a program you can easily modify for other

projects that works by monitoring data sent by a

sensor and reacting when specific conditions are filled.

Over the course of this project, you will learn the basics of Arduino program- ming, distance measurement with ultrasonic sensors, and motor control. The Stalker Guard can be easily customized into new variations by changing the values of the ultrasonic sensor, replacing the sensor with another one, or replacing the motor with, say, a speaker. With little effort, you can develop the circuit further—for example, by turning it into a height meter.

In thIs chApter

What You’ll Learn Tools and Parts Solderless Breadboard Jumper Wire Ping Ultrasonic Sensor Vibration Motor Combining Components to Make the Stalker Guard Making the Motor Vibrate Providing Power from a Battery What’s Next? Making an Enclosure

Tools and Parts

30 Chapter 3

Before starting the project, you’ll need to install the Arduino development environment and make sure you can run the “Hello World” program from Chap- ter 2. The project is organized in steps, so you can always return to the previous step if you find that something isn’t functioning correctly. Remember that you can download the complete code examples for each stage at http://BotBook .com/ or http://examples.oreilly.com/0636920010371, which allows you to test their functions before reading the individual descriptions of each program.

Figure 3-2. The Stalker Guard in action

What You’ll Learn In this chapter, you’ll learn how to:

  • Measure distance using the PING))) ultrasonic sensor
  • Use a motor
  • Apply the principles of Arduino programming
  • Power Arduino from a battery

Tools and Parts You’ll need the following tools and parts for this project (Figure 3-3).

Manufacturer part numbers are shown for:

  • Maker SHED (US: http://makershed.com): SHED
  • Element14 (International and US; formerly Farnell and Newark, http://element- .com): EL
  • SparkFun (US: http://sparkfun.com): SFE

Solderless Breadboard

32 Chapter 3

Note the power terminals at the left end of the breadboard in Figure 3-4. These are useful, but you won’t find them in every breadboard. If your breadboard does not have power terminals, you can push power leads into any of the holes in the ap- propriate horizontal row to provide power to all the other leads along that row. We won’t use power terminals in this project.

Figure 3-4. The holes in the prototyping breadboard are connected to each other by vertical rows; bus strips for power are connected horizontally

Figure 3-5 shows the breadboard with its bottom cover removed (don’t do this to your breadboard, as it tends to damage it) so you can see more clearly how the rows are connected to each other.

Figure 3-5. View of the bottom of the prototyping breadboard; metal plates conduct current from hole to hole

So how would you connect the Arduino Nano’s D5 (digital pin 5) pin to the second wire of a motor? Insert the Arduino into the middle of the prototyp- ing board (also known as the “gutter”), so that it is straddling the vertical rows between both sides of the Arduino legs. This prevents us from short-circuiting the opposite side legs of the Arduino. Push the Arduino into the board so that the Arduino’s D5 pin is connected to each hole of the strip on the same side of the gutter (highlighted in Figure 3-9, which appears later in this chapter). Then simply insert the motor wire in the hole next to the Arduino D5 pin. Now the motor wire and Arduino pin D5 are connected to each other. It’s always a good idea to begin a project by building circuits on a prototyping breadboard. Once you’re sure that a project functions correctly, you can then consider a more permanent place for it. Even in the next stage, you don’t need to solder things together. For example, you can leave the more expensive parts, such as the Arduino itself, on a smaller prototyping breadboard (Figure 3-6). This way, you can easily use it in other projects and then put it back in its Figure 3-6. Small prototyping breadboard original place.

Stalker Guard (^33)

Ping Ultrasonic Sensor

Jumper Wire

We’re going to use jumper wire—a thin, single-strand electrical wire—to make connections to the prototyping breadboard. You’ll need an adequate amount of visible conductive metal to connect the jumper wire deeply enough; about ¼ inch of exposed wire is sufficient.

Jumper wires (also known as hookup wire) are sold in ready-cut assortments (Figure 3-7), but you can also cut and strip them yourself from suitable wire. Generally, 22AWG solid-core wire is best. Using a different-colored wire for each distinct purpose can be useful. For example, use a red wire for power, and black for ground (0V, GND). Wires hooked to data pins often use other colors, such as blue or green. This method makes the circuit easier to comprehend.

Ping Ultrasonic Sensor

An ultrasonic sensor functions on the same principles as radar: it transmits a high-frequency signal and, based on the echo, determines the proximity of a specific object. The frequency is outside the human audible range, so you won’t hear a thing. Ultrasonic sensors can measure the distance of an object accurately at a minimum of 2 centimeters and a maximum of 3 meters from the device.

This type of sensor functions well when you need to know not just whether something exists in front of an object, but also at what proximity. Lights don’t affect ultrasonic sensors, so the sensors can function in complete darkness. On the other hand, there is a chance the sensor won’t detect reflective surfac- es or objects located at steep angles, because the sound wave won’t bounce back from them. Also, very small or soft objects might reflect back such minuscule amounts of the sound that the sensor will not detect them.

The Parallax Ping))) Ultrasonic Sensor is shown in Figure 3-8.

Figure 3-8. The PING))) ultrasonic sensor

Figure 3-7. Jumper wires

MetrIc UnIts

Because this book started life as a Finnish book, and because Ar- duino is an international phenom- enon, we stuck with metric (also known as Système International, or SI) measurements throughout. For easy conversions, you can type any measurement into a Google search, along with the desired out- put unit, such as “23 cm in inches,” and the conversion calculation will appear in the results. In fact, you can get fancy, such as “29. microseconds per centimeter in mph,” for which Google returns “768 389768 mph” (which is in fact roughly the speed of sound at 20 degrees C). For a wider variety of calculations, check out Wolfram Alpha (http:// www.wolframalpha.com/), which can not only tell you “speed of sound at 20 degrees Celsius,” but will also let you tweak the results to take into account air pressure and humidity!