Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore 30 Arduino Projects for the Evil Genius

30 Arduino Projects for the Evil Genius

Published by Rotary International D2420, 2021-03-23 12:48:03

Description: Simon Monk - 30 Arduino Projects for the Evil Genius-McGraw-Hill_TAB Electronics (2010)

Search

Read the Text Version

30 Arduino™ Projects for the Evil Genius™

Evil Genius™ Series Bike, Scooter, and Chopper Projects for the Evil Genius Bionics for the Evil Genius: 25 Build-it-Yourself Projects Electronic Circuits for the Evil Genius, Second Edition: 64 Lessons with Projects Electronic Gadgets for the Evil Genius: 28 Build-it-Yourself Projects Electronic Sensors for the Evil Genius: 54 Electrifying Projects 50 Awesome Auto Projects for the Evil Genius 50 Green Projects for the Evil Genius 50 Model Rocket Projects for the Evil Genius 51 High-Tech Practical Jokes for the Evil Genius 46 Science Fair Projects for the Evil Genius Fuel Cell Projects for the Evil Genius Holography Projects for the Evil Genius Mechatronics for the Evil Genius: 25 Build-it-Yourself Projects Mind Performance Projects for the Evil Genius: 19 Brain-Bending Bio Hacks MORE Electronic Gadgets for the Evil Genius: 40 NEW Build-it-Yourself Projects 101 Spy Gadgets for the Evil Genius 101 Outer Space Projects for the Evil Genius 123 PIC® Microcontroller Experiments for the Evil Genius 123 Robotics Experiments for the Evil Genius 125 Physics Projects for the Evil Genius PC Mods for the Evil Genius: 25 Custom Builds to Turbocharge Your Computer PICAXE Microcontroller Projects for the Evil Genius Programming Video Games for the Evil Genius Recycling Projects for the Evil Genius Solar Energy Projects for the Evil Genius Telephone Projects for the Evil Genius 30 Arduino Projects for the Evil Genius 22 Radio and Receiver Projects for the Evil Genius 25 Home Automation Projects for the Evil Genius

30 Arduino™ Projects for the Evil Genius™ Simon Monk New York Chicago San Francisco Lisbon London Madrid Mexico City Milan New Delhi San Juan Seoul Singapore Sydney Toronto

Copyright © 2010 by The McGraw-Hill Companies, Inc. All rights reserved. Except as permitted under the United States Copyright Act of 1976, no part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written permission of the publisher. ISBN: 978-0-07-174134-7 MHID: 0-07-174134-8 The material in this eBook also appears in the print version of this title: ISBN: 978-0-07-174133-0, MHID: 0-07-174133-X. All trademarks are trademarks of their respective owners. Rather than put a trademark symbol after every occurrence of a trademarked name, we use names in an editorial fashion only, and to the benefit of the trademark owner, with no intention of infringement of the trademark. Where such designa- tions appear in this book, they have been printed with initial caps. McGraw-Hill eBooks are available at special quantity discounts to use as premiums and sales promotions, or for use in corporate training programs. To contact a representative please e-mail us at [email protected]. Trademarks: McGraw-Hill, the McGraw-Hill Publishing logo, Evil Genius™, and related trade dress are trademarks or registered trademarks of The McGraw-Hill companies and/or its affiliates in the United States and other countries and may not be used without written permission. All other trade- marks are the property of their respective owners. The McGraw-Hill Companies is not associated with any product or vendor mentioned in this book. Information has been obtained by McGraw-Hill from sources believed to be reliable. However, because of the possibility of human or mechanical error by our sources, McGraw-Hill, or others, McGraw-Hill does not guarantee the accuracy, adequacy, or completeness of any information and is not responsible for any errors or omissions or the results obtained from the use of such information. TERMS OF USE This is a copyrighted work and The McGraw-Hill Companies, Inc. (“McGrawHill”) and its licensors reserve all rights in and to the work. Use of this work is subject to these terms. Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one copy of the work, you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, transmit, distribute, disseminate, sell, publish or sublicense the work or any part of it without McGraw-Hill’s prior consent. You may use the work for your own noncommercial and personal use; any other use of the work is strictly prohibited. Your right to use the work may be terminated if you fail to comply with these terms. THE WORK IS PROVIDED “AS IS.” McGRAW-HILL AND ITS LICENSORS MAKE NO GUARANTEES OR WARRANTIES AS TO THE ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK, INCLUDING ANY IN- FORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY OR FIT- NESS FOR A PARTICULAR PURPOSE. McGraw-Hill and its licensors do not warrant or guarantee that the functions contained in the work will meet your requirements or that its operation will be uninterrupted or error free. Neither McGraw-Hill nor its licensors shall be liable to you or anyone else for any inaccuracy, error or omission, regardless of cause, in the work or for any damages resulting therefrom. McGraw-Hill has no responsibility for the content of any information accessed through the work. Under no circumstances shall McGraw-Hill and/or its licensors be liable for any indirect, incidental, special, punitive, consequential or similar damages that result from the use of or inability to use the work, even if any of them has been advised of the possibility of such damages. This limitation of liability shall apply to any claim or cause whatsoever whether such claim or cause arises in contract, tort or otherwise.





To my late father, Hugh Monk, from whom I inherited a love for electronics. He would have had so much fun with all this.

About the Author Simon Monk has a bachelor’s degree in cybernetics and computer science and a doctorate in software engineering. He has been an active electronics hobbyist since his school days, and is an occasional author in hobby electronics magazines.

Contents Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi 1 Quickstart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Powering Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Installing the Software. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Configuring Your Arduino Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Downloading the Project Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Project 1 Flashing LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 Breadboard. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 2 A Tour of Arduino . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 Microcontrollers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 What’s on an Arduino Board? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 The Arduino Family. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 The C Language. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 3 LED Projects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 Project 2 Morse Code S.O.S. Flasher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 Project 3 Morse Code Translator. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 Project 4 High-Brightness Morse Code Translator . . . . . . . . . . . . . . . . . . . . . . . . 35 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 4 More LED Projects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 Digital Inputs and Outputs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 Project 5 Model Traffic Signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 Project 6 Strobe Light . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 Project 7 S.A.D. Light . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 Project 8 High-Powered Strobe Light . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 Random Number Generation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 Project 9 LED Dice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 5 Sensor Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 Project 10 Keypad Security Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 Rotary Encoders. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 Project 11 Model Traffic Signal Using a Rotary Encoder . . . . . . . . . . . . . . . . . . 68 Sensing Light . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 Project 12 Pulse Rate Monitor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 vii

viii 30 Arduino Projects for the Evil Genius Measuring Temperature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 Project 13 USB Temperature Logger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 6 Light Projects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 Project 14 Multicolor Light Display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 Seven-Segment LEDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 Project 15 Seven-Segment LED Double Dice. . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 Project 16 LED Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 LCD Displays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 Project 17 USB Message Board . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 7 Sound Projects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 Project 18 Oscilloscope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 Sound Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 Project 19 Tune Player. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 Project 20 Light Harp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 Project 21 VU Meter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 8 Power Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 Project 22 LCD Thermostat. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 Project 23 Computer-Controlled Fan. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 H-Bridge Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 Project 24 Hypnotizer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 Servo Motors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 Project 25 Servo-Controlled Laser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 9 Miscellaneous Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 Project 26 Lie Detector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 Project 27 Magnetic Door Lock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 Project 28 Infrared Remote . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 Project 29 Lilypad Clock. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 Project 30 Evil Genius Countdown Timer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 10 Your Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 Circuits. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 Tools. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175 Project Ideas. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 Appendix Components and Supplies . . . . . . . . . . . . . . . . . . 181 Suppliers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 Starter Kit of Components. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187

Acknowledgments I WOULD LIKE to thank my sons, Stephen and Matthew Monk, for their interest and encouragement in the writing of this book, their helpful suggestions, and their field testing of projects. Also, I could not have written this book without Linda’s patience and support. I am grateful to Chris Fitzer for the loan of his oscilloscope, and his good grace after I broke it! I also thank all the “techies” at Momote for taking an interest in the project and humoring me. Finally, I would like to thank Roger Stewart and Joya Anthony at McGraw-Hill, who have been extremely supportive and enthusiastic, and have been a pleasure to work with. ix

