Docsity

Arduino Boot, Manuais, Projetos, Pesquisas de Engenharia Elétrica

Pré-visualização parcial do texto

Baixe Arduino Boot e outras Manuais, Projetos, Pesquisas em PDF para Engenharia Elétrica, somente na Docsity!

D ownload from Wow! eBook <www.wowebook.com>

Make: Arduino Bots and Gadgets

by Kimmo and Tero Karvinen

Copyright © 2011 O’Reilly Media, Inc. All rights reserved. Printed in Canada.

Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.

O’Reilly Media books may be purchased for educational, business, or sales promotional use. Online editions are also avail- able for most titles (my.safaribooksonline.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or [email protected].

Development Editors: Brian Jepson and Brian Sawyer
Production Editor: Holly Bauer
Technical Editor: Joe Saavedra
Copyeditor: Rachel Monaghan
Proofreader: Jennifer Knight
Translator: Marko Tandefelt
Indexer: Ellen Troutman Zaig
Cover Designer: Mark Paglietti
Interior Designer: Ron Bilodeau
Illustrator/Photographer: Kimmo Karvinen
Cover Photographer: Kimmo Karvinen
Software Architect: Tero Karvinen
Print History:

March 2011: First Edition.

The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trademark claim, the designations have been printed in caps or initial caps.

Important Message to Our Readers: The technologies discussed in this publication, the limitations on these technologies that technology and content owners seek to impose, and the laws actually limiting the use of these technologies are con- stantly changing. Thus, some of the projects described in this publication may not work, may cause unintended harm to systems on which they are used, or may not be consistent with current laws or applicable user agreements.

Your safety is your own responsibility, including proper use of equipment and safety gear, and determining whether you have adequate skill and experience. Electricity and other resources used for these projects are dangerous unless used prop- erly and with adequate precautions, including safety gear. These projects are not intended for use by children. While every precaution has been taken in the preparation of this book,

O’Reilly Media, Inc. and the authors assume no responsibility for errors or omissions. Use of the instructions and suggestions in Make: Arduino: Bots and Gadgets is at your own risk. O’Reilly Media, Inc. and the authors disclaim all responsibility for any resulting damage, injury, or expense. It is your responsibility to make sure that your activities comply with applicable laws, including copyright.

This book uses Otabind™, a durable and flexible lay-flat binding.

ISBN: 978-1-449-38971-
[TI]

iii

  • 1.. Introduction.. Preface.. vii
    • Building Philosophy.
    • Reusing Parts
    • Buying Components
    • Useful Tools
    • Electronic Circuit Theory Review.
    • System.. 2.. Arduino:.The.Brains.of.an.Embedded.
    • Why Arduino?
    • Starting with Arduino
    • Hello World with Arduino
    • Structure of “Hello World”
    • Arduino Uno
    • Arduino Nano
  • 3.. Stalker.Guard.
    • 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
  • 4.. Insect.Robot iv Contents
    • What You’ll Learn.
    • Tools and Parts
    • Servo Motors.
    • Constructing the Frame
    • Programming the Walk
    • Avoiding Obstacles Using Ultrasound
    • What’s Next?
  • 5.. Interactive.Painting.
    • What You’ll Learn.
    • Tools and Parts
    • Resistors
    • LEDs.
    • Detecting Motion Using Ultrasonic Sensors
    • Moving Images
    • Installing Python
    • Hello World in Python
    • Communicating over the Serial Port
    • Displaying a Picture
    • Scaling an Image to Full Screen.
    • Changing Images with Button Control
    • Gesture-Controlled Painting in Full Screen
    • Animating the Sliding Image
    • Connecting Arduino with Processing
    • Processing Code for the Painting
    • The Finished Painting
    • Creating an Enclosure
    • Building a Frame
  • 6.. Boxing.Clock.
    • What You’ll Learn.
    • Tools and Parts
    • Android Software Installation
    • Creating a Boxing Clock in Android
    • What’s Next?
  • 7.. Remote.for.a.Smart.Home
    • What You’ll Learn.
    • Tools and Parts
    • The Relay: A Controllable Switch
    • Hacking the Remote Control Contents v
    • Controlling the Arduino from the Computer
    • Creating a Graphical User Interface
    • The Finished Remote Control Interface
    • Creating an Enclosure
  • 8.. Soccer.Robot..
    • What You Will Learn
    • Tools and Parts
    • Continuous Rotation Servos
    • Modding a Standard Servo into a Continuous Rotation Servo
    • Connecting the Arduino to the Bluetooth Mate
    • Testing the Bluetooth Connection
    • Building a Frame for the Robot
    • Programming the Movements.
    • Controlling Movement from a Computer
    • Steering with an Android Cell Phone
    • The Accelerometer.
    • An Easier Approach to Bluetooth
    • Controlling the Robot with Cell Phone Motion
    • Completing the Soccer Robot
    • What’s Next?
  • A.. tBlue.Library.for.Android
    • Index

D ownload from Wow! eBook <www.wowebook.com>

Embedded Systems Are Everywhere

viii^ Preface

Most embedded systems are reactive systems, operating in a continuous in- teraction with their environment and responding within a tempo defined by that environment. This makes them a logical choice for tasks that must react immediately, such as a car braking system. In some cases, it can be hard to tell whether a particular system should be classified as an embedded system or a computer. For example, cell phones are starting to include more and more features typically associated with comput- ers, but they still have much in common with embedded systems.

Why.Should.You.Study.Embedded.Systems?

The world is already full of embedded systems. With reasonable effort, you can learn how to build one yourself. Turn inventions and ideas into inexpen- sive prototypes, automate your home by creating a fish-feeding device or con- trolling lighting from your computer, or build a remote-controlled surveillance camera for your yard that you can access via a computer located anywhere in the world. Artists can create interactive installations or integrate sensors into a game that you can control without touching a computer. Possible implemen- tations are endless. During the 2000s, the DIY meme gathered more and more popularity, as is evident with the growth of MAKE Magazine and websites such as http://www .instructables.com. The Bay Area Maker Faire, an annual DIY festival, went from 22,000 attendees in its first year (2006) to more than double that amount (45,000) in its second year. And each year, Maker Faire attendance keeps growing. Learning embedded systems is becoming even more appealing due to the growing interest in robotics. In a 2006 Scientific American article,* Microsoft founder Bill Gates predicted that robotics would be the next revolution within homes, comparing the current state of the robotics industry to the computing industry in the 1970s. Gates anticipates that robots will soon become a natu- ral part of a home, taking care of simple tasks such as vacuum cleaning, lawn mowing, surveillance, and food service. In addition, because robots can be con- trolled remotely from anywhere, we’ll be able to use them for telepresence— viewing, hearing, and touching people and things without even having to be present.

Intelligent.Air.Conditioning

The common use of embedded systems is not just the stuff of science fic- tion or future technology. It’s already here and pervasive in the home. Con- sider air conditioning. A smart air conditioning system adjusts itself based on measurements. How does it know when the air is thick or stale? Air conditioners measure the temperature, humidity, and sometimes also carbon dioxide levels using sensors. A microcontroller (a small, dedicated computer) follows these measurements, and if the air is damp, for example, it activates a servo that opens an air valve, letting fresh air flow in. This type of

*http://www.scientificamerican.com/article.cfm?id=a-robot-in-every-home

Preface (^) ix

Learn Embedded Systems in a Week

intelligent air control system has many benefits. It saves energy, because the air conditioning system doesn’t need to be used at full power all the time, and it makes working in such a space more comfortable, because there’s neither a constant draft nor stagnant air. The heating and air conditioning system at your own school or job likely functions on the same principles.

Sensors,.Microcontrollers,.and.Outputs

Embedded systems include sensors, microcontrollers, and outputs. Sensors measure conditions within a physical environment, such as distance, accelera- tion, light, pressure, reflection of a surface, and motion.

The microcontroller is the brain of an embedded system. It’s a tiny computer, with a processor and memory, which means you can run your own programs on it. The Arduino microcontroller used in this book is programmed using a full-size computer via a USB cable, with sensors and outputs connected to the microcontroller pins.

Outputs affect the physical environment. Examples of outputs you’ll learn to control in this book include LEDs and servo motors. Output devices are some- times known as actuators.

Learn Embedded Systems in a Week

This book will teach you the basics of embedded systems in just one week, during which time you’ll build your first gadget. After that, you can move on to more complex projects and prototypes based on your own ideas. Within seven days, you will already be deep within the world of embedded systems.

This goal can sound immense—at least, we felt it was impossible before we became familiar with contemporary development environments. But today, many projects that once felt impossible now seem straightforward.

The purpose of this book is to teach you how to build embedded systems, and we’ve left out any topic that does not support the practice of building proto- types. For example, we don’t cover history, movement of electrons, or complex electrical formulas. We believe it makes more sense to study these concepts after you are surrounded by your own homemade devices.

Classroom.Use

We tested this book with actual students during a one-week, intensive course led by Tero Karvinen. By the end of the week, all the students in the course were able to build their own prototypes.

The students built many types of projects: a burglar alarm that can be dis- armed with a wireless RFID keychain; a flower-measurement device that saves the height, humidity, and temperature of a flower to memory; a sonar device that draws an image of its distance on a computer screen; an automatic trig- gering device for a camera; a web-based control device for a camera; and a temperature meter observable via an Internet interface. For more examples of projects, visit http://BotBook.com/.

Preface (^) xi

Contents of This Book

The projects are partitioned so you can test each part one step at a time. This way, it is easier to understand the function of each step and the relationships between different parts. This also helps ensure that once you have built a de- vice, you can easily troubleshoot any problems; if something doesn’t work, you can always go back to an earlier functioning phase and restart from there.

There are examples of enclosures for several projects in this book. They are useful as teaching techniques for mechanical construction and give you ideas for how to make a demonstrable prototype relatively inexpensively. You are not obligated to follow the instructions literally. You might have different parts or a better vision for the look of your device.

Contents of This Book

This book includes two introductory chapters followed by six chapters with projects. As you move through the book, you’ll go from learning the basics of Arduino to completing projects with moving parts, wireless communication, and more:

Chapter 1, Introduction This chapter explains prototyping, including an overview of the philoso- phy behind it, techniques, and tools.

Chapter 2, Arduino: The Brains of an Embedded System

This chapter familiarizes you with Arduino, the open source electronics prototyping platform used in every project in this book (except the Box- ing Clock in Chapter 6).

Chapter 3, Stalker Guard In this chapter, you’ll learn how to use distance-finding sensors to detect when someone is trying to sneak up on you.

Chapter 4, Insect Robot This chapter uses distance-finding sensors, servos, and spare parts to make an obstacle-avoiding robot.

Chapter 5, Interactive Painting This chapter combines Arduino, your computer, and distance-finding sen- sors to create an interactive slideshow you can control with your hands. You’ll also learn about two languages for programming on the computer: Processing and Python.

Chapter 6, Boxing Clock This chapter teaches you how to build a graphically rich timer clock on an Android phone. It will also serve as a primer for Chapter 8.

Chapter 7, Remote for a Smart Home In this chapter, you’ll hack some remote-controlled power outlets so you can turn things on or off using a sketch running on Arduino—or even from the convenience of your desktop computer.

Using Code Examples

xii^ Preface

Chapter 8, Soccer Robot This chapter combines a lot of what you’ve learned so far: Arduino, robot- ics, and cell phone (Android) programming. You’ll learn how to create a remote-controlled, soccer-playing robot. You’ll control it from your cell phone’s built-in accelerometer; simply tilt the phone to tell the robot to move or kick a small ball! Appendix, tBlue Library for Android The appendix presents tBlue, a lightweight library that makes it easy to communicate over Bluetooth between an Android phone and Arduino.

Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, envi- ronment variables, statements, and keywords. Constant width bold Shows commands or other text that should be typed literally by the user. Constant width italic Shows text that should be replaced with user-supplied values or by values determined by context.

Using Code Examples This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of ex- amples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission. We appreciate attribution. An attribution usually includes the title, authors, publisher, copyright holder, and ISBN. For example: “Make: Arduino Bots and Gadgets, by Kimmo Karvinen and Tero Karvinen (O’Reilly). Copyright 2011 O’Reilly Media, 978-1-449-38971-0.” If you feel that your use of code examples falls outside fair use or the permission given above, feel free to contact us at [email protected].

Acknowledgments

xiv^ Preface

Acknowledgments Thanks to:

  • Juho Jouhtimäki
  • Marjatta Karvinen
  • Nina Korhonen
  • Mikko Toivonen
  • Marianna Väre
  • Medialab, Aalto University School of Art and Design
  • O’Reilly Media
  • Readme.fi
  • Tiko, Haaga-Helia University of Applied Sciences

1

Introduction

This chapter will get you started building and
designing prototypes for embedded systems. You will
learn basic principles that you’ll follow in Chapters
3 and 4 as you build the Stalker Guard and Robot
Insect. Prototypes in this book are just the beginning.
Once you know the techniques, you’ll be able to build
prototypes for your own inventions.

Building Philosophy

When you break a programming problem down into smaller pieces, be sure to test and validate each piece as you go. If you don’t do this, you could find yourself wildly off track by the time you’ve gotten through a few pieces.

Prototype

This book provides techniques for building prototypes, or test versions of a device. A prototype such as the one shown in Figure 1-1 provides a proof of concept—a concrete realization of a device’s intended functions.

Try to finish a functional prototype as quickly as possible. Once you’ve docu- mented a working prototype, you can build in improvements in later versions.

You can make a working end result by stripping out unnecessary functions and taking shortcuts. If it makes testing quicker, use rubber bands and duct tape when you have to. Don’t try to optimize your code in the first version.

It’s much easier to build an impressive version once the first prototype is fin- ished. Usually, you’ll find that many challenging problems you face in the pro- totype don’t even need to be solved for the final version. In the same way, building a prototype can reveal new opportunities for development.

Figure 1-1. Jari Suominen testing a proto- type made of Legos

In thIs chApter

Building Philosophy Reusing Parts Buying Components Useful Tools Electronic Circuit Theory Review

Introduction (^3)

Building Philosophy

Test.in.Steps

“I wrote the code for a singing and dancing robot that can walk up stairs. The code is 30,000 lines long. I just tried compiling it, but it doesn’t work. Do you have any advice?”

Conduct testing as early as possible. If, for example, you build a walking robot, the first thing to test is whether you can make the servo motor move. The next test can make the servo move back and forth.

After you have tested the functionality of a specific version of code, save it separately from the version you are working on.

Revert.to.the.Last.Known.Good.Version

When you have developed your code into a confusing and nonfunctional state, the solution is easy. Go back to the last working version.

More specifically, go back to a working stage when the situation was already becoming confusing. This method removes the problem areas and lets you start over with a functional clean slate, helping you isolate what went wrong.

Read.the.Friendly.Manual

RTFM is an old Internet acronym. (Actually, the F is not always friendly, so we usually stick with just RTM.) The point of the expression is that most answers are out there, written in a manual. When you’re surrounded by parts (see Figure 1-5), you're going to need answers.

Friends and students sometimes wonder how we know so much. How do we know the Arduino operating voltage or the way to install SSL encryption to the Apache web server?

Figure 1-5. Mikko Toivonen, surrounded by robots and microcontrollers

The answer is easy. You can find instructions for almost anything if you know where to look.

Instructions don’t always come with devices and parts, but you can often find them on manufacturer’s web pages (such as http://www.parallax.com) or by searching in Google. Good search terms include device names (e.g., “ping ul- trasonic sensor”) or a sequence of numbers on a circuit board (e.g., “H48C”).

Reusing Parts

4 Chapter 1

You could also combine a search sequence with a technology—for example, “H48C arduino.” Some web pages are devoted specifically to Arduino—for example, http://arduino.cc and our site, http://BotBook.com.

Document

Most things appear easy once you know them. The details of a project seem obvious on the day you complete them (“of course I remember when I pro- grammed the 16-servo walker”). But a week after building, coding details begin to disappear from your memory. After a year or so, it can be hard for someone who builds many projects to remember anything about a specific one. For this reason, it is worthwhile to document all projects. Typing notes avoids the potential problem of illegible handwriting, and shooting stages with a digital camera provides an accurate visual snapshot of each stage. You might also consider publishing your results on the Web. Some projects that would otherwise be collecting dust in your drawer might actually be use- ful to others. You might even find your own instructions (long since forgotten) when looking to solve a new problem with similar logic. Two sites where you can publish projects are Make: Projects (http://www.makeprojects.com) and In- structables (http://www.instructables.com).

Reusing Parts Prototype mechanics (see Figure 1-6) need all kinds of parts, such as frames, limbs, and joints. Finding appropriate materials can seem daunting. Custom- izing more complicated parts using homebrew methods isn’t always easy, and even basic materials—such as lightweight and sturdy metal plates—can be significantly expensive at hardware stores. As a starting point, we recommend using recycled parts. Old devices are filled with usable materials, so remove all salvageable parts before you throw them away. One additional perk that comes with using recycled parts is a unique aesthetic. Old parts often have interesting shapes, curves, and worn areas (Figure 1-7).

Figure 1-7. An assortment of parts that can be reused

Figure 1-6. Jenna Sutela and David Szauder demoing functions of a wearable prototype

Not every device is safe to salvage: for example, a CRT (Cathode Ray Tube) TV retains a hazardous voltage for a long time after you unplug it from the wall.