This page intentionally left blank

Introduction ARDUINO INTERFACE BOARDS provide the Evil At this point, the Evil Genius might be Genius with a low-cost, easy-to-use technology to wondering which top secret government create their evil projects. A whole new breed of organization they need to break into in order to projects can now be built that can be controlled acquire one. Well, disappointingly, no evil deeds at from a computer. Before long, the computer- all are required to obtain one of these devices. The controlled, servo-driven laser will be complete and Evil Genius needs to go no further than their the world will be at the mercy of the Evil Genius! favorite online auction site or search engine. Since the Arduino is an open-source hardware design, This book will show the Evil Genius how to anyone is free to take the designs and create their attach an Arduino board to their computer, to own clones of the Arduino and sell them, so the program it, and to connect all manner of market for the boards is competitive. An official electronics to it to create projects, including the Arduino costs about $30, and a clone often less computer-controlled, servo-driven laser mentioned than $20. earlier, a USB-controlled fan, a light harp, a USB temperature logger, a sound oscilloscope, and The name “Arduino” is reserved by the original many more. makers. However, clone Arduino designs often have the letters “duino” on the end of their name, Full schematic and construction details are for example, Freeduino or DFRduino. provided for every project, and most can be built without the need for soldering or special tools. The software for programming your Arduino is However, the more advanced Evil Genius may easy to use and also freely available for Windows, wish to transfer the projects from a plug-in Mac, and LINUX computers at no cost. breadboard to something more permanent, and instructions for this are also provided. Arduino So, What Is Arduino? Although Arduino is an open-source design for a microcontroller interface board, it is actually rather Well, Arduino is a small microcontroller board more than that, as it encompasses the software with a USB plug to connect to your computer and development tools that you need to program an a number of connection sockets that can be wired Arduino board, as well as the board itself. There is up to external electronics, such as motors, relays, a large community of construction, programming, light sensors, laser diodes, loudspeakers, electronics, and even art enthusiasts willing to microphones, etc. They can either be powered share their expertise and experience on the through the USB connection from the computer or Internet. from a 9V battery. They can be controlled from the computer or programmed by the computer and To begin using Arduino, first go to the Arduino then disconnected and allowed to work site (www.arduino.cc) and download the software independently. for Mac, PC, or LINUX. You can then either buy an official Arduino by clicking the Buy An xi

xii 30 Arduino Projects for the Evil Genius Arduino button or spend some time with your connection. When over the middle and bottom favorite search engine or an online auction site to pins, the board will be powered from an external find lower-cost alternatives. In the next chapter, power supply plugged into the socket below. On step-by-step instructions are provided for installing the newer Duemilanove boards, there is no such the software on all three platforms. jumper and the supply switches automatically from USB to the 9V socket. There are, in fact, several different designs of Arduino board. These are intended for different The power supply can be any voltage between types of applications. They can all be programmed 7 and 12 volts. So a small 9V battery will work from the same Arduino development software, and just fine for portable applications. Typically, while in general, programs that work on one board will you are making your project, you will probably work on all. power it from USB for convenience. When you are ready to cut the umbilical cord (disconnect the In this book we mostly use the Arduino USB lead), you will want to power the board Duemilanove, sometimes called Arduino 2009, independently. This may be with an external power which is an update of the popular board, the adaptor or simply with a 9V battery connected to a Diecimila. Duemilanove is Italian for 2009, the plug to fit the power socket. year of its release. The older Diecimila name means 10,000 in Italian, and was named that after There are two rows of connectors on the edges 10,000 boards had been manufactured. Most of the board. The row at the top of the diagram is compatible boards such as the Freeduino are based mostly digital (on/off) pins, although any marked on the Diecimila and Duemilanove designs. with “PWM” can be used as analog outputs. The bottom row of connectors has useful power Most of the projects in this book will work with connections on the left and analog inputs on a Diecimila, Duemilanove, or their clone designs, the right. apart from one project that uses the Arduino Lilypad. These connectors are arranged like this so that so-called “shield” boards can be plugged on to the When you are making a project with an main board in a piggyback fashion. It is possible to Arduino, you will need to download programs onto buy ready-made shields for many different the board using a USB lead between your purposes, including: computer and the Arduino. This is one of the most convenient things about using an Arduino. Many I Connection to Ethernet networks microcontroller boards use separate programming hardware to get programs into the microcontroller. I LCD displays and touch screens With Arduino, it’s all contained on the board itself. This also has the advantage that you can use the I XBee (wireless data communications) USB connection to pass data back and forth between an Arduino board and your computer. For I Sound instance, you could connect a temperature sensor to the Arduino and have it repeatedly tell your I Motor control computer the temperature. I GPS tracking On the older Diecimila boards, you will find a jumper switch immediately below the USB socket. I And many more With the jumper fitted over the top two pins, the board will receive its power from the USB You can also use prototyping shields to create your own shield designs. We will use these Protoshields in some of our projects. Shields usually have through connectors on their pins, which means that you can stack them on top of

Introduction xiii each other. So a design might have three layers: an Most of the projects in this book can be Arduino board on the bottom, a GPS shield on it, constructed without the need for soldering; instead and then an LCD display shield on top of that. we use a breadboard. A breadboard is a plastic block with holes in it with sprung metal The Projects connections behind. Electronic components are pushed through the holes at the front. These are The projects in this book are quite diverse. We not expensive, and a suitable breadboard is also begin with some simple examples using standard listed in the appendix. However, if you wish to LEDs and also the ultra high-brightness Luxeon make your designs more permanent, the book LEDs. shows you how to do that, too, using the prototyping board. In Chapter 5, we look at various sensor projects for logging temperature and measuring light and Sources for all the components are listed in the pressure. The USB connection to the Arduino appendix, along with some useful suppliers. The makes it possible to take the sensor readings in only things you will need in addition to these these projects and pass them back to the computer, components are an Arduino board, a computer, where they can be imported into a spreadsheet and some wire, and a piece of breadboard. The charts drawn. software for all the projects is available for download from www.arduinoevilgenius.com. We then look at projects using various types of display technology, including an alphanumeric Without Further Ado LCD message board (again using USB to get messages from your computer), as well as seven- The Evil Genius is not noted for their patience, so segment and multicolor LEDs. in the next chapter we will show you how to get started with Arduino as quickly as possible. This Chapter 7 contains four projects that use sound chapter contains all the instructions for installing as well as a simple oscilloscope. We have a simple the software and programming your Arduino project to play tunes from a loudspeaker, and build board, including downloading the software for the up to a light harp that changes the pitch and projects, so you will need to read it before you volume of the sound by waving your hand over embark on your projects. light sensors. This produces an effect rather like the famous Theremin synthesizer. The final project In Chapter 2 we take a look at some of the in this chapter uses sound input from a essential theory that will help you build the microphone. It is a VU meter that displays the projects described in this book, and go on to intensity of the sound on an LED display. design projects of your own. Most of the theory is contained in this chapter, so if you are the kind of The final chapters contain a mixture of projects. Evil Genius who prefers to just make the projects Among others, there is, as we have already and find out how they work afterwards, you may mentioned, an unfathomable binary clock using an prefer, after reading Chapter 1, to just to pick a Arduino Lilypad board that indicates the time in an project and start building. Then if you get stuck, obscure binary manner only readable by an Evil you can use the index or read some of the early Genius, a lie detector, a motor-controlled swirling chapters. hypnotizer disk, and, of course, the computer- controlled-servo-guided laser.

This page intentionally left blank

CHAPTER 1 Quickstart THIS IS A CHAPTER for the impatient Evil Genius. Arduino Duemilanove boards do not have this Your new Arduino board has arrived and you are jumper and select the power source automatically. eager to have it do something. If everything is working okay, the LED should So, without further ado... blink once every two seconds. The reason that new Arduino boards have this Blink sketch already Powering Up installed is to verify that the board works. If your board does not start to blink when connected, When you buy an Arduino Diecimila or check the position of the power jumper (if it has Duemilanove board, it is usually preinstalled with one) and try a different USB socket, possibly on a a sample Blink program that will make the little different computer, as some USB sockets are built-in LED flash. Figure 1-1 shows an Arduino- capable of supplying more power than others. compatible board with the LED lit. Also, clicking the Reset button should cause the LED to flicker momentarily. If this is the case, but The light-emitting diode (LED) marked L is the LED does not flash, then it may just be that the wired up to one of the digital input-output sockets board has not been programmed with the Flash on the board. It is connected to digital pin 13. This sketch; but do not despair, as once everything is really limits pin 13 to being used as an output, but installed, we are going to modify and install that the LED only uses a small amount of current, so script anyway as our first project. you can still connect other things to that connector. Installing the Software All you need to do to get your Arduino up and running is supply it with some power. The easiest Now we have our Arduino working, let’s get the way to do this is to plug in it into the Universal software installed so that we can alter the Blink Serial Bus (USB) port on your computer. You will program and send it down to the board. The exact need a type A-to-type B USB lead. This is the procedure depends on what operating system you same type of lead that is normally used to connect use on your computer. But the basic principle is a computer to a printer. the same for all. If you are using the older Arduino Diecimila Install the USB driver that allows the computer board, make sure that the power jumper is in the to talk to the Arduino’s USB port. It uses this for USB position (see Figure 1-1). The jumper should programming and sending messages. connect together the two top pins to allow the board to be powered from the USB. The newer 1

2 30 Arduino Projects for the Evil Genius Figure 1-1 A powered-up Arduino board with LED lit. Install the Arduino development environment, Select the Save option from the dialog, and save which is the program that you run on your the Zip file onto your desktop. The folder computer that enables you to write sketches and contained in the Zip file will become your main download them to the Arduino board. Arduino directory, so now unzip it into C:\\Program Files\\Arduino. The Arduino website (www.arduino.cc) contains the latest version of the software. You can do this in Windows XP by right- clicking the Zip file to show the menu in Figure Installation on Windows 1-3 and selecting the Extract All option. This will open the Extraction Wizard, shown in Figure 1-4. Follow the download link on the Arduino home page (www.arduino.cc) and select the download Figure 1-2 Downloading the Arduino software for Windows. This will start the download of the for Windows. Zip archive containing the Arduino software, as shown in Figure 1-2. You may well be downloading a more recent version of the software than the version 17 shown. This should not matter, but if you experience any problems, refer back to the instructions on the Arduino home page. The Arduino software does not distinguish between different versions of Windows. The download should work for all versions, from Windows XP onwards. The following instructions are for Windows XP.

Chapter 1 ■ Quickstart 3 Click Next and then modify the folder to extract Figure 1-4 Extracting the Arduino file in files to C:\\Program Files\\Arduino as shown in Windows. Figure 1-5. Then click Next again. This will create a new directory for this version of Arduino (in this case, 17) in the folder C:\\Program Files\\Arduino. This allows you to have multiple versions of Arduino installed at the same time, each in its own folder. Updates of Arduino are fairly infrequent and historically have always kept compatibility with earlier versions of the software. So unless there is a new feature of the software that you want to use, or you have been having problems, it is by no means essential to keep up with the latest version. Now that we have got the Arduino folder in the right place, we need to install the USB drivers. We let Windows do this for us by plugging in the Arduino board to trigger the Windows Found New Hardware Wizard shown in Figure 1-6. Figure 1-3 The Extract All menu option in Figure 1-5 Setting the directory for extraction. Windows. Select the option No, Not This Time, and then click Next. On the next screen (Figure 1-7), click the option to install from a specified location, enter or browse to the location C:\\Program Files\\Arduino\\arduino- 0017\\drivers\\FTDI USB Drivers, and then click Next. Note that you will have to change 0017 in the path noted if you download a different version. The installation will then complete and you are ready to start up the Arduino software itself. To do this, go to My Computer, navigate to C:\\Program

4 30 Arduino Projects for the Evil Genius Figure 1-6 Windows Found New Hardware Figure 1-7 Setting the location of the USB Wizard. drivers. Files\\Arduino\\arduino-0017, and click the Arduino The next two sections describe this same icon, as shown in Figure 1-8. The Arduino procedure for installing on Mac and LINUX software will now start. computers, so if you are a Windows user, you can skip these sections. Note that there is no shortcut created for the Arduino program, so you may wish to select the Installation on Mac OS X Arduino program icon, right-click, and create a shortcut that you can then drag to your desktop. The process for installing the Arduino software on the Mac is a lot easier than on the PC. Figure 1-8 Starting the Arduino software from Windows.

Chapter 1 ■ Quickstart 5 As before, the first step is to download the file. Figure 1-9 Installing the Arduino software on In the case of the Mac, it is a disk image file. Once Mac OS X. downloaded, it will mount the disk image and open a Finder window, as shown in Figure 1-9. The You can now skip the next subsection, which is Arduino application itself is installed in the usual for installation on LINUX. Mac way by dragging it from the disk image to your Applications folder. Installation on LINUX The disk image also contains two installer There are many different LINUX distributions, and packages for the USB drivers (see Figure 1-10). Be for the latest information, refer to the Arduino sure to choose the package for your system home page. However, for most versions of LINUX, architecture. Unless you are using a Mac built installation is straightforward. Your LINUX will before March 2006, you will need to use the Intel version rather than the PPC version. When you run the installer, you can simply click Continue until you come to the Select Disk screen, where you must select the hard disk before clicking Continue. As this software installs a kernel extension, it will prompt you to enter your password before completing the installation. You can now find and launch the Arduino software in your Applications folder. As you are going to use it frequently, you may wish to right- click its icon in the dock and set it to Keep In Dock. Figure 1-10 Installing the USB drivers on Mac OS X.

6 30 Arduino Projects for the Evil Genius probably already have the USB drivers installed, computer using the USB port or you will not be the AVR-GCC libraries, and the Java environment able to select the serial port. that the Arduino software needs. The serial port is set from the Tools menu, as So, if you are lucky, all you will need to do is shown in Figure 1-11 for the Mac and in Figure download the TGZ file for the Arduino software 1-12 for Windows—the list of ports for LINUX is from the Arduino home page (www.arduino.cc), similar to the Mac. extract it, and that is your working Arduino directory. If you use many USB or Bluetooth devices with your Mac, you are likely to have quite a few If, on the other hand, you are unlucky, then as a options in this list. Select the item in the list that LINUX user, you are probably already adept at begins with “dev/tty.usbserial.” finding support from the LINUX community for setting up your system. The pre-requisites that you On Windows, the serial port can just be set to will need to install are Java runtime 5 or later and COM3. the latest AVR-GCC libraries. From the Tools menu, we can now select the Entering into Google the phrase “Installing board that we are going to use, as shown in Figure Arduino on SUSE LINUX,” or whatever your 1-13. If you are using the newer Duemilanove, distribution of LINUX is, will, no doubt, find you choose the first option. However, if you are using lots of helpful material. the older Diecimila board, select the second option. Configuring Your Arduino Downloading the Environment Project Software Whatever type of computer you use, you should The software for all of these sketches is available now have the Arduino software installed on it. We for download. The whole download is less than a now need to make a few settings. We need to megabyte, so it makes sense to download the specify the operating system name for the port that software for all of the projects, even if you only is connected to the USB port for communicating intend to use a few. To download them, browse to with the Arduino board, and we need to specify the www.arduinoevilgenius.com and click Downloads type of Arduino board that we are using. But first, at the top of the screen. you need to connect your Arduino to your Figure 1-11 Setting the serial port on the Mac.

Figure 1-12 Setting the serial port on Windows. Figure 1-13 Setting the board. 7

8 30 Arduino Projects for the Evil Genius Click the evil_genius.zip link to download a Zip using a bigger external LED and resistor rather file of all the projects. If you are using Windows, than the tiny built-in LED. unzip the file to My Documents\\Arduino. On a Mac and LINUX, you should unzip it to Software Documents/Arduino in your home directory. First, we need to load the Blink sketch into the Once the files are installed, you will be able to Arduino software. The Blink sketch is included as access them from the File | Sketchbook menu on an example when you install the Arduino the Arduino software. environment. So we can load it using the File menu, as shown in Figure 1-14. Project 1 The majority of the text in this sketch is in the Flashing LED form of comments. Comments are not actually part of the program but explain what is going on in the Having assumed that we have successfully program to anyone reading the sketch. installed the software, we can now start on our first exciting project. Actually, it’s not that exciting, but Comments can be single-line comments that we need to start somewhere, and this will ensure start after a // and continue to the end of the line, that we have everything set up correctly to use our or they can be multiline comments that start with a Arduino board. /* and end some lines later with a */. We are going to modify the example Blink If all the comments in a sketch were to be sketch that comes with Arduino. We will increase removed, it would still work in exactly the same the frequency of the blinking and then install the way, but we use comments because they are useful modified sketch on our Arduino board. Rather than to anyone reading the sketch trying to work out blink slowly, our board will flash its LED quickly. what it does. We will then take the project a stage further by Before we start, a little word about vocabulary COMPONENTS AND EQUIPMENT is required. The Arduino community uses the word “sketch” in place of “program,” so from now on, I Description Appendix will refer to our Arduino programs as sketches. Occasionally I may refer to “code.” Code is Arduino Diecimila or 1 programmer speak for a section of a program or Duemilanove board or clone even as a generic term for what is written when creating a program. So, someone might say, “I D1 5-mm red LED 23 wrote a program to do that,” or they could say, “I wrote some code to do that.” R1 270 ⍀ 0.5W metal film resistor 6 To modify the rate at which the LED will blink, ■ In actual fact, almost any commonly available we need to change the value of the delay so that in LED and 270 ⍀ resistor will be fine. the two places in the sketch where we have: ■ No tools other than a pair of pliers or wire delay(1000); cutters are required. ■ The number in the Appendix column refers to the component listing in the appendix, which lists part numbers for various suppliers.

Chapter 1 ■ Quickstart 9 Figure 1-14 Loading the example Blink sketch. change the value in the parentheses to 200 so that will be a short pause and then the two red LEDs it appears as: on the board will start flashing away furiously as the sketch is uploaded onto the board. This should delay(200); take around 5 to 10 seconds. This is changing the delay between turning the If this does not happen, check the serial port and LED on and off from 1000 milliseconds (1 second) board type settings as described in the previous to 200 milliseconds (1/5th of a second). In Chapter sections. 3 we will explore this sketch further, but for now, we will just change the delay and download the When the completed sketch has been installed, sketch to the Arduino board. the board will automatically reset, and if everything has worked, you will see the LED for With the board connected to your computer, digital port 13 start to flash much more quickly click the Upload button on the Arduino. This is than before. shown in Figure 1-15. If everything is okay, there Figure 1-15 Uploading the sketch to the Arduino board.

10 30 Arduino Projects for the Evil Genius Hardware one direction. The little arrows next to the LED symbol indicate that it emits light. At the moment, this doesn’t really seem like real electronics because the hardware is all The resistor is just depicted as a rectangle. contained on the Arduino board. In this section, we Resistors are also often shown as a zigzag line. will add an external LED to the board. The rest of the lines on the diagram represent electrical connections between the components. LEDs cannot simply have voltage applied to These connections may be lengths of wire or them; they must have a current-limiting resistor tracks on a circuit board. In this case, they will just attached. Both parts are readily available from any be the wires of the components. electronics suppliers. The component order codes for a number of suppliers are detailed in the We can connect the components directly to the appendix. Arduino sockets between the digital pin 12 and the GND pin, but first we need to connect one lead of The Arduino board connectors are designed to the LED to one lead of the resistor. attach “shield” plug-in boards. However, for experimentation purposes, they also allow wires or It does not matter which lead of the resistor is component leads to be inserted directly into the connected to the LED; however, the LED must be sockets. connected the correct way. The LED will have one lead slightly longer than the other, and it is the Figure 1-16 shows the schematic diagram for longer lead that must be connected to digital pin attaching the external LED. 12 and the shorter lead that should be connected to the resistor. LEDs and some other components This kind of schematic diagram uses special have the convention of making the positive lead symbols to represent the electronic components. longer than the negative one. The LED appears rather like an arrow, which indicates that light-emitting diodes, in common To connect the resistor to the short lead of the with all diodes, only allow the current to flow in LED, gently spread the leads apart and twist the short lead around one of the resistor leads, as shown in Figure 1-17. Then push the LED’s long lead into the digital pin 12 and the free lead of the resistor into one of Figure 1-16 Schematic diagram for an LED Figure 1-17 An LED connected to a serial connected to the Arduino board. resistor.

Chapter 1 ■ Quickstart 11 Figure 1-18 An LED connected to the Arduino board. the two GND sockets. This is shown in Figure 1-18. Breadboard Sometimes, it helps to bend a slight kink into the end of the lead so that it fits more tightly into the Twisting together a few wires is not practical for sockets. anything much more than a single LED. A breadboard allows us to build complicated circuits We can now modify our sketch to use the without the need for soldering. In fact, it is a good external LED that we have just connected. All we idea to build all circuits on a breadboard first to get need to do is change the sketch so that it uses the design right and then commit the design to digital pin 12 instead of 13 for the LED. To do solder once everything is working. this, we change the line: A breadboard comprises a plastic block with int ledPin = 13; holes in it, with sprung metal connections behind. // LED connected to digital pin 13 Electronic components are pushed through the holes at the front. to read: Underneath the breadboard holes, there are int ledPin = 12; strips of connectors, so each of the holes in a strip // LED connected to digital pin 12 are connected together. The strips have a gap between them so that integrated circuits in dual-in- Now upload the sketch by clicking the Upload line packaging can be inserted without leads on the To IO Board button in the same way as you did same row being shorted together. when modifying the flash rate.

12 30 Arduino Projects for the Evil Genius Figure 1-19 Project 1 on breadboard. We can build this project on a breadboard rather breadboard, as it does not go the whole width of than with twisted wires. Figure 1-19 shows a the board. photograph of this. Figure 1-20 makes it a little easier to see how the components are positioned In addition to a breadboard, you will need some and connected together. solid-core wire and some wire strippers or pliers to cut and remove the insulation from the ends of the You will notice that at the edges of the wire. It is a good idea to have at least three breadboard (top and bottom), there are two long different colors: red for all wires connected to the horizontal strips. The connections on the back of positive side of the supply, black for negative, and these long strips run at right angles to the normal some other color (orange or yellow) for other strips of connections and are used to provide connections. This makes it much easier to power to the components on the breadboard. understand the layout of the circuit. You can also Normally, there is one for ground (0V or GND) buy prepared short lengths of solid-core wire in a and one for the positive supply voltage (usually variety of colors. Note that it is not advisable to 5V). There are little linking wires between the left use multicore wire, as it will tend to bunch up and right halves of the GND strip, as on this when you try to push it into the breadboard holes. Figure 1-20 Project 1 breadboard layout.

Chapter 1 ■ Quickstart 13 Possible sources of these materials are included design board and leave it permanently attached to in the appendix. the breadboard. We can straighten out the wires of our LED and Summary resistor and plug them into a breadboard. It is best to use a reasonable-sized breadboard and attach the We have created our first project, albeit a very Arduino board to it. You probably do not want to simple one. In the next chapter we will get a bit attach the board permanently, so I use a small more background on the Arduino before moving lump of adhesive putty. However, you may find it on to some more interesting projects. easier to dedicate one Arduino board to be your

This page intentionally left blank

CHAPTER 2 A Tour of Arduino IN THIS CHAPTER, we look at the hardware of the processor, a kilobyte of random access memory Arduino board and also of the microcontroller at (RAM) for holding data, a few kilobytes of its heart. In fact, the board basically just provides erasable programmable read-only memory support to the microcontroller, extending its pins to (EPROM) or Flash memory for holding our the connectors so that you can connect hardware to programs, and it has input and output pins. These them and providing a USB link for downloading input/output pins are what link the microcontroller sketches, etc. to the rest of our electronics. We also learn a few things about the C language Inputs can read both digital (is the switch on or used to program the Arduino, something we will off?) and analog (what is the voltage at a pin?). build on in later chapters as we start on some This enables us to connect many different types of practical project work. sensors for light, temperature, sound, etc. Although this chapter gets quite theoretical at Outputs can also be analog or digital. So, you times, it will help you understand how your can set a pin to be on or off (0V or 5V) and this projects work. However, if you would prefer just to can turn LEDs on and off directly, or you can use get on with your projects, you may wish to skim the output to control higher-power devices such as this chapter. motors. They can also provide an analog output voltage. That is, you can set the output of a pin to Microcontrollers some particular voltage, allowing you to control the speed of a motor or the brightness of a light, The heart of our Arduino is a microcontroller. for example, rather than simply turning it on or off. Practically everything else on the board is concerned with providing the board with power What’s on an Arduino Board? and allowing it to communicate with your desktop computer. Figure 2-1 shows our Arduino board—or in this case an Arduino clone. Let us have a quick tour of So what exactly do we get when we buy one of the various components on the board. these little computers to use in our projects? The answer is that we really do get a little computer on a chip. It has everything and more than the first home computers had. It has a 15

16 30 Arduino Projects for the Evil Genius Figure 2-1 The components of an Arduino board. Power Supply something between 4.5V and 5.5V. So 5V became the standard voltage for all digital electronics. Directly below the USB connector is the 5V voltage regulator. This regulates whatever voltage These days, the type of logic gates used in chips (between 7 and 12 volts) is supplied from the has changed and they are far more tolerant of power socket into a constant 5V. different voltages. 5V (along with 3V, 6V, 9V, and 12V) is a bit of The 5V voltage regulator chip is actually quite a standard voltage in electronics. 3, 6, and 9V are big for a surface-mount component. This is so that standard because the voltage that you get from a it can dissipate the heat required to regulate the single alkaline cell is 1.5V, and these are all voltage at a reasonably high current, which is convenient multiples of 1.5V, which is what you useful when driving our external electronics. get when you make a “battery” of two, three, six, or eight cells. Power Connections So if that is the case, you might be wondering Next, let us look at the connectors at the bottom of why 5V? You cannot make that using 1.5V cells. Figure 2-1. You can read the connection names Well, the answer lies in the fact that in the early next to the connectors. days of computing, a range of chips became available, each of which contained logic gates. The first is Reset. This does the same thing as These chips used something called TTL pressing the Reset button on the Arduino. Rather (Transistor-Transistor Logic), which was a bit like rebooting a PC, it resets the microcontroller, fussy about its voltage requirements and required beginning its program from the start. The Reset connector allows you to reset the microcontroller

Chapter 2 ■ A Tour of Arduino 17 by momentarily setting this pin high (connecting it ■ The height of the water (or if you prefer, the to +5V). pressure generated by the pump). This is like voltage in electronics. The rest of the pins in this section provide different voltages (3.3, 5, GND, and 9), as labeled. ■ The resistance to flow offered by the GND, or ground, just means zero volts. It is the constriction in the pipework reference voltage to which all other voltages on the board are relative. The more powerful the pump, the higher the water can be pumped and the greater the current At this point, it would be useful to remind the that will flow through the system. On the other reader about the difference between voltage and hand, the greater the resistance offered by the current. There is no perfect analogy for the pipework, the lower the current. behavior of electrons in a wire, but the author finds an analogy with water in pipes to be helpful, In the right half of Figure 2-2, we can see the particularly in dealing with voltage, current, and electronic equivalent of our pipework. In this case, resistance. The relationship between these three current is actually a measure of how many things is called Ohm’s Law. electrons flow past a point per second. And yes, resistance is the resistance to the flow of electrons. Figure 2-2 summarizes the relationship between voltage, current, and resistance. The left Instead of height or pressure, we have a side of the diagram shows a circuit of pipes, concept of voltage. The bottom of the diagram is where the top of the diagram is higher up (in at 0V, or ground, and we have shown the top of elevation) than the bottom of the diagram. So the diagram as being at 5V. So the current that water will naturally flow from the top of the flows (I) will be the voltage difference (5) divided diagram to the bottom. Two factors determine by the resistance R. how much water passes any point in the circuit in a given time (the current): Ohm’s Law is usually written as V ϭ IR. Normally, we know what V is and are trying to Figure 2-2 Ohm’s Law.

18 30 Arduino Projects for the Evil Genius calculate R or I, so we can do a bit of rearranging Digital 0 to 13. These can be used as either inputs to have the more convenient I ϭ V/R and R ϭ V/I. or outputs. When using them as outputs, they behave rather like the supply voltages we talked It is very important to do a few calculations about earlier, except that these are all 5V and can using Ohm’s Law when connecting things to your be turned on or off from our sketch. So, if we turn Arduino, or you may damage it if you ask it to them on from our sketch, they will be at 5V and if supply too much current. Generally, though, the we turn them off, they will be at 0V. As with the Arduino boards are remarkably tolerant of supply connectors, we have to be careful not to accidental abuse. exceed their maximum current capabilities. So, going back to our Arduino power pins, we These connections can supply 40 mA at 5V. can see that the Arduino board will supply us with That is more than enough to light a standard LED, useful voltages of 3.3V, 5V, and 9V. We can use but not enough to drive an electric motor directly. any of those supplies to cause a current to flow, as long as we are careful not to make it a short circuit As an example, let us look at how we would (no resistance to flow), which would cause a connect an LED to one of these digital potentially large current to flow that could cause connections. In fact, let’s go back to Project 1 in damage. In other words, we have to make sure that Chapter 1. anything we connect to the supply has enough resistance to prevent too much current from As a reminder, Figure 2-3 shows the schematic flowing. As well as supplying a particular voltage, diagram for driving the LED that we first used in each of those supply connections will have a the previous chapter. If we were to not use a maximum current that can be allowed to flow. resistor with our LED but simply connect the LED Those currents are 50 mA (thousandths of an amp) between pin 12 and GND, then when we turned for the 3.3V supply, and although it is not stated in digital output 12 on (5V), we might burn out the the Arduino specification, probably around 300 LED, destroying it. mA for the 5V. This is because LEDs have a very low resistance Analog Inputs and will cause a very high current to flow unless they are protected from themselves by using a The next section of connections is labeled Analog resistor to limit the flow of current. In 0 to 5. These six pins can be used to measure the voltage connected to them so that the value can be used in a sketch. Note that they measure a voltage and not a current. Only a tiny current will ever flow into them and down to ground because they have a very large internal resistance. Although labeled as analog inputs, these connections can also be used as digital inputs or outputs, but by default, they are analog inputs. Digital Connections Figure 2-3 LED and series resistor. We now switch to the top connector and start on the right side (Figure 2-1). We have pins labeled

Chapter 2 ■ A Tour of Arduino 19 An LED needs about 10 mA to shine reasonably On the left side of the top connector in Figure brightly. The Arduino can supply 50 mA, so there 2-1, there is another GND connection and a is no problem there; we just need to choose a connection called AREF. AREF can be used to sensible value of resistor. scale the readings for analog inputs. This is rarely used and can safely be ignored. LEDs have the interesting property that no matter how much current flows through them, Microcontroller there will always be about 2V between their pins. Getting back to our tour of the Arduino board, the We can use this fact and Ohm’s Law to work out microcontroller chip itself is the black rectangular the right value of resistor to use. device with 28 pins. This is fitted into a DIL (dual in-line) socket so that it can be easily We know that (at least when it’s on) the output replaced. The 28-pin microcontroller chip used on pin will be supplying 5V. Now, we have just said Arduino Duemilanove is the ATmega328. Figure that 2V will be “dropped” by our LED, leaving 2-4 is a block diagram showing the main features 3V (5 – 2) across our current-limiting resistor. We of this device. want the current flowing around the circuit to be 10 mA, so we can see that the value for the The heart, or perhaps more appropriately the resistor should be brain, of the device is the CPU (central processing unit). It controls everything that goes on within the R ϭ V/I device. It fetches program instructions stored in the Flash memory and executes them. This might R ϭ 3V/10 mA involve fetching data from working memory (RAM), changing it, and then putting it back. Or, it R ϭ 3V/0.01 A may mean changing one of the digital outputs from 0 to 5 volts. R ϭ 300 ⍀ Figure 2-4 ATmega328 block diagram. Resistors come in standard values, and the closest value to 300 ⍀ is 270 ⍀. This means that instead of 10 mA, the current will actually be I ϭ V/R I ϭ 3/270 I ϭ 11.111 mA These things are not critical, and the LED would probably be equally happy with anything between 5 and 30 mA, so 270 ⍀ will work just fine. We can also set one of these digital connections to be an input, in which case, it works rather like an analog input, except that it will just tell us if the voltage at a pin is above a certain threshold (roughly 2.5V) or not. Some of the digital connections (3, 5, 6, 9, 10, and 11) have the letters PWM next to them. These can be used to provide a variable output voltage rather than a simple 5V or nothing.

20 30 Arduino Projects for the Evil Genius The electrically erasable programmable read- The Arduino Family only memory (EEPROM) memory is a little like the Flash memory in that it is nonvolatile. That is, It’s useful to have a little background on the you can turn the device off and on and it will not Arduino boards. We will be using the Duemilanove have forgotten what is in the EEPROM. Whereas for most of our projects; however, we will also the Flash memory is intended for storing program dabble with the interesting Lilypad Arduino. instructions (from sketches), the EEPROM is used to store data that you do not want to lose in the The Lilypad (Figure 2-5), is a tiny, thin Arduino event of a reset or power failure. board that can be stitched into clothing for applications that have become known as wearable The older Diecimila uses the ATmega168, computing. It does not have a USB connection, which functions in an identical way to the and you must use a separate adaptor to program it. ATmega328 except that it has half the amount of This is an exceptionally beautiful design. Inspired every sort of memory. It has 16KB of Flash by its clocklike appearance, we will use this in memory, 1KB of RAM, and 512 bytes of Project 29 (Unfathomable Binary Clock). EEPROM. At the other end of the spectrum is the Arduino Other Components Mega. This board has a faster processor with more memory and a greater number of input/output pins. Above the microcontroller there is a small, silver, rectangular component. This is a quartz crystal Cleverly, the Arduino Mega can still use shields oscillator. It “ticks” 16 million times a second, and built for the smaller Arduino Diecimila and on each of those ticks, the microcontroller can Duemilanove boards, which sit at the front of the perform one operation—an addition, subtraction, etc. board, allowing access to the double row of connectors for the Mega’s additional connections To the right of the crystal, is the Reset switch. at the rear. Only the most demanding of projects Clicking this sends a logic pulse to the Reset pin really need an Arduino Mega. of the microcontroller, causing the microcontroller to start its program afresh and clear its memory. Figure 2-5 Arduino Lilypad. Note that any program stored on the device will be retained because this is kept in nonvolatile Flash memory—that is, memory that remembers even when the device is not powered. To the right of the Reset button is the serial programming connector. It offers another means of programming the Arduino without using the USB port. Since we do have a USB connection and software that makes it convenient to use, we will not avail ourselves of this feature. In the top left of the board next to the USB socket is the USB interface chip. This converts the signal levels used by the USB standard to levels that can be used directly by the Arduino board.

Chapter 2 ■ A Tour of Arduino 21 The C Language digitalWrite(ledPin, LOW); // set the LED off Many languages are used to program microcontrollers, from hard-core Assembly delay(1000); language to graphical programming languages like // wait for a second Flowcode. Arduino sits somewhere in between these two extremes and uses the C programming } language. It does, however, wrap up the C language, hiding away some of the complexity. It is standard practice to include such text at the This makes it easy to get started. top of any program file. You can also include comments that describe a tricky bit of code, or The C language is, in computing terms, an old anything that requires some explanation. and venerable language. It is well suited to programming the microcontroller because it was The Arduino development environment uses invented at a time when compared to today’s something called a compiler that converts the monsters, the typical computer was quite poorly script into the machine code that will run on the endowed. microcontroller. C is an easy language to learn, yet compiles into So, moving onto the first real line of code, we efficient machine code that only takes a small have: amount of room in our limited Arduino memory. int ledPin = 13; An Example This line of code gives a name to the digital We are now going to examine the sketch for output pin that we are going to connect to the Project 1 in a bit more detail. The listing for this LED. If you look carefully at your Arduino board, sketch to flash an LED on and off is shown here. you will see the connector for pin 13 between We have ignored all the lines that begin with // or GND and pin 12 on the Arduino’s top connector. blocks of lines that start with /* and end with */ The Arduino board has a small green LED already because these are comment lines that have no soldered onto the board and connected to pin 13. effect on the program and are just there for We are going to change the voltage of this pin to information. between 0V and 5V to make the LED flash. int ledPin = 13; We are going to use a name for the pin so that // LED connected to digital pin 13 it’s easy to change it and use a different one. You can see that we refer to “ledPin” later in the void setup() sketch. You may prefer to use pin 12 and the { external LED that you used with your breadboard in Chapter 1. But for now, we will assume that you pinMode(ledPin, OUTPUT); are using the built-in LED attached to pin 13. } You will notice that we did not just write: void loop() { led pin = 13 digitalWrite(ledPin, HIGH); That is because compilers are kind of fussy and // set the LED on precise about how we write our programs. Any name we use in a program cannot use spaces, so it delay(1000); is a convention to use what is called “bumpy case.” // wait for a second

22 30 Arduino Projects for the Evil Genius So, we start each word (apart from the first) with The next lines of the sketch are an uppercase letter and remove the space; that gives us: void setup() // run once, when the sketch starts ledPin = 13 { The word ledPin is what is termed a variable. pinMode(ledPin, OUTPUT); When you want to use a variable for the first time // sets the digital pin as output in a sketch, you have to tell the compiler what type of variable it is. It may be an int, as is the case } here, or a float, or a number of other types that we will describe later in this chapter. This is what is called a function, and in this case, the function is called setup. Every sketch An int is an integer—that is, a whole number— must contain a setup function, and the lines of which is just what we need when referring to a code inside the function surrounded by curly particular pin on the Arduino. There is, after all, no brackets will be carried out in the order that they pin 12.5, so it would not be appropriate to use a are written. In this case, that is just the line starting floating point number (float). with pinMode. The syntax for a variable declaration is A good starting point for any new project is to copy this example project and then alter it to your type variableName = value; needs. So first we have the type (int), then a space, We will not worry too much about functions at then a variable name in bumpy case (ledPin), then this stage, other than to say that the setup function an equal sign, then a value, and finally a semicolon will be run every time the Arduino is reset, to indicate the end of the line: including when the power is first turned on. It will also be run every time a new sketch is int ledPin = 13; downloaded. As I mentioned, the compiler is fussy, so if you In this case, the only line of code in setup is forget the semicolon, you will receive an error message when you compile the sketch. Try pinMode(ledPin, OUTPUT); removing the semicolon and clicking the Play // sets the digital pin as output button. You should see a message like this: The first thing to mention is that we have a error: expected unqualified-id before different type of comment on the end of this line. numeric constant That is, the single-line comment. This begins with a // and ends at the end of the line. It’s not exactly “you forgot a semicolon,” and it is not uncommon for error messages to be The line can be thought of as a command to the similarly misleading. Arduino to use the ledPin as a digital output. If we had a switch connected to ledPin, we could set it as an input using: pinMode(ledPin, INPUT); However, we would call the variable something more appropriate, like switchPin.

Chapter 2 ■ A Tour of Arduino 23 The words INPUT and OUTPUT are what are of digitalWrite, it is said to take two parameters: called constants. They will actually be defined the Arduino pin to write to and the value to write. within C to be a number. INPUT may be defined as 0 and OUPUT as 1, but you never need to In our example, we pass the parameters of actually see what number is used, as you always ledPin and HIGH to turn the LED on and then refer to them as INPUT or OUTPUT. Later in this ledPin and LOW to turn it off again. chapter, we will see two more constants, HIGH and LOW, that are used when setting the output of Variables and Data Types a digital pin to +5V or 0V, respectively. We have already met the variable ledPin and The next section of code is another function that declared it to be of type int. Most of the variables every Arduino sketch must have; it is called loop: that you use in your sketches are also likely to be ints. An int holds an integer number between void loop() –32,768 and +32,767. This uses just two bytes of { data for each number stored from the 1024 available bytes of storage on an Arduino. If that digitalWrite(ledPin, HIGH); range is not enough, you can use a long, which // sets the LED on uses four bytes for each number and will give you a range of numbers from –2,147,483,648 to delay(1000); +2,147,483,647. // waits for a second Most of the time, an int represents a good digitalWrite(ledPin, LOW); compromise between precision and use of memory. // sets the LED off If you are new to programming, I would use ints delay(1000); for almost everything and gradually expand your // waits for a second repertoire of data types as your experience grows. } Other data types available to you are summarized in Table 2-1. The function loop will be run continuously until the Arduino is powered down. That is, as soon as it One thing to consider is that if data types finishes executing the commands it contains, it will exceed their range, strange things happen. So if begin again. Remember that an Arduino board is you have a byte variable with 255 in it and you capable of running 16 million commands per add 1 to it, you get 0. More alarmingly, if you have second, so things inside the loop will happen an int variable with 32,767 and you add 1 to it, you frequently if you let them. will end up with –32,768. In this case, what we want the Arduino to keep Until you are completely happy with these doing continuously is to turn the LED on, wait a different data types, I would recommend sticking second, turn the LED off, and then wait another to int, as it works for practically everything. second. When it has finished doing this, it will begin again, turning the LED on. In this way it will Arithmetic go round the loop forever. It is fairly uncommon to need to do much in the By now, the command syntax for digitalWrite way of arithmetic in a sketch. Occasionally, you and delay will be becoming more familiar. will need to do a bit of scaling of, say, an analog Although we can think of them as commands that are sent to the Arduino board, they are actually functions just like setup and loop, but in this case they have what are called parameters. In the case

24 30 Arduino Projects for the Evil Genius TABLE 2-1 Data Types in C Type Memory (bytes) Range Notes boolean 1 true or false (0 or 1) char 1 –128 to +128 Used to represent an ASCII character code (e.g., A is byte 1 0 to 255 represented as 65). Its negative int 2 –32,768 to +32,767 numbers are not normally used. unsigned int 2 0 to 65,536 Can be used for extra precision long 4 –2,147,483,648 to where negative numbers are not 2,147,483,647 needed. Use with caution, as unsigned long 4 0 to 4,294,967,295 arithmetic with ints may cause float 4 –3.4028235E+38 to unexpected results. + 3.4028235E+38 Needed only for representing very double 4 as float large numbers. See unsigned int. Normally, this would be eight bytes and higher precision than float with a greater range. However, on Arduino, it is the same as float. input to turn it into a temperature, or more might want to use Strings: when writing messages typically, add 1 to a counter variable. to an LCD display or sending back serial text data over the USB connection. When you are performing some calculation, you need to be able to assign the result of the Strings are created using the following syntax: calculation to a variable. char* message = \"Hello World\"; The following lines of code contain two assignments. The first gives the variable y the The char* word indicates that the variable value 50 and the second gives the variable x the message is a pointer to a character. For now, we do value of y + 100. not need to worry too much about how this works. We will meet this later in the book when we look y = 50; at interfacing with textual LCD displays. x = y + 100; Conditional Statements Strings Conditional statements are a means of making When programmers talk of Strings, they are decisions in a sketch. For instance, your sketch referring to a string of characters such as the may turn the LED on if the value of a temperature much-used message “Hello World.” In the world of variable falls below a certain threshold. Arduino, there are a couple of situations where you

Chapter 2 ■ A Tour of Arduino 25 The code for this is shown here: Often, when using an if statement, you want to do one thing if the condition is true and a different if (temperature < 15) thing if it is false. You can do this by using the else { keyword, as shown in the following example. Note the use of nested parentheses to make it clear what digitalWrite(ledPort, HIGH); is being or’d with what. } if ((temperature < 15) || (temperature The line or lines of code inside the curly braces > 20)) will only be executed if the condition after the if keyword is true. { digitalWrite(ledPort, HIGH); The condition has to be contained in parentheses, and is what programmers call a } logical expression. A logical expression is like a else mathematical sentence that must always return one { of two possible values: true or false. digitalWrite(ledPort, LOW); The following expression will return true if the } value in the temperature variable is less than 15: Summary (temperature < 15) In this chapter, we have explored the hardware As well as <, you have: >, <=, and >=. provided by the Arduino and refreshed our To see if two numbers are equal, you can use == knowledge of a little elementary electronics. and to test if they are not equal, you can use !=. So the following expression would return true if We have also started our exploration of the C the temperature variable had a value that was programming language. Don’t worry if you found anything except 15: some of this hard to follow. There is a lot to take in if you are not familiar with electronics, and while (temperature != 15) the author’s goal is to explain how everything works, you are completely at liberty to simply start You can also make complex conditions using on the projects first and come back to the theory what are called logical operators. The principal when you are ready. operators being && (and) and || (or). In the next chapter we will get to grips with So an example that turned the LED on if the programming our Arduino board and embark on temperature was less than 15 or greater than 20 some more serious projects. might look like this: if ((temperature < 15) || (temperature > 20)) { digitalWrite(ledPort, HIGH); }

This page intentionally left blank

CHAPTER 3 LED Projects IN THIS CHAPTER, we are going to start building COMPONENTS AND EQUIPMENT some LED-based projects. We will keep the hardware fairly simple so that we can concentrate Description Appendix on the programming of the Arduino. Arduino Diecimila or Programming microcontrollers can be a tricky business requiring an intimate knowledge of the Duemilanove board or clone 1 inner workings of the device: fuses, registers, etc. This is, in part, because modern microcontrollers D1 5-mm red LED 23 are almost infinitely configurable. Arduino standardizes its hardware configuration, which, in R1 270 ⍀ 0.5W metal film resistor 6 return for a small loss of flexibility, makes the devices a great deal easier to program. ■ Almost any commonly available LED and 270 ⍀ resistor will be fine. Project 2 ■ No tools other than a pair of pliers or wire Morse Code S.O.S. Flasher cutters are required. Morse code used to be a vital method of Hardware communication in the 19th and 20th centuries. Its coding of letters as a series of long and short dots The hardware is exactly the same as Project 1. So, meant that it could be sent over telegraph wires, you can either just plug the resistor and LED over a radio link, and using signaling lights. The directly into the Arduino connectors or use a letters S.O.S. (Save Our Souls) is still recognized breadboard (see Chapter 1). as an international signal of distress. Software In this project, we will make our LED flash the sequence S.O.S. over and over again. Rather than start typing this project in from scratch, we will use Project 1 as a starting point. For this project, you will need just the same So if you have not already done so, please components as for Project 1. complete Project 1. If you have not already done so, download the project code from www.arduinoevilgenius.com; then you can also just load the completed sketch for Project 1 from your Arduino Sketchbook and download it to the board (see Chapter 1). However, 27

28 30 Arduino Projects for the Evil Genius it will help you understand Arduino better if you delay(200); modify the sketch from Project 1 as suggested digitalWrite(ledPin, HIGH); next. // third dot Modify the loop function of Project 1 so that it delay(200); now appears as shown here. Note that copy and digitalWrite(ledPin, LOW); paste is highly recommended in this kind of delay(1000); situation: // wait 1 second before we start void loop() again { } digitalWrite(ledPin, HIGH); // S (...) first dot This would all work, and feel free to try it; however, we are not going to leave it there. We are delay(200); going to alter our sketch to improve it, and at the digitalWrite(ledPin, LOW); same time make it a lot shorter. delay(200); digitalWrite(ledPin, HIGH); We can reduce the size of the sketch by creating our own function to replace the four lines of code // second dot involved in any flash with one line. delay(200); digitalWrite(ledPin, LOW); After the loop function’s final curly brace, add delay(200); the following code: digitalWrite(ledPin, HIGH); void flash(int duration) // third dot { delay(200); digitalWrite(ledPin, LOW); digitalWrite(ledPin, HIGH); delay(500); delay(duration); digitalWrite(ledPin, HIGH); digitalWrite(ledPin, LOW); delay(duration); // O (—-) first dash } delay(500); digitalWrite(ledPin, LOW); Now modify the loop function so that it looks delay(500); like this: digitalWrite(ledPin, HIGH); void loop() // second dash { delay(500); digitalWrite(ledPin, LOW); flash(200); flash(200); flash(200); delay(500); // S digitalWrite(ledPin, HIGH); delay(300); // third dash // otherwise the flashes run delay(500); together digitalWrite(ledPin, LOW); delay(500); flash(500); flash(500); flash(500); digitalWrite(ledPin, HIGH); // O // S (...) first dot flash(200); flash(200); flash(200); delay(200); // S digitalWrite(ledPin, LOW); delay(200); delay(1000); digitalWrite(ledPin, HIGH); // wait 1 second before we start again // second dot delay(200); } digitalWrite(ledPin, LOW);

Chapter 3 ■ LED Projects 29 LISTING PROJECT 2 int ledPin = 13; void setup() // run once, when the sketch starts { // sets the digital pin as output pinMode(ledPin, OUTPUT); } void loop() // S { // otherwise the flashes run together // O flash(200); flash(200); flash(200); // S delay(300); // wait 1 second before we start again flash(500); flash(500); flash(500); flash(200); flash(200); flash(200); delay(1000); } void flash(int duration) { digitalWrite(ledPin, HIGH); delay(duration); digitalWrite(ledPin, LOW); delay(duration); } The whole final listing is shown in Listing Loops Project 2. Loops allow us to repeat a group of commands a This makes the sketch a lot smaller and a lot certain number of times or until some condition is easier to read. met. Putting It All Together In Project 2, we only want to flash three dots for an S, so it is no great hardship to repeat the flash That concludes Project 2. We will now cover some command three times. However, it would be far more background on programming the Arduino less convenient if we needed to flash the LED 100 before we go on to look at Project 3, where we or 1000 times. In that case we can use the for will use our same hardware to write a Morse code language command in C. translator, where we can type sentences on our computer and have them flashed as Morse code. In for (int i = 0; i < 100; i ++) Project 4, we will improve the brightness of our { flashing by replacing our red LED with a high- power Luxeon-type LED. flash(200); } But first, we need a little more theory in order to understand Projects 3 and 4. The for loop is a bit like a function that takes three arguments, although here, those arguments are separated by semicolons rather than the usual

30 30 Arduino Projects for the Evil Genius commas. This is just a quirk of the C language. contrast, an array contains a list of values, and you The compiler will soon tell you when you get it can access any one of those values by its position wrong. in the list. The first thing in the parentheses after “for” is a C, in common with the majority of programming variable declaration. This specifies a variable to be languages, begins its index positions at 0 rather used as a counter variable and gives it an initial than 1. This means that the first element is actually value—in this case, 0. element zero. The second part is a condition that must be true To illustrate the use of arrays, we could change for us to stay in the loop. In this case, we will stay our Morse code example to use an array of flash in the loop as long as “i” is less than 100, but as durations. We can then use a for loop to step soon as “i” is 100 or more, we will stop doing the through each of the items in the array. things inside the loop. First let’s create an array of ints containing the The final part is what to do every time you have durations: done all the things in the loop. In this case, that is increment “i” by 1 so that it can, after 100 trips int durations[] = {200, 200, 200, 500, around the loop, cease to be less than 100 and 500, 500, 200, 200, 200} cause the loop to exit. You indicate that a variable contains an array by Another way of looping in C is to use the while placing [] after the variable name. If you are command. The same example shown previously setting the contents of the array at the same time could be accomplished using a while command, you are defining it, as in the previous example, you as shown here: do not need to specify the size of the array. If you are not setting its initial contents, then you need to int i = 0; specify the size of the array inside the square while (i < 100) brackets. For example: { int durations[10]; flash(200); i ++; Now we can modify our loop method to use the } array: The expression in parentheses after while must void loop() be true to stay in the loop. When it is no longer // run over and over again true, the sketch will continue running the commands after the final curly brace. { for (int i = 0; i < 9; i++) The curly braces are used to bracket together a { group of commands. In programming parlance, flash(durations[i]); they are known as a block. } delay(1000); Arrays // wait 1 second before we start // again Arrays are a way of containing a list of values. The variables we have met so far have only } contained a single value, usually an int. By

Chapter 3 ■ LED Projects 31 An obvious advantage of this approach is that it computer to the Arduino board through the USB is easy to change the message by simply altering cable. the durations array. In Project 3, we will take the use of arrays a stage further to make a more For this project, you will need just the same general-purpose Morse code flasher. components as for Project 1 and 2. In fact, the hardware is exactly the same; we are just going to Project 3 modify the sketch of Project 1. Morse Code Translator COMPONENTS AND EQUIPMENT In this project, we are going to use the same Description Appendix A hardware as for Projects 1 and 2, but we are going to write a new sketch that will let us type in a Arduino Diecimila or 1 sentence on our computer and have our Arduino Duemilanove board or clone 23 board convert that into the appropriate Morse code D1 5-mm Red LED 6 dots and dashes. R1 270 Ω 0.5W metal film resistor Figure 3-1 shows the Morse code translator in Hardware action. The contents of the message box are being flashed as dots and dashes on the LED. Please refer back to Project 1 for the hardware construction for this project. To do this, we will make use of what we have learned about arrays and strings, and also learn You can either just plug the resistor and LED something about sending messages from our directly into the Arduino connectors, or use the Figure 3-1 Morse code translator.

32 30 Arduino Projects for the Evil Genius breadboard (see Chapter 1). You can even just TABLE 3-1 Morse Code Letters change the ledPin variable in the sketch to be pin 13 so that you use the built-in LED and do not A .- N -. 0 ——- need any external components at all. B -… O —- 1 .—— C -.-. P .--. 2 ..--- Software D -.. Q --.- 3 …-- E. R .-. 4 ….- The letters in Morse code are shown in Table 3-1. F ..-. S… 5 ….. G --. T- 6 -…. Some of the rules of Morse code are that a dash H …. U ..- 7 --… is three times as long as a dot, the time between I .. V …- 8 ---.. each dash or dot is equal to the duration of a dot, J .--- W .-- 9 ----. the space between two letters is the same length as K -.- X -..- a dash, and the space between two words is the L .-.. Y -.-- same duration as seven dots. M -- Z --.. For the sake of this project, we will not worry The sketch for this is shown in Listing Project 3. about punctuation, although it would be an An explanation of how it all works follows. interesting exercise for you to try adding this to the sketch. For a full list of all the Morse characters, see http://en.wikipedia.org/wiki/Morse_code. LISTING PROJECT 3 int ledPin = 12; char* letters[] = { // A-I \".-\", \"-...\", \"-.-.\", \"-..\", \".\", \"..-.\", \"--.\", \"....\", \"..\", // J-R \".---\", \"-.-\", \".-..\", \"--\", \"-.\", \"---\", \".--.\", \"--.-\", \".-.\", // S-Z \"...\", \"-\", \"..-\", \"...-\", \".--\", \"-..-\", \"-.--\", \"--..\" }; char* numbers[] = {\"-----\", \".----\", \"..---\", \"...--\", \"....-\", \".....\", \"-....\", \"--...\", \"---..\", \"----.\"}; int dotDelay = 200; void setup() { pinMode(ledPin, OUTPUT); Serial.begin(9600); } void loop() // is there anything to be read from USB? { char ch; if (Serial.available())

Chapter 3 ■ LED Projects 33 LISTING PROJECT 3 (continued) { ch = Serial.read(); // read a single letter if (ch >= 'a' && ch <= 'z') { flashSequence(letters[ch - 'a']); } else if (ch >= 'A' && ch <= 'Z') { flashSequence(letters[ch - 'A']); } else if (ch >= '0' && ch <= '9') { flashSequence(numbers[ch - '0']); } else if (ch == ' ') { delay(dotDelay * 4); // gap between words } } } void flashSequence(char* sequence) // gap between letters { int i = 0; while (sequence[i] != NULL) { flashDotOrDash(sequence[i]); i++; } delay(dotDelay * 3); } void flashDotOrDash(char dotOrDash) // gap between flashes { digitalWrite(ledPin, HIGH); if (dotOrDash == '.') { delay(dotDelay); } else // must be a - { delay(dotDelay * 3); } digitalWrite(ledPin, LOW); delay(dotDelay); }


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook