Visit us at www.syngress.com Syngress is committed to publishing high-quality books for IT Professionals and delivering those books in media and formats that fit the demands of our customers. We are also committed to extending the utility of the book you purchase via additional materials available from our Web site.
SOLUTIONS WEB SITE
To register your book, visit www.syngress.com/solutions. Once registered, you can access our
[email protected] Web pages. There you may find an assortment of valueadded features such as free e-books related to the topic of this book, URLs of related Web sites, FAQs from the book, corrections, and any updates from the author(s).
ULTIMATE CDs
Our Ultimate CD product line offers our readers budget-conscious compilations of some of our best-selling backlist titles in Adobe PDF form. These CDs are the perfect way to extend your reference library on key topics pertaining to your area of expertise, including Cisco Engineering, Microsoft Windows System Administration, CyberCrime Investigation, Open Source Security, and Firewall Configuration, to name a few.
DOWNLOADABLE E-BOOKS
For readers who can’t wait for hard copy, we offer most of our titles in downloadable Adobe PDF form. These e-books are often available weeks before hard copies, and are priced affordably.
SYNGRESS OUTLET
Our outlet store at syngress.com features overstocked, out-of-print, or slightly hurt books at significant savings.
SITE LICENSING
Syngress has a well-established program for site licensing our e-books onto servers in corporations, educational institutions, and large organizations. Contact us at
[email protected] for more information.
CUSTOM PUBLISHING
Many organizations welcome the ability to combine parts of multiple Syngress books, as well as their own content, into a single volume for their own internal use. Contact us at
[email protected] for more information.
This page intentionally left blank
Owen Bishop
Elsevier, Inc., the author(s), and any person or firm involved in the writing, editing, or production (collectively “Makers”) of this book (“the Work”) do not guarantee or warrant the results to be obtained from the Work. There is no guarantee of any kind, expressed or implied, regarding the Work or its contents. The Work is sold AS IS and WITHOUT WARRANTY.You may have other legal rights, which vary from state to state. In no event will Makers be liable to you for damages, including any loss of profits, lost savings, or other incidental or consequential damages arising out from the Work or its contents. Because some states do not allow the exclusion or limitation of liability for consequential or incidental damages, the above limitation may not apply to you. You should always use reasonable care, including backup and other appropriate precautions, when working with computers, networks, data, and files. Syngress Media®, Syngress®, “Career Advancement Through Skill Enhancement®,” “Ask the Author UPDATE®,” and “Hack Proofing®,” are registered trademarks of Elsevier, Inc. “Syngress: The Definition of a Serious Security Library”™, “Mission Critical™,” and “The Only Way to Stop a Hacker is to Think Like One™” are trademarks of Elsevier, Inc. Brands and product names mentioned in this book are trademarks or service marks of their respective companies. KEY 001 002 003 004 005 006 007 008 009 010
SERIAL NUMBER HJIRTCV764 PO9873D5FG 829KM8NJH2 BAL923457U CVPLQ6WQ23 VBP965T5T5 HJJJ863WD3E 2987GVTWMK 629MP5SDJT IMWQ295T6T
PUBLISHED BY Syngress Publishing, Inc. Elsevier, Inc. 30 Corporate Drive Burlington, MA 01803 Programming Lego Mindstorms NXT
Copyright © 2008 by Elsevier, Inc. All rights reserved. Printed in the United States of America. Except as permitted under the 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, with the exception that the program listings may be entered, stored, and executed in a computer system, but they may not be reproduced for publication. Printed in the United States of America 1 2 3 4 5 6 7 8 9 0 ISBN 13: 978-1-59749-278-2 Page Layout and Art: SPi Publishing Services Copy Editor: Judy Eby For information on rights, translations, and bulk sales, contact Matt Pedersen, Commercial Sales Director and Rights, at Syngress Publishing; email
[email protected].
Author Owen Bishop is the author of over 80 books, mostly on electronics and computing, including the best-selling Commodore 64 Games Book. His most recent publication is the Robot Builder’s Cookbook (Elsevier/Newnes, 2007). Owen’s talent for introducing the world’s of electronics and computing has long been proven fact with his textbooks, professional introductions and hobby guides being chosen by thousands of students, lecturers and enthusiasts. With Owen’s clear program descriptions you can get your robot up and running quickly, even if you are a beginner, and have fun whilst doing so. Educated in England, at Bristol University and the University of Oxford, Owen has lived and worked in several countries as a science education adviser for UNESCO and the British Council. He is at present a freelance technical writer, living in Perth, Western Australia.
This page intentionally left blank
Contents Chapter 1 Robots and Programs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 What is a Program? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 Designing a Robot. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Specify the Robot’s Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 Intelligent or Smart?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Chapter 2 About NXT-G Programs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Creating a Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 First Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 Out of Memory?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 Coming for a Spin?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 Tying it Together . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 Chapter 3 Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 Sources of Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 A Variable Has a Name, a Type, and a Value. . . . . . . . . . . . . . . . . . . . . . . . 27 Arithmetic Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 Logical Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 Flag Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 Chapter 4 Loops. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 Outside Events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 Time Limit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 Counting the Loops. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 Dance Some More. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 Use Loops to Make Actions Repeat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 Another Way to Use the Loop Counter. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 Logical Conclusions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 Use a Loop (or a Wait Block) to Wait for an Event to Occur . . . . . . . . . . . . . 38 Nested Loops. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 The Wait Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 vii
viii
Contents
Chapter 5 Switches and Other Topics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 The Switch Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Switch Blocks Direct Execution Along Alternative Pathways . . . . . . . . . . . . . . . . 44 Simultaneous Processing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 Diagnostic Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 Chapter 6 Using the Light Sensor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 Light Sensor Directed Downward. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 Lined in. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 Line Follower . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 Edge Follower. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 Light Sensor Directed Upward . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 Housefly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 Light Sensor Directed Forward. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 Lightfinder1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 LightFinder2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 Almost an Interrupt. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 LightFinder3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 LightFinder4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 Chapter 7 Using the Touch Sensor and the NXT Buttons . . . . . . . . . . . . . . 71 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 Waiting for Contact. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 Bumper. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 Waiting for Input. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 Scanning the NXT Buttons. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 Entering Numbers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 Chapter 8 Using the Ultrasonic Sensor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 Avoidance Routine for Alpha Rex. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 Ultrasonic Search. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 Chapter 9 Sounds Received and Emitted. . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 Start and Stop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 Start, Stop, and Turn. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 One Clap or Two?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 Playing a Tune (with a Little Dance). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
www.syngress.com
Contents
Choreography. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 Song Snippets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 Dance Snippets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 Chapter 10 The Magnetic Compass Sensor. . . . . . . . . . . . . . . . . . . . . . . . . . 95 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 Heading in the Right Direction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 Polygon. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 Circle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 Chapter 11 More Mathematics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 Floating Point Arithmetic. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 Calculating Cosines. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 Calculating Sines. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 Square Root . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 Factorials. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 Combinations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 X modulo Y. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 Modulo Counting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 Chapter 12 Navigation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 Distance Traveled. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 Magnetic Compass. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 Edge Follower 1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 No-go Response to a Line. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 Steering Alpha Rex. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 Marching Orders. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 Rex On Line. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 Rex On Edge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 Pathfinder. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 Cosine Rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 Chapter 13 Games Robots Play. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 Maze Runner—Version 1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 Maze Runner—Version 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 Maze Runner—Version 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154 Maze Learner. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 Scissors, Paper, Stone . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
www.syngress.com
ix
Contents
Signalling by Semaphore. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 Magic. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 The Program. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 Chapter 14 Databases for Robots. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 Lookup Table for Weekdays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 Writable Lookup Table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176 Another Way of Using a Lookup Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 Reading Data from a File Access Block. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
www.syngress.com
Chapter 1
Robots and Programs
Chapter 1 • Robots and Programs
Introduction Without a program, a robot is just an assembly of electronic and mechanical components. This book shows you how to give it a program. The LEGO® Mindstorms® kit contains the parts and directions for building the following four different types of robots: ■
A vehicle called a Tribot
■
A machine called a RoboArm
■
An animal called Spike the scorpion
■
A humanoid Alpha Rex
Of these, Alpha Rex is closest to most people’s idea of what a robot is. But Tribot and RoboArm are typical of robots commonly seen in industrial situations. It is a lot of fun building them, testing them with the few simple programs that come with the kit, and then getting them to do new and interesting things by writing your own programs. As well as these four, there are dozens of other robots waiting to be built and programmed. For example, the monkey and the mouse in the book by Dave Astolfo, Mario Ferrari, and Guilio Ferrari, “Building Robots with LEGO Mindstorms NXT” (Syngress, 2007). There are also dozens of robots that you can invent and program using the same kit of parts! In this book, the programs and program snippets are written using the Mindstorms NXT-G language that comes with the kit. NXT-G is described as a visual language. Instead of being written in text, it is created as a diagram (see Figure 1.1). NXT-G is described in more detail in Chapter 2.
www.syngress.com
Robots and Programs • Chapter 1
Figure 1.1 This is the computer screen during a NXT-G programming session. On the left-hand side is the palette from which you drag the icons that represent the programming blocks. The icons are assembled into a program on the grid of the working area. Below the working area is the configuration pane, which displays the detailed settings of the currently selected block.
www.syngress.com
Chapter 1 • Robots and Programs
Most of the NXT-G programs in this book are based on the Tribot (Figure 1.2) and the RoboArm, because these are the most versatile robots. Also, there are several programs specially written for Alpha Rex. Figure 1.2 This version of the Tribot is equipped with bumper sensor, to detect objects that it runs into, and also has a light sensor pointing forward with which it can seek out light sources in the room.
What is a Program? A program is essentially a list of instructions that tells the robot what to do and when and how to do it. A NXT-G program does not look anything like a list (see Figure 1.3). The program is built up from icons, each icon representing one or more instructions. The icons are arranged in order on a framework. The design of each icon tells us what the icon does (see Figure 1.4). When the program is run, the icons are taken in the order in which they are on the framework, or sequence beam, and executed in that order. This is the same as having a written list of instructions and following them in the order in which they are listed.
www.syngress.com
Robots and Programs • Chapter 1
Figure 1.3 A NXT-G program consists of a number of programming blocks, which are executed in the order in which they are placed on the sequence beam. Sometimes the blocks are linked by data wires, which transmit data from block to block. This program switches on the drive motors for 1 second. Four seconds later, it starts to switch motor A on and off every 2 seconds.
Figure 1.4 The gear wheels on the upper icon indicate that it is a move block. The lower icon is obviously a sound sensor block.
www.syngress.com
Chapter 1 • Robots and Programs
Now comes the problem. Humans can understand the icons and sequences of icons, but robots can’t. Robots only understand an arrangement of electrical charges in the electronic circuits in their memories. The program in icon form has be turned into electronic form. This is where a compiler program comes in. The compiler program is run by clicking on one of the buttons at the bottom right-hand corner of the screen. When the program has been compiled, it is read and executed by the microcontrollers in the NXT brick.
Microcontrollers The microcontrollers are the two vital electronic devices inside the NXT. They read and then execute the program instructions stored in the NXT’s memory.
Designing a Robot When you have finished building and programming the robots that come with the kit, you will almost certainly want to design and build robots of your own. This is when things get really exciting. When you are designing your own robots, the first question that must be asked is “What do I want it to do?”. Do I want it to pick up objects? If so, it will need one or more arms with grippers (see Figure 1.5). Do I want it to move around? If so, it needs to have wheels, or legs, if its environment includes steps or rough surfaces. Does it need an ultrasonic sensor for navigation? Does it need an audio sensor for receiving spoken commands?
www.syngress.com
Robots and Programs • Chapter 1
Figure 1.5 Equipping a robot. This robot is going to be mobile, so it needs drive wheels with motors. The rear wheel is a caster. The robot has an ultrasonic sensor for navigation, and a bumper for detecting obstacles. It has an arm with a gripper for handling objects and a microphone for detecting spoken commands. Like all robots, it must have at least one microcontroller or microprocessor. To make the whole system operational it must have a program.
By considering these types of questions you build up a specification for the robot that is related to what it has to do and where it has to operate.
Specify the Robot’s Environment Animals (including humans) adapt to the environment in which they live. It is different with robots. Sometimes it makes things simpler if we adapt the environment to the robot instead of adapting the robot to the environment. One example is if the robot is designed to find its way to a source of light, it’s a good idea to make sure there is only one source of light in the room. Later you can try to get it to distinguish between one bright source of light and other sources of light. Give it a simple environment to start with, and when the program is working properly you can try improving it to work in a more complex environment. Start with something easy and progress to something more difficult. In the case of a robot that handles objects, it may be a good idea for the objects to be all the same size and shape. Later you can try programming the robot to handle objects of different sizes and shapes. If the robot has to move from one place to another, paint a line on the floor for it to follow. It is much easier for a robot to follow a line, rather than to navigate between the walls and furniture. There are many ways of adapting the environment to simplify the task of the robot. www.syngress.com
Chapter 1 • Robots and Programs
Intelligent or Smart? Most of the programs in this book give the robot a pattern of smart behavior. A robot that heads toward a bright source of light while avoiding obstacles may be smart, but can hardly be called intelligent. It is interesting to compare the NXT brick with the brain of a very simple animal such as the flatworm. This animal can solve a simple T-maze (see Figure 1.6) by trial and error. The experimenter put the worm at the base of the T. In the early trials the worm found its way to the food by chance, sometimes going left and sometimes going right. After the trial was repeated several times, it gradually learned that going left would take it to the food. From then on it always went to the left. This is one type of intelligent behavior. The animal learned to find where its food was placed. Robots can do the same thing. Later in this book we describe how to program a Mindstorms robot to solve a maze with three or more junctions. At first it operates by trial and error, but when it finds a successful pattern of behavior it remembers it and repeats it as long as it continues to be successful. Figure 1.6 The maze for training the flatworm is made of glass and filled with water. It has only one junction. If food is always placed in the left arm of the maze, the flatworm soon learns to turn left at the junction.
www.syngress.com
Robots and Programs • Chapter 1
Summary If it is possible to program a robot to solve a maze better than a flatworm, it should be easy to get it to mimic the behavior of other lowly animals. Why not program the Tribot to behave like a bat, using an ultrasonic sensor to steer its way across an obstacle-littered floor in total darkness. One of the programs later in this book shows how a Tribot can be programmed to behave like a housefly, ignoring slow changes in the light intensity, but accelerating rapidly away when the shadow of a swatting hand suddenly A bit further up the intelligence scale, we see how RoboArm can be programmed to perform a magical illusion in the same way that a human magician does. But is this intelligent behavior or just smart? This is for the reader to decide.
www.syngress.com
This page intentionally left blank
Chapter 2
About NXT-G Programs
11
12
Chapter 2 • About NXT-G Programs
Introduction NXT-G is a visual language where instead of writing the program in text, you work with icons that represent self-contained units of program instructions. These units are called programming blocks, or just blocks. You drag the required blocks on to the work area of the screen and arrange them on the sequence beam in the order in which they are to be executed (see Figure 2.1). Figure 2.1 Creating a program. A wait block is being dragged from the palette on the left and dropped on to the end of the sequence beam. The beam expands automatically to make room for it. The block will provide 1 second of silence after the second tone has been played.
When you first open your LEGO Mindstorms kit you are invited to begin by building the Quickstart buggy. This is a mobile vehicle with two drive wheels at the front and a small caster wheel at the rear (see Figure 2.2). The Quickstart has three motors, one for each drive wheel. The third motor is not used until later, when it is used to drive a gripper.
www.syngress.com
About NXT-G Programs • Chapter 2
Figure 2.2 This rear view of the Quickstart buggy shows the two drive wheels and the rear caster wheel. The advantage of this arrangement is the stable three-point contact with the surface, which does not have to be absolutely flat.
After you have built the Quickstart (or Tribot) it needs to be told what to do and how to behave. In other words, it needs to be programmed.
Creating a Program As explained above, a NXT-G program appears on the computer screen as a sequence of programming blocks placed in order of execution on a sequence beam. Each block is dragged from the programming palette on the left-hand side of the screen. Clicking on a block (see Figure 2.3) shows its settings in a configuration pane (see Figure 2.4) at the bottom left-hand side of the screen.
www.syngress.com
13
14
Chapter 2 • About NXT-G Programs
Figure 2.3 The icon for the move block shows the main settings, but you have to display the configuration pane (see Figure 2.4) to find out the details.
Figure 2.4 The configuration pane of the move block shows all the settings, which you can change to suit your program.
The settings are edited to suit the program. When the configuration panel is first displayed the settings are set to their default values. For example, the motor block always sets the motor to run forward. If you want it to run in reverse, you need to click the radio button beside the backward-pointing arrow. For some of the settings you have to enter a value. Many, but not all, of the settings are indicated by symbols on the block icons, so you can get a good idea of the program by looking at the displayed symbols. In Figure 2.3, for example, we can see that this is a move block because of the double gear wheels and that the motors operate on high power (but not the exact power) and runs for a given time (but not exactly how long). The icon does not show whether the next action is to brake or coast. You have to display the configuration pane (Figure 2.4) to discover the settings in full detail.
www.syngress.com
About NXT-G Programs • Chapter 2
Screen Shots
and
Comments
The programs in this book are illustrated by screen shots made when we had finished designing and testing them. If you copy them on to your computer exactly, they should work properly the first time. You can assume that all settings have their default values except where another option is quoted beside the block as a comment. The commenting makes programming quicker, because you edit only those values or options that are to be changed. The comments tell you what changes to make in the configuration pane.
Figure 2.5 The Quickstart buggy is ready to run its first program.
www.syngress.com
15
16
Chapter 2 • About NXT-G Programs
If you want a complete record of the program, you can type the comments as well as the blocks, which are saved along with the program. They will help you to remember how the program works if you come back to it a few months later. However, the comments are not incorporated into the compiled program, which is downloaded into the brick. Comments are added to the screen shots to make the program clearer to you and to show you how to edit the settings.
First Steps Figure 2.6 shows an example of a NXT program. It is the NXT-G equivalent of the traditional “Hello World” program that is featured in many books on programming. The Quickstart moves forward a short distance, says, “Have a nice day,” and then reverses back to its starting point. Figure 2.6 In the working area, the first program looks like this. Comments have been added to show some of the settings, but you do not need not include them. Just check the configuration panel of each block to make sure that you have edited the settings as specified in the comments.
The robot performs three different actions, one after the other. This means that the program has three action stages, and therefore consists of three action blocks: ■
Move To move the robot forward
■
Sound To say “Have a nice day”
■
Move To reverse back to the starting position
www.syngress.com
About NXT-G Programs • Chapter 2
Create and run the program by following these seven steps: 1. Build the sequence. Use the mouse to drag blocks from the programming palette on the left-hand side of the screen and drop them in order onto the sequence beam. 2. Settings. All settings have their default values except where otherwise indicated. Check or uncheck radio buttons, set sliders, and type values or text into text boxes. 3. Save the file under the file name firstSteps. 4. Compile and download. With the robot connected by USB cable or with Bluetooth switched on, click on the bottom left-hand side controller button. This compiles the program and downloads it into the NXT but does not run it.
Out
of
Memory?
If you get this error message when compiling, check the contents of the NXT’s memory.
5. Prepare to run the program. Disconnect the USB cable if used. Use the buttons on the NXT to navigate to the “Run” instruction. Starting at “My files,” press the orange button three times. The screen then displays the file name, firstSteps and the word “Run.” Put the robot on the floor, making sure there is at least 1.5 meters of clear space ahead of it.
Editing
the
Configuration Pane
In the first move block, checkboxes B and C are already checked by default, so do not need to be changed. Similarly, there’s no need to change the direction and steering settings. The power supplied to the motors is reduced to 50 percent and the duration is set to five rotations. The main change in the sound block is to set the spoken message to “Have a nice day.” At stage three, we have to alter the direction to backward, increase the power to 100 percent, and repeat the setting of five rotations.
www.syngress.com
17
18
Chapter 2 • About NXT-G Programs
6. All ready? Press the orange button. After a second or two delay, the robot moves forward, stops, says its party piece, and reverses back to its starting position. Because of the differing power levels in the two move blocks, the robot runs faster when it is returning to its starting position. Press the button again to repeat this star performance. 7. Switching off. When you are satisfied that the robot is behaving according to plan, conserve the power supply by switching it off. Three presses on the dark grey button bring you back to the “Switch off?” screen. Then press the orange button to switch off.
Try Something New! Alter one or more of the settings in the first program. For example, change the direction of the steering, change the power delivered to the motors, or select a different sound file. Re-save the program under a different file name, and then re-compile it. Run your new version. See what happens. Be ready to grab the robot if it starts to run into danger.
Out of Memory? You may get the “Out of Memory?” message during the compiling stage. At this stage, you will have to free some memory space before compiling can be completed. Often some of the files you find in memory are no longer needed. When you delete a program file, the files associated with it (e.g., sound files) are not automatically deleted. Sound files take up a lot of memory. For example, the “Have a nice day” file takes 5 kilobytes out of the total 130.7 kilobytes available. Be sure to delete it before going on to compile another program that does not use it. To manage memory, either click on the “Manage Memory” button in the window that appears during compiling, or click on the top left-hand button of the on-screen controller. In the panel that appears, click on the “Memory” tab. You will see a display of the current memory usage. Select and delete files that are no longer needed. www.syngress.com
About NXT-G Programs • Chapter 2
Coming for a Spin? The Quickstart robot can do more than run backward and forward. The move block can make it run on a curved path. Just shift the steering slider on the configuration panel. One motor is then powered to run faster than the other. This is the simplest way to make the robot change direction. To make it spin on the spot, shift the slider as far as it will go to the left or right. This makes one motor run forward and one motor run backward. The vehicle spins on a point midway between its two large wheels. The next program (see Figure 2.7) includes a spin. The robot advances, greets the watchers, retreats, and then spins on the spot. Its dancing skill deserves the applause that is programmed in the final Sound block. Figure 2.7 The next version of the program is like the first but ends in a spin.
Spinning is often used for scanning the surroundings with the light sensor or ultrasonic sensor.
Tying it Together One more element in the NXT-G program is the use of data wires to convey data from one block to one or more other blocks. Figure 2.8 shows a program that demonstrates the properties of data wires. It needs a light sensor plugged into socket 3. The sensor measures the intensity of light being reflected from a surface held about 1 centimeter away. The intensity is represented by a number in the range 0–100. The number is available at an output terminal on the data hub of the light sensor block. A data wire was drawn by clicking on that terminal and www.syngress.com
19
20
Chapter 2 • About NXT-G Programs
dragging a wire from there to the A input terminal of the math block. Note that the data output of the sensor block and the data input on the math block are both for numeric data. On the screen the wire is yellow, which is the color code for a wire carrying numeric data. Figure 2.8 Data wires carry information between blocks. Here, a yellow wire carries the light intensity reading (numeric data) from the sensor block to the math block. The second wire, which is green, carries a logical signal from the math block to the move block. The signal controls the direction in which the motors turn.
The math block compares the incoming data with the value 60, to which B was set when programming. The output from the math block is logical and is drawn with a green line. This line carries the logical result of the comparison: it is either True (intensity > 60) or False (intensity < 60). We use this data to control the direction of the motors. Expand the data hub, if necessary, by clicking on the bottom left of the icon. The terminal marked +/− is the one for direction control. Drag the data wire from the output of the math block to the direction control terminal. Test the program by holding the sensor against a white surface. When the program is run, and if the intensity is greater than 60, the output of the math block is True, and the motors turn one revolution in the forward direction. www.syngress.com
About NXT-G Programs • Chapter 2
Conversely, if the sensor is looking at a dark surface, the intensity is less than 60, the output of the math block is False, and the motors turn one revolution in the backward direction.
Compacting
the
Diagram
Data hubs may take up a lot of space. A clear example is the one on the move block in Figure 2.8. When you have finished connecting the data wires, click on the bottom left-hand corner of the icon. The data hub will contract, leaving only those terminals that have a data wire connection (see Figure 2.9).
Figure 2.9 The program in Figure 2.8 can be made more compact by contracting the long data hubs. The software automatically re-routes the data wires. You can expand the hubs again if you want to add more data wires later.
Text is the third kind of data that can be sent along data wires. Text data wires are red.
www.syngress.com
21
This page intentionally left blank
Chapter 3
Data
23
24
Chapter 3 • Data
Introduction At the end of Chapter 2 we described data wires and how to use them for sending data from one block to another. Handling data is what programming is all about, so let’s take a closer look at how data wires work. There are three kinds of data wires for conveying the three types of data: ■
■ ■
Numeric Integers (whole numbers), including negatives, for example 50, 6, −261. Logic Have one of two possible values, False or True. Text A string of alphanumeric characters, for example Hello, turn right, 471, D34r7.
One type of data that NXT-G does not have is floating point data; that is, numeric data with a decimal fraction. Examples are 3.4, 124.778, 72.9 (more precise than 73), and 0.0053. It is not often that we need to work with floating point values, but when we do, there are ways of doing equivalent calculations using integers.
Sources of Data The prime sources of numeric data are the sensors. Light sensors measure light intensity and the ultrasonic sensor measures the distance of an object. The sound sensor measures the loudness of a sound in decibels. The values of these quantities are available at terminals on the data hub of a block, and can be conveyed to another block by a numeric data wire. The math block is another source of numeric data, such as the result of adding two numbers. Some sensors produce logical output. The touch sensor sends out a logical True when its switch closes. At other times its output is False. The light sensor produces logical output in addition to the numeric output mentioned above. This is the result of comparing measured light intensity with a given pre-set level. The program in Figure 3.1 uses this output to control the direction of rotation of the motors. But, wait a minute. We already have a program that does this. Figure 2.9 has three
www.syngress.com
Data • Chapter 3
blocks to do what Figure 3.1 does in two blocks. The compare block in Figure 2.9 is redundant because there already is a comparator in the sensor block. Figure 2.9 is a demonstration program to illustrate two different kinds of data wire. However, it is 50 percent longer than it needs to be, wasting memory and processing time. Always try to minimize when programming. Figure 3.1 This version of the program in Figure 2.9 does the same thing but uses only two blocks. The math block of Figure 2.9 is redundant.
The most obvious source of text data is the number-to-text block. This accepts a numeric value as input and generates an alphanumeric string as output. For example, the input might be 427, which is the result of adding 250 to 177 in a math block. If you want to display this on the NXT window, you might try to use a display block, but unfortunately you cannot do this. The action section of the configuration pane offers only Image, Drawing, Text, and Reset. This is where the number-to-text block comes in handy. It takes the number 427 and turns it into a string of three characters 4, 2, and 7. Explore this with the short program in Figure 3.2.
www.syngress.com
25
26
Chapter 3 • Data
Figure 3.2 A useful program snippet for displaying numbers. Make it more compact by retracting the long data hub. Make it easier to use by turning the three blocks on the right into a My Block.
Note the five seconds wait after the display block. This is to give you time to read the display. This technique for reading numbers is often required in programs, especially when debugging. We have combined the number-to-text, display and wait blocks into a My Block named dispresult. It appears in many of the programs in this book.
Variables The values (numeric, logic, or text) that are referred to in the previous section are all dynamic. They originate in certain types of block and are carried to other blocks. They may remain constant for a while, but are liable to change. For instance, when the light falling on a light sensor changes, or when a touch sensor is pressed. Sometimes we want to store a value for reference at later stages in a program. If so, we store it in a variable block where it remains until it is changed. If a program includes variables, each is identified by giving it a name, which could be a one-letter name, such as x, y, a, or b. However, it is better to give it a more meaningful name, such as distance, direction, or answer. The name can be made up of two or more words without spaces in between. Some programmers follow the convention of typing variable names in lowercase. If there are two or more words, the second www.syngress.com
Data • Chapter 3
and subsequent words each begin with a capital letter. Examples are finalScore, firingAngle, and sizeOfObject. Each variable is defined in its own variable block. To create a variable block, click on the “Complete Palette” icon at the bottom left-hand side of the palette, then click on the Data icon (the red “plus” symbol). Drag out a variable block (see Figure 3.3). A variable is given its name by clicking on Edit, and then on Define variables. You can use the three variables already defined in the menu that appears, or you can define a new named variable. Figure 3.3 A variable block and its configuration pane. The three blocks listed in the menu are created automatically. When you create new variable blocks they appear in this menu. The menu is used for selecting the name of a block. For instance, the block in the working area has been designated as Logic 1 by clicking on that name in the list.
A Variable Has a Name, a Type, and a Value Variables are able to store one of three different types of data: ■
Numeric Integers (whole numbers). The default value is zero. Numbers can range from −2147483648 to 2147483647.
■
Logic False or True. The default value is False.
■
Text A string of alphanumeric characters. The default value is a blank. www.syngress.com
27
28
Chapter 3 • Data
Default When a block is first put down on the sequence beam its settings are set to default. If you want any of them to be set differently, you have to edit them.
When you configure a new variable block, declare it first by naming it as described above. Every time you add that variable block to a program, select this name from the variable list that is displayed in the configuration pane. The name of the variable appears on its icon. Remember that a variable of a given type cannot be given a value of another type. Variable blocks may be configured to read or write. If configured to write, a variable may be given an initial value, typed in on the configuration pane. Otherwise, it is given its value later by connecting it by a data wire to a block that generates the value.
Arithmetic Operators As might be expected from their name, these perform arithmetic operations on numeric values, including values stored in variable blocks. NXT-G provides for four operations, otherwise known as the “four rules.” These are add, subtract, multiply, and divide, and are all performed by the math block. The symbols used are +,−,*, and /. All operations are carried out as integer operations. Remember that, when dividing, the operation loses the digits after the decimal point. For example, 13/4 returns 3, not 3.25. Note that the integer result is not rounded, so that 15/4 gives 3, not 4. However, it is possible, though more complicated, to devise routines to perform division with rounding. Other mathematical operators such as modulo are described later.
Logical Operators Operations on logical variables comprise NOT, AND, OR and exclusive-OR (XOR). These operations are performed by a logic block. NAND and NOR can be obtained by using NOT after AND and OR. The operators perform whole-variable logic of two logic values, such as: If A = True and B = True, then A AND B = True
If A = True and B = False, then A AND B = False If A = True and B = False, then A OR B = True.
www.syngress.com
Data • Chapter 3
The icon of a logic block carries a Venn diagram indicating which operator is selected. There are no bit-wise logical operators in NXT-G.
Flag Variables Often we assign a logical variable to act as a flag. The variable has the default value False, but is set to True when a specified event occurs. For example, a flag variable named intensity can be set to True when the light sensor detects a light intensity greater than, say, 50. If another routine in the program needs to know whether or not that event has ever occurred, it reads the value of intensity. In some programs it is important to remember to reset the variable to False after its value has been read. An arithmetic variable can also be used as a flag. For example, its default value is 0, but is set to 1 when the event occurs. There are several examples of logical and arithmetic flags later in the book.
www.syngress.com
29
This page intentionally left blank
Chapter 4
Loops
31
32
Chapter 4 • Loops
Introduction A loop repeats a whole program or part of a program. Once the microcontrollers have entered a loop, they read the instructions in the loop over and over again, repeating the actions programmed within the loop. They exit at the end of the loop only when a given condition applies. We find the same sort of thing in a musical score (Figure 4.1). Figure 4.1 This musical score is an example of a loop that is repeated once. The two pairs of dots on the right tell the musician to go back and play part of the score again. By contrast, a loop block usually repeats more than once, perhaps many times or even “forever.”
One of the shortest possible loop programs is illustrated in Figure 4.2. The loop has its default configuration, “Forever.” The robot advances a short distance and then says “Good Morning.” It never leaves the loop. The program runs repeatedly until you either press the grey button on the NXT to abort the program, or you disconnect the power supply. Figure 4.2 This program runs forever in its loop.
www.syngress.com
Loops • Chapter 4
A Forever loop is useful in a games program, where the player is invited to play again when the current game has ended. In a program written in BASIC, we would achieve the same effect by putting a GOTO command at the end to send the microcontroller back to an earlier stage in the program, perhaps to the beginning.
Outside Events Figure 4.3 shows a loop ended by a signal from a sensor. The looping ends when the orange NXT button is pressed. On leaving the loop, the sound block says “Goodbye.” Other sensors may be used to end a loop. The sensor is selected from a drop-down menu in the configuration pane. You can set conditional values for the selected sensor. An appropriate icon appears at the exit point of the loop. This kind of loop is used to keep the program waiting for some outside event to occur, and to repeatedly do something while waiting. In Figure 4.3 there is a beep every time around the loop. Figure 4.3 The loop in this program repeats until the orange Enter button is pressed.
A similar loop is seen in Figure 4.4, using input from a light sensor to control the loop. When the light intensity exceeds 50, the comparator in the loop block generates a True signal. The controller exits from the loop and the robot says “Thank you.”
www.syngress.com
33
34
Chapter 4 • Loops
Figure 4.4 This loop repeats until the light intensity is greater than 50.
These are simple examples of loops ended by sensor input. The loop could be programmed to generate much more complex activity. If you do not want any activity while the loop is running, omit the blocks that generate the beeps. However a shorter option is to use a wait block, as explained later in this chapter.
Time Limit A loop can be set to run for a given time. This is used when we want to introduce a delay into a program. The loop will contain blocks to produce some kind of activity, usually something complicated. If it is only a simple activity, such as running a motor for 20 seconds, you do not use a loop; just set the motor block for 20. If you want to introduce a delay during which absolutely nothing happens, use a wait block.
Counting the Loops If you set “count” as the loop control, the actions in the loop are repeated a set number of times. This is the equivalent of a “FOR … Next” loop in a program written in BASIC, or a “FOR… loop” written in Java. The “Dance Some More” program below shows one way to use the loop counter.
Dance Some More To make the robot do more to earn applause, we add a loop block to its program. A loop can be included in a program when it is first created, but here we are modifying an existing program. www.syngress.com
Loops • Chapter 4 ■
■
Original Program Display the extended First steps program, with added spin and applause. Add the Loop Block Click on the loop block in the programming palette, drag it across and drop it on the first block that is to be included in the loop. This is the move block on the left-hand side of the sequence beam. The loop block settles into position on the left side and the existing blocks shift one place to the right. The loop is now included in the program, but there is nothing in the loop (Figure 4.5).
Figure 4.5 The loop block (left) is ready to receive some of the blocks to be transferred from the right.
■
■
■
Put Blocks Inside the Loop For each of the existing blocks, working from left to right, click on the block and drag it into the loop. As you drag each block, the loop expands to hold it. Repeat Move all of the blocks except the last one. The robot does not expect applause until it has repeated its dance a few times. The loop is a repeating structure as shown by the gray arrow in the diagram. This connects the last block in the loop (Move) to the beginning of the loop. Settings A loop block makes the program repeat until something happens to end the looping action. There is a choice of ways to end the loop. In the first option, the loop never ends. The buggy will dance until the battery dies, so ignore this option. This version of Quickstart is not equipped with sensors, so ignore this option. Tr y the “count” option where the default setting of the loop block is altered to “Count until 5.”
Figure 4.6 shows how it looks when ready to run. www.syngress.com
35
36
Chapter 4 • Loops
Figure 4.6 Ready to dance some more! We use a loop to repeat a sequence of actions. When the loop has repeated five times the controller leaves the loop and plays the Applause file.
Use Loops to Make Actions Repeat Another Way to Use the Loop Counter You can access the counter by clicking the check box (Show: Counter) in the configuration pane. A terminal appears at the beginning of the loop. To use the counter’s output, connect it by data wire to a block inside the loop. Figure 4.7 is a program snippet that demonstrates how to use the loop counter. The counter output is connected by data wire to the input of a math block. The block is set to multiply the count by 100, so the output of the block is successively 100, 200, 300, and so on, up to 1200. The data wire routes the values to the tone frequency input of the sound block. The result when the program is run is a tone that rises in frequency in 12 steps.
www.syngress.com
Loops • Chapter 4
Figure 4.7 Using the counter output of a loop block to generate a tone of gradually increasing pitch.
Logical Conclusions The loop can be programmed to end when a given logical variable changes from False to True, or vice versa. The change in value may occur within the loop or elsewhere in the program. For instance, the loop can respond to a change in the logical output from a sensor. Loops controlled by logic are the equivalents of the “DO … WHILE” and “WHILE …WEND” loops in BASIC. As described earlier, ending a loop by sensor or time is essentially a logical operation. The output of the sensor is either above or below the preset value; the preset time either has or has not elapsed. If the control is set to “logic,” we need to provide logical input from some other source, perhaps from a computation that produces a logical output. If we select “logic” from the drop-down list of loop control options, a terminal appears at the exit from the loop. This must be connected by data wire to a block that has logical output.
www.syngress.com
37
38
Chapter 4 • Loops
Use a Loop (or a Wait Block) to Wait for an Event to Occur Sometimes we may want the loop to respond to two sensors. For instance, there may be two light sensors and the loop is to end only when both sensors have outputs greater than 50. The program in Figure 4.8 shows how to do it. Figure 4.8 Using a logical signal to end a loop. When both sensors are receiving light, the robot stops bleeping and thanks you.
Most of the program is in a loop. The loop generates a tone burst, then, after a wait of 1 second, two light sensors sample the light intensity. One of these is plugged into NXT input 3, and the other into input 4. Although they are actually read one after the other, the control circuits of the NXT operate so fast that we can consider that both sensors sample the light at the same time. Each sensor produces a True output when the intensity of the light falling on it is greater than 50. Their outputs go (by data wires) to a logic block that is set to perform the AND operation. The output of this block is True if both of the sensors have a True output. A True output from the logic block ends the loop and the robot says “Thank you.” This program module is used in the Pathfinder and maze solving programs.
Nested Loops When one loop is run inside another loop we say that the inner loop is nested within the outer loop. Figure 4.9 shows an example of nested loops. This program is for a mobile robot. The inner loop makes it run forward and backward five times. www.syngress.com
Loops • Chapter 4
When the inner loop ends the program returns to the outer loop where the robot is made to spin four times. The action then repeats. The forward, backward, and spin pattern prompts the robot to exhibit a fancy dancing performance. Figure 4.9 Nested loops.
The Wait Block The activities of this block fall into two categories: ■
Waiting for the output of a sensor to change,
■
Waiting for an interval of time to elapse.
When the wait block is first placed on the sequence beam, its default configuration is to wait for the touch sensor to be pressed. Its icon (see Figure 4.10) carries a small hourglass (symbolizing wait) and a symbolic finger pressing a button (symbolizing the touch sensor). The icon changes appropriately when we configure the block for other sensors or for time.
www.syngress.com
39
40
Chapter 4 • Loops
Figure 4.10 To start with, a wait block is enabled to receive input from a touch sensor, as its icon shows.
The wait block receives input from a sensor or clock. It does not need a data wire to bring it this information. It delays the program while waiting for a suitable input signal, at which point the flow of the program is resumed. For these reasons, a wait block does not have a data hub.
www.syngress.com
Chapter 5
Switches and Other Topics
41
42
Chapter 5 • Switches and Other Topics
The Switch Block Switches allow the flow of a program to branch along one of two or more routes. The route taken depends on a preset condition. The condition may be the output from a sensor, or the value of a given variable (numeric, logic, or text). The program in Figure 5.1 shows a switch being controlled by the output of the light sensor. If the light intensity is less than 50, the switch routes the microcontrollers along the lower sequence beam. The sound block plays “dark.” If the intensity is greater than 50, the switch routes the microcontrollers along the upper beam and the sound block plays “light.” Either way, the microcontrollers eventually leave the switch by the single exit. Figure 5.1 Demonstrating how switch blocks work. The robot says “light” or “dark”, depending on whether or not its light sensor is receiving light.
Like a loop block, a switch may be controlled by the logical output from any of the sensor blocks. It may also be controlled by a value. The value may be numeric, logic, or text. Figure 5.2 shows a numeric source (a math block) that you can edit by making B equal to 0 or 1. The configuration pane of the switch block is displayed and shows what the switch will do. The input value is matched against the values in the right-hand column of the Conditions table. An input value of 0 matches the value n the top line, so the switch selects branch 1. This is the top branch in the diagram, on which the sound block is programmed to say “black.” If you edit the math block to send 1, the second line matches, the program is directed along the lower branch of the switch, and we hear “white.” www.syngress.com
Switches and Other Topics • Chapter 5
Figure 5.2 Configuring a switch block to be controlled by a numeric value.
The top line of the Conditions table is ticked. This means that this line is selected by default if the input is neither 0 nor 1. For example, if B = 5, we hear “black” when the program is run. Figure 5.3 illustrates a similar program based on matching text. Input comes from a text block in which we can type one of two keywords: “piano” or “message.” The Conditions table selects the top branch if the keyword is “message.” The sound block on the top branch is set to say “Thank you.” If the keyword is “piano,” the lower branch is selected and we hear a tone A for 2 seconds. As in the numeric example, one of the lines is ticked as the default. If any other keyword is received, the upper branch is selected.
www.syngress.com
43
44
Chapter 5 • Switches and Other Topics
Figure 5.3 Configuring a switch block to be controlled by a logic value.
A switch may contain many activity blocks, and include loops and further switch blocks. The “Magic” program illustrates the complex programs that can be built from loops and switches. Switch blocks are the equivalents of “IF…THEN” and “IF… THEN…ELSE” in BASIC.
Switch Blocks Direct Execution Along Alternative Pathways Simultaneous Processing The NXT is able to process two or more activities at the same time. In Figure 5.4, the sequence beam divides into two and both branches are run simultaneously. In this simple demonstration, the upper beam alternately displays two images for 1 second each. www.syngress.com
Switches and Other Topics • Chapter 5
The effect is that the eyes look from side to side, like those of a spectator at a tennis match. At the same time, the lower branch of the sequence beam generates a bleeping sound of 2-second tone bursts every 2.4 seconds. The NXT’s microcontrollers run the two activities simultaneously. Figure 5.4 An example of simultaneous processing.
Try Something New! Experiment with the switch block. Try using it with the ultrasonic sensor or the touch sensor to control the drive motors of Tribot. For instance, make the robot run forward until it is within 30 centimeters of a wall or other object. Then let it spin through a small angle before setting off in another direction. Try building a program in which the switch block is controlled by logical input.
www.syngress.com
45
46
Chapter 5 • Switches and Other Topics
Diagnostic Programming If you make a mistake when programming the NXT, it may result in an error message when the program is being compiled. Compiling stops and you can go no further until you have discovered and corrected the error. Sometimes the computer suggests what can be done to correct the error, and sometimes it doesn’t. A common error is to leave a data input unconnected when it should be connected to a source by a data wire. This type of error is easily detected and is rejected by the NXT, but other errors may escape detection and are accepted. The program runs, but not correctly. Errors that escape the NXT’s error-detecting routines are generally the result of mistaken programming. You intend to instruct the NXT to do one thing (such as adding two numbers together) but actually you have instructed it to do something else (such as multiplying them together). You have made a mistake in working out the math or the logic, or have forgotten to alter one of the settings. The NXT does not know the difference between right and wrong, so it goes ahead obeying your faulty program. For example, a listing includes complicated calculations, which look correct but seem to be producing an incorrect answer. The best approach is to go back and check the calculations stage by stage. Work it out on paper, and then compare the results with what actually happens on the robot. Identify the stage at which an error first appears. This approach may help to locate the reason for the error. In Figure 5.5, the numeric variable angle is being read to check that its value is correct. It is fed to a number-to-text block, which converts it into text to display on the NXT window. For instance, if angle equals 12 (a numeric value), the block turns it into 12 (a string of two numeric characters). The data is sent to a display block to display it on the screen of the NXT. The display block is followed by a 100-second wait to allow time to read the display before continuing with the program.
www.syngress.com
Switches and Other Topics • Chapter 5
Figure 5.5 Checking the progress of a calculation by displaying the intermediate results.
This diagnostic sequence of four blocks will not be part of the final program. It is deleted after it is confirmed that the value of the angle is correct at this stage. The sequence may be inserted temporarily at each stage in a complicated calculation, working through from beginning to end. Each stage is verified, after which the diagnostic sequence is deleted. If you have many calculations to check, first make the diagnostic sequence into a my block. Figure 5.6 shows the icon for the my block, which we created for testing the calculations in our programs. It is called dispresult. Figure 5.6 A useful my block that displays numeric results. This was generated from the program illustrated in Figure 5.5.
www.syngress.com
47
48
Chapter 5 • Switches and Other Topics
Sound files and tones are handy for confirming that a program is running as intended. They are particularly useful when a program includes a switch block. A different sound file or a tone of different pitch is programmed into each branch. As the microprocessors run along a branch they trigger off the appropriate sound. This allows the programmer to check that the right route is being taken. In the “Wait” section of the Configuration pane, uncheck the “Wait for Completion” radio button. This makes the program run without being delayed by the sound. Figure 5.7 below runs in a “Forever” loop. In the light, it says “Light” and turns on the motor for 5 s. In the dark it says “Dark” and turns the motor off. More activities can be added to each branch. After checking that these operate correctly and experimenting to find the best setting for the threshold light level, the two sound blocks are deleted. Figure 5.7 This program indicates which branch is being followed by saying “light” or “dark.”
Our other useful my block for debugging programs is called displogic (see Figure 5.8). It has a similar structure to dispresult. It accepts logical (that is, Boolean) input. Figure 5.9 is the configuration pane of the switch. If the input is True, the upper branch of the switch is selected. The value stored in the variable block called resstring www.syngress.com
Switches and Other Topics • Chapter 5
is the text “True.” If the input is False, the lower branch is taken and resstring is set to “False.” Beyond the switch block, the text value held in resstring is sent to the display block and appears on the NXT screen. Figure 5.8 A program module for reading logical values when debugging.
Figure 5.9 The configuration pane when setting the program of Figure 5.8.
www.syngress.com
49
This page intentionally left blank
Chapter 6
Using the Light Sensor
˛ Summary
51
52
Chapter 6 • Using the Light Sensor
Introduction The light sensor is the most useful of the NXT’s sensors. As seen in Figure 6.1, the sensor comprises two LEDs. One is the actual sensor, a photodiode, which receives light and is used to measure its intensity. The other is an ordinary LED, which illuminates a surface so the first LED can measure the amount of light being reflected from it. Figure 6.1 The light sensor showing the photodiode (top) and the illuminating LED (bottom).
The icon (see Figure 6.2) has a “light” symbol to identify it, and the bar across the icon is yellow. The icon exhibits a smaller light symbol if the LED is switched on. There is also a histogram symbol to indicate roughly if the threshold of its comparator is set to low or high.
www.syngress.com
Using the Light Sensor • Chapter 6
Figure 6.2 The light sensor’s icon and configuration pane.
When first displayed, the block shows only the output terminal for the light intensity signal. When you expand the data hub (see Figure 6.3) it reveals (from the top downward): ■
Port input, settable by data wire
■
Trigger point, the comparator threshold, settable by data wire
■
><, whether a True output means > or < the threshold, settable by data wire
■
Illuminating LED on or off, settable by data wire
■
Logical output from comparator
■
Intensity output (0–100)
■
Raw intensity output (0–1024)
www.syngress.com
53
54
Chapter 6 • Using the Light Sensor
Figure 6.3 The extended data hub has seven single or double data plugs. The double plugs are for inputs, receiving the signal on the left. They also relay it unchanged to the corresponding plugs on the right. The single plugs (right side only) are for outputs from the processing circuits of the block.
The intensity may be read directly while a program is running on the NXT. Click on the icon and watch the box in the left-most section of the configuration pane. This displays the current intensity. This feature is very useful when you are setting a threshold value for the comparator.
Light Sensor Directed Downward Figures 6.4 and 6.5 show the light sensor mounted on the Quickstart vehicle, pointing down. Mounting details are illustrated in Figures 6.6 and 6.7.
www.syngress.com
Using the Light Sensor • Chapter 6
Figure 6.4 When mounted in the downwardly directed position, the diodes are about 1 centimeter above the surface.
Figure 6.5 Another view of the downwardly directed light sensor.
www.syngress.com
55
56
Chapter 6 • Using the Light Sensor
Figure 6.6 The light sensor is ready to mount on the front beam of the Quickstart.
Figure 6.7 Ready to mount, another view.
In this position, it is nearly always used with the LED switched on and the photodiode receives light reflected from the surface beneath. Typically it is used for detecting dark-toned (black paint) markings on a light surface (white card). However, we often found it more convenient to run the robots on a panel of builder’s hardboard, which is dark brown, and the markings are made with a roll of decorator’s masking tape, which is almost pure white. www.syngress.com
Using the Light Sensor • Chapter 6
Lined in A Quickstart robot or a Tribot can be imprisoned by drawing a line around it. It has a down-pointing light sensor and runs on a light-colored surface with an area enclosed by a black line. The line is about 3 centimeters wide and can outline any regular or irregular area. Try leaving a 10-centimeter gap in the line and see how long it takes the robot to escape (see Figure 6.8). Figure 6.8 The LinedIn program prevents the robot from crossing a line.
There is a data wire joining the output of the random block to the control input of the switch block. The robot is started at any point within the area. The program enters the outer loop, a “forever” loop, and moves forward a short distance. It stops and measures the intensity of the reflected light. If it is greater than 50, the robot has not reached the line. www.syngress.com
57
58
Chapter 6 • Using the Light Sensor
Consequently, the statement “intensity > 50” is true. A True input to the switch sends the program along the upper branch, on which nothing happens. The loop repeats and the robot moves straight ahead, indefinitely. Eventually it comes to a line and “intensity > 50” is false. The False input causes the lower branch to be followed and a lot happens. First, the motors are put into reverse to back the robot away from the line. Then a random block generates 0 or 1. This value is fed to the inner switch block. The robot is made to spin left or right. After this, the program drops back into the outer loop and resumes running forward. You may find that performance is improved by adjusting the motor duration settings, and it may also be necessary to alter the light sensor’s threshold level, particularly if the ambient light is extra bright. The random routine helps to make the robot’s behavior appear to be lifelike. There is no real need to include the inner switch block. Just use a single spin to the left. However, there is some doubt about the random block being truly random for the range 0–1 (see the Maze Learner program), but this is no problem in the current program. You could modify LinedIn to operate in a truly random way. The program runs forever. Modify it to stop when the robot has encountered the line, say, 20 times.
Line Follower Following a line is a popular way of directing a robot from one location to another. Or, if the line is an irregular closed loop, it is entertaining to watch the robot circulate around it, especially on the sharper bends. In practice, working with only one sensor, the robot is programmed to follow the edge of the line. It keeps the sensor half on and half off the line. The trigger point of the sensor reading is set to an average of the fully black and fully white readings. The program (see Figure 6.9) operates by negative feedback. Suppose the robot is to follow the right-hand edge of the line. If the robot veers to the left, the sensor comes more fully over the line and the intensity falls below the threshold. The statement “intensity < 50” becomes true and the robot turns right to increase intensity above the threshold. The converse happens if the robot veers to the right—it turns left. In this way, the robot follows the line in a zigzag fashion, along its right-hand edge. This program works provided that the line is wide enough for the robot not to reach the left-hand edge. If it gets across to this edge, feedback becomes positive, the system becomes unstable, and the robot quickly strays away from the line. www.syngress.com
Using the Light Sensor • Chapter 6
Figure 6.9 In the Line Follower program the robot actually follows one edge of the line.
Edge Follower This is another approach to following the edge of a line or area. It is a simple program that produces a less jerky action than the Line Follower. It relies on biasing the path of the robot to the left so that it tends to hug a straight edge or a curving edge that curves to the left. This is how it works. As long as the sensor is to the right of the line, the robot hugs the curve (you may have to increase the rate of curving if there are sharp leftward bends). If the sensor actually comes over the line, light intensity falls. The lower branch of the switch makes the robot back away from the line, spin a little to the right, and run forward again. It repeats this action until the sensor is once again clear of the line.
www.syngress.com
59
60
Chapter 6 • Using the Light Sensor
Figure 6.10 The Edge Follower program is simple and works well on paths that curve mainly in one direction.
Try Something New The Edge Follower program does not always negotiate a line that curves to the right. Extend the program to cope with right-turning curves.
Light Sensor Directed Upward You may wonder why a robot would want to be aware of something above its head but, if the Tribot is mimicking the behavior of a housefly, it is always on the alert to possible attack from above. The Housefly program below shows how a robot can be made to behave like a housefly.
www.syngress.com
Using the Light Sensor • Chapter 6
Housefly This program requires the light sensor to be mounted on top of the Quickstart robot or the Tribot. You could also write a version for Spike, the scorpion, maybe with a more aggressive response. The program is an example of parallel or simultaneous programming. There are two routines, each running in separate “forever” loops. There are data wires in the upper loop, from the first light sensor block to the light variable block and (carrying the same data) from the light block to math block A. There are also data wires from the second light sensor block to math block B. Finally, there are data wires from the math block to the change variable block. In the upper loop, data wires run from the change variable block and from there to the switch block. The Condition table for the switch block is set to 1. False or 2. True. The upper loop is waiting for a rapid reduction of light intensity. To the housefly, this could be the shadow of an approaching fly swatter. Slower changes are to be ignored as they do not indicate danger. The way to detect a rapid change is to sample the light twice with a short interval (0.1 seconds) between samples. If the intensity falls by more than a given amount during that interval, there is a threat of danger. The math block calculates the reduction in intensity by subtracting B (the second sample) from A (the first sample). The difference is stored in the change variable block. Note that this program acts on the difference between the two intensities. For this reason, it works under a range of ambient intensities ranging from dull cloudy to bright sunlight. Meanwhile, the lower loop represents the normal behavior of feeding flies. It stays where it is. Each time around the loop it reads the change variable and, if it is greater than 5, switches the program along the “do nothing” path (the condition is False, so follow the top branch). The upper loop continues to sample and calculate, and the difference is read from the change variable in the lower loop. The two loops are running independently of each other but the continually updated value of change calculated in the upper loop is immediately available in the lower loop. A shadow falling suddenly on the sensor causes change to increase. The quicker the shadow the greater the increase. If change exceeds 5, even if only for one run through the lower loop, the switch block sends the program through its lower branch. The motors are switched fully on and the robot accelerates to a safer spot a short distance away.
www.syngress.com
61
62
Chapter 6 • Using the Light Sensor
Figure 6.11 While the housefly (Tribot) is peacefully feeding on the cake icing, a branch of the program is continuously on the alert for the approach of a fly swatter.
Try Something Different! Fine-tune the settings to make the fly more difficult to swat. Try bringing your hand very slowly toward the sensor so that you succeed in touching the fly before it escapes. It is said that some flies jump backward when they take off. Modify the program to simulate this, or program it to take a fast twisting escape path.
www.syngress.com
Using the Light Sensor • Chapter 6
Light Sensor Directed Forward There are many applications for a light sensor that points forward. In this section, you will find how to program the sensor in routines that avoid light or seek it. The seeking routines can become quite complicated if designed for use in a room with many light sources. Then there are the uses of light sensors as proximity detectors. Figure 6.12 shows one way of fixing a sensor at the front of the robot. Figure 6.12 A forward pointing light sensor is used in avoidance and seeking routines, and could often function as a proximity detector.
Lightfinder1 This short program, like all the other programs in this section, is intended for a mobile robot with tank steering. Quickstart and Tribot are examples. The LightFinder1 routine is very elementary (see Figure 6.13). It spins the robot around until it finds a source of light that is greater than a preset intensity.
www.syngress.com
63
64
Chapter 6 • Using the Light Sensor
Figure 6.13 The LightFinder1 routine.
The program operates in a loop. The drive motors turn in opposite directions, spinning the robot through a small angle. The motors stop and the light intensity is read. If the intensity is greater than 50, the loop ends. The routine stops at the first bright light it finds and ignores other, possibly brighter, lights that are in the room. This may or may not suit the application. To use this routine there must be at least one bright light for it to find. If not, the robot spins forever. A possible extension would count the number of times the loop is run. If the robot has been spun in a complete 360-degree turn and has found nothing, the threshold light intensity is reduced dynamically. But you cannot do this with the light intensity comparator. Instead, use a light sensor block (which has a data plug for setting the threshold by data wire). The logic output from the sensor is used as the logic control to end the loop.
LightFinder2 With parallel processing, the tasks of spinning the robot and looking for bright light are run separately. The action is much smoother than in LightFinder1 because the motors are not continually starting and stopping. In LightFinder2 (see Figure 6.14) the upper branch turns on the motors and leaves the robot spinning until told to stop.
www.syngress.com
Using the Light Sensor • Chapter 6
Figure 6.14 LightFinder2 does the same thing as LightFinder1, but the action is smoother.
The lower branch shows another way of ending the loop. If the intensity is greater than 50, the logical output from the light sensor block ends the loop. Expand the data hub of the light sensor block and draw a data wire from the block to the output terminal of the loop. Because there is only one activity block in the loop, the loop repeats more frequently, which means we have more frequent sampling of the light intensity. This continues until the intensity is above a threshold level, at which point the program leaves the loop and turns the motors off.
Almost an Interrupt The structure of this program is about as near as one can get to the interrupt structure in assembler language programs. This is actually a polling program, but the poll rate is so frequent that it is like an interrupted routine in its effect. However, there’s no saving of variables when an interrupt occurs so it’s not exactly the same. The program has the disadvantage that it stops at the first bright light it comes to and ignores any other lights in the room. To make a complete scan of the room, use LightFinder3. www.syngress.com
65
66
Chapter 6 • Using the Light Sensor
LightFinder3 Quite often we want to pick out the brightest source of light of many sources that are in the room. The LightFinder3 program (see Figure 6.15) does just this. Figure 6.15 The program for LightFinder3.
There are data wires to the input of the input variable block and also to input B of the compare block. Another data wire runs from the output of the maximum block to input A of the compare block. Within the switch block, the input variable is fed to the maximum variable to update it. The program runs in a continuous loop, which can be set for as many repeats as are needed to scan the room completely. Within the loop, the first block spins the robot through a small angle. Then the light sensor block samples the light intensity ahead. This is saved in the input variable and at the same time, sent on to the compare block, input B. The compare block also has input from the maximum variable block. If the latest reading of intensity is greater than the previous maximum, the program follows the top branch of the switch block, where maximum is given the value of the latest input. Otherwise, the maximum value is left unaltered. In this way, every time a new input value exceeds all previous values, the new input value is assigned to the maximum variable. The settings of the loop and the move block at the beginning of the routine can be adjusted so that the robot scan takes in a complete view of the room. You can choose between scanning a few times at widely separated angles, or making the angle smaller and having more samples. You therefore need to a set both the duration of the move block and the number of counts of the loop. www.syngress.com
Using the Light Sensor • Chapter 6
LightFinder4 In this program, the robot searches for the brightest light in the room and moves towards it. In any light finding routine, the directional precision is not high. The robot heads towards the light in the direction it is facing, but finds that it is heading to one side of the light. It needs to repeat the scan and head off in a modified direction. This process of continually correcting the direction eventually brings it to its goal. The lighting pattern in the room may change while all of this is happening, in which case the robot roams around the room continually searching for the brightest light. The program looks simple (see Figure 6.16), however, the first block is more complicated than it appears. Let’s say that the first block, which is the my block, is where all the action occurs, where it performs the turning and searching for light. The main progress of the robot from one scan to the next is the result of the move block. The motor duration of this is set to 80 degrees, but you can experiment with this value.You need to make the robot move a reasonable distance, otherwise we’ll get nowhere, but if the distances between the scan is too great, the robot may find itself up against the wall and in the dark. So it’s a matter of compromise. Figure 6.16 This program is more complicated than it appears.
Now let’s put look at ScanTurn. The easiest way to do this is to click on the bottom left edge of the icon and expand it. This reveals a complex array of programming blocks (see Figures 6.17 and 6.18). ScanTurn begins with a variable block called maximum. The content of this is set to zero. This is a precaution in case maximum has been used already in the outside program. The main part of this my block is the loop that follows. This is set to run for 10 repeats. At each repeat of the loop, the data wire running from the count terminal of the loop carries the loop number, to be saved in a variable block called iteration. www.syngress.com
67
68
Chapter 6 • Using the Light Sensor
Figure 6.17 The main loop of this program contains another my block called MaxIteration.
Figure 6.18 Spinning the robot back to the position in which it received maximum light.
Next comes the light sensor block where there is a data wire carrying light intensity to a my block called MaxIteration. Here we have a my block within a my block. Leaving the details of MaxIteration for a moment, we see that the loop concludes with a burst of power from the motors. The move block is set to spin the robot through a small angle. In the trials, the duration of the motor was set to 80 degrees, which produced a rotation of the robot of about 40 degrees. This gave it 10 samplings in one complete sweep of the room. As with the previous program, you can choose between having a few samplings widely spaced or for greater precision, a small angle between the samples with greater accuracy. But this program is a bit more complicated and clever. The robot spins to sample the whole room and, as it does so, it records which sample is the biggest. Having sampled the whole room, it then spins back to the position that had the maximum www.syngress.com
Using the Light Sensor • Chapter 6
light intensity (see Figure 6.18). This begins with the variable block called MaxLight. This holds the value carried through from MaxIteration. This is not the light intensity, but rather is the number of the sample in which light intensity was greatest. A calculation follows in which the number of the sample is subtracted from nine (A has been preset to 9), and then the difference is multiplied by 80. This gives the number of degrees that the robot should rotate in order to get back to the position in which it received maximum light. Figure 6.19 The inner structure of MaxIteration.
If your program has either more or fewer sampling positions, you need to use different values in this routine. A is to be set to the number of samples minus one. Then you need to multiply by the same amount as was used for the number of rotations between samples during the scan. After using a my block within a my block, we get to the end of the secret mysteries of the program. This final my block is the one in which the sampling occurs and the position in which the brightest light was found is recorded as MaxLight. The light intensity of the current sample is fed in from the light sensor (see Figure 6.17). In Figure 6.18, we see what happens to the signal. It is first stored in a variable block called input. This is compared with the value of maximum, and the result is sent to the switch block. If the input is less than maximum, nothing happens. If the input is greater than maximum, the current value of the input is stored as maximum and at the same time the current number of the iteration is stored (that is, the number of the iteration in which light was at a maximum).
www.syngress.com
69
70
Chapter 6 • Using the Light Sensor
Summary MaxIteration accepts light intensity and keeps the value of the maximum light intensity found so far, and at the same time records the number of the iteration in which the maximum light intensity was found. ScanTurn uses MaxIteration as it sweeps around the room and finds the position in which it receives the greatest amount of light. The robot is now pointing towards the brightest light source and the LightFinder program takes it towards it. The process repeats 10 (or however many are wanted) times, and then stops, but can be continued by pressing the Run button again.
www.syngress.com
Chapter 7
Using the Touch Sensor and the NXT Buttons
71
72
Chapter 7 • Using the Touch Sensor and the NXT Buttons
Introduction The touch sensor is a typical pushbutton that can be pressed or not pressed. Usually, we build a simple lever system to touch against the button. An example is the system used in TriBot (see Figure 7.1). The arrangement is used to detect when the robot has bumped into something or when there is an object ahead that is ready for grabbing. These are the two main uses of the touch sensor. Figure 7.1 The bumper mechanism of Tribot consists of a freely swinging paddle that rests against the button of the touch sensor.
The touch sensor is used with any one of four programming blocks (see Figure 7.2). On its own, and in conjunction with loops, switches, and wait blocks, it can be said to respond to three types of touch: ■
At the instant the button is pressed
■
At the instant the button is released
■
When the button is bumped (pressed and released)
Which one you use depends on the action you wish to initiate.
www.syngress.com
Using the Touch Sensor and the NXT Buttons • Chapter 7
Figure 7.2 The touch sensor is a feature of four programming blocks.
The touch sensor can be used as an elementary way of communicating with the robot. You can use it instead of, or as well as, the three buttons on the NXT.
Waiting for Contact Figure 7.3 shows one way to use a wait block. In this version of the program, the robot waits patiently for the sensor to be pressed before going on to other activities. This routine can be used at the beginning of a program in which you need to have everything ready before the action begins. Often simply pressing Run does not give enough time for the operator to get clear of the robot. After pressing the Run button, this program has a short delay before things start to operate.
www.syngress.com
73
74
Chapter 7 • Using the Touch Sensor and the NXT Buttons
Figure 7.3 If you put this routine at the beginning of a program, it will prevent the robot from running away before you are ready for it.
Bumper This program uses the touch sensor for a more typical purpose. When the mobile robot encounters an object in its path it may simply stop, bulldoze the object away, or navigate around it. The most realistic reaction is to navigate around the object. This program initializes the navigation. The touch sensor is usually provided with a lever or a hinged plate to act as a bumper. Figure 7.4 shows a typical example of a bumper mechanism. When the robot vehicle runs against the object, the lever is deflected and presses the button of the sensor. What happens in this program is that the vehicle runs forward until it hits an object. Then it stops, backs up a short distance, spins through a small angle, bleeps, and then continues to run forward again. The first block sets the motors to rush forward indefinitely, so the robot will scoot around the room banging into objects and changing direction. Figure 7.4 The bumper program sends the Quickstart vehicle rushing around the room, bouncing off objects.
As we can see, the program runs indefinitely in a loop. The first block is a move block, which starts the motors running straight ahead indefinitely (that is, until they are told to do something else). The wait block is programmed to wait until the touch sensor www.syngress.com
Using the Touch Sensor and the NXT Buttons • Chapter 7
is bumped. Sooner or later the robot will hit an obstacle, thereby ending the wait period. The program continues with a move block to make the vehicle back up for a short distance. Then comes another move block to spin it left through a small angle. That done, the sound block produces a 2-second bleep. At this stage, the vehicle is a short distance away from the obstacle and facing in a different direction. At the end of the loop, the controller is sent back to the beginning, where the move block makes the vehicle run straight ahead in the new direction. You can omit the bleep in this program, which will speed up the action. This program is the basis of a number of obstacle avoidance routines.
Waiting for Input This routine allows you the time to make some sort of input to a running program. If, after a given period of time, you have not made any input, the routine carries on. Another way of looking at the action is to think of it as a waiting period or delay, which you could end before the appointed time by pressing the button. The program (see Figure 7.5) has several data wires. In the upper branch of the sequence beam a wire runs from the NXT buttons to passit, pressed, and the loop exit. In the lower branch, a wire runs from passit to the loop exit. Figure 7.5 This program can be modified to use the other NXT buttons.
www.syngress.com
75
76
Chapter 7 • Using the Touch Sensor and the NXT Buttons
When the program gets to this routine, its action is halted and it waits for the left button to be pressed. If the left button is pressed, there are two bleeps. The program continues with the pressed variable set to True. If five seconds have elapsed with no button press, there is a timeout and the program continues by emitting a single bleep and with pressed set to False. This routine is an example of parallel processing. The sequence beam branches into three and the branches are processed simultaneously. The program relies on a flag variable named passit. This is a Boolean (logic) variable that is False in the default state, but is changed to True when the wait is ended. In the upper branch that runs in a loop, the NXT buttons are continuously monitored by the NXT buttons block. The output from the block is fed to the passit and pressed variables. The value of these two variables is False to begin with, but they are changed to True when the left button is pressed. In the middle branch there is a five-second wait, after which passit is set to True. The lower branch is where the program waits for passit to become True, either as a result of a button pressed or as the result of the timeout. The next stage in the main program follows. In this example, there is a sound block to produce a bleep, indicating that the wait period is over. This program responds to the grey button on the left. You can also set the buttons block to respond to the grey button on the right or to the orange Enter button. This program is useful when you want a delay that can be ended ahead of time by pressing a button. Later stages in the program you can read pressed to discover if the wait was ended by pressing a key or ended by default as a result of the timeout.
Scanning the NXT Buttons The previous program responded to one particular button of the three. This program responds to any one of the three buttons and lets you know which one was pressed. The next buttons are identified by the numerical code: 1 = right button 2 = left button 3 = enter button
www.syngress.com
Using the Touch Sensor and the NXT Buttons • Chapter 7
These are the values used while scanning in the program (see Figures 7.6 and 7.7). Figure 7.6 A program for scanning the NXT buttons.
Figure 7.7 The output from the program in Figure 7.6 is the code for the button that was pressed.
www.syngress.com
77
78
Chapter 7 • Using the Touch Sensor and the NXT Buttons
The following table shows the data wires in this program: Source
Value held
Destination
Action
Loop counter
Count
xmody, B
Math1
3
xmody, A
Scanning sequence: 0, 1, 2
xmody
Scanning sequence: 0, 1, 2
Math2, A
Scanning sequence: 1, 2, 3
Math2
Scanning sequence: 1,2, 3
Buttons
Scan buttons
Math2
Scanning sequence: 1, 2, 3
Pressed
Buttons
True when button pressed
Loop exit
Number of pressed button End scan
Pressed
Number of pressed button
dispresult
Display number of pressed key
The action of the routine is to halt execution of the main program while buttons are scanned for input. When one of the buttons is pressed, the program resumes with the code for the pressed button stored in the numeric pressed variable. The routine runs in a loop, scanning the buttons for input. Scanning relies on the action of the my block, xmody. There are three keys to scan so y = 3. This value is fed to xmody from the Math1. The output of the loop counter functions as x. It goes to the x input of xmody. The output from xmody cycles through 0, 1, 2, …, but we need it to cycle through the button codes 1, 2, and 3. This is easy. Just add 1 to the output, using Math2. Its output is fed to the NXT buttons block. The logical output from the block is normally False and is fed to the loop exit. This makes the loop repeat. But, if the button is pressed at the time when it’s code is on the button’s input terminal, it becomes True. The loop ends and the controllers move on to process the blocks following the loop. At the same time as the loop is ending, the button code is fed from Math2 to the pressed variable. Upon leaving the loop we hear a short bleep to indicate that the button press has been registered. In this demo version, the value of pressed was fed to dispresult (not shown) so that we can check that the routine is working correctly. www.syngress.com
Using the Touch Sensor and the NXT Buttons • Chapter 7
If you need to scan only keys left and right, make B = 2 in Math3. This program has several applications, particularly in games programs and for controlling machines such as RoboArm.
Entering Numbers The NXT does not have a numeric keyboard, so this program (see Figures 7.8 and 7. 9) is a substitute for that. Pressing the Enter button repeatedly displays a number that begins at 1 and increases by 1 at each press. When the intended value is reached, pressing the left button ends the routine. Figure 7.8 A routine for entering a number by pressing the orange button that number of times. The scanning routine of figure is 7.6 has been converted into a my book called scanButton.
Figure 7.9 The number program of figure 7.8 continued.
www.syngress.com
79
80
Chapter 7 • Using the Touch Sensor and the NXT Buttons
This program has a large number of data wires. There is a data wire running from the ScanButtons my block to the input terminal of the switch block. In the top branch of the switch block there is a data wire running from passit to finish. In the bottom branch there are wires running from selected to Math, Math to the second selected, Math to number-to-text, and from number-to-text to display. At the loop exit a data wire runs from finish to the loop exit terminal. After the loop there are wires running from selected to number-to-text, and from number-to-text to display. The program runs in a loop, starting with the ScanButton my block (see Figures 7.6 and 7.7). This scans the three NXT buttons and, when a button is pressed, the routine continues with the code for the button stored in selected, and with passit set to True. In the switch, the lower branch is followed if the enter button has been pressed. There is a short beep and then the value in selected is incremented. This value is converted into text and displayed. This process is repeated every time the Enter key is pressed. If the left button is pressed, the top branch is followed. The passit variable was set to True by ScanButton and now this value is transferred to finish. The program runs on to the exit where the True value held by finish is used to end the loop. A variation of this program is to give B in the math block a different value. In this way we can obtain a different arithmetic series, such as 5, 10, 15, 20 and so on. To do this, preset selected with a starting value to begin the series. Applications of this program include selecting options, calibrating sensor outputs, and any other application where a program needs to be told a number while the program is running.
www.syngress.com
Chapter 8
Using the Ultrasonic Sensor
81
82
Chapter 8 • Using the Ultrasonic Sensor
Introduction Like the light sensor, the ultrasonic sensor is useful for detecting objects that are some distance away from the robot. However, unlike the touch sensor, the ultrasonic sensor does not rely on physical contact. The distance gives more space in which to respond. Generally, the ultrasonic sensor is used for distances of 10 centimeters or more, whereas the light sensor is used at shorter distances. Programs that employ the light sensor can be adapted to use with the ultrasonic sensor. For instance, you can use the ultrasonic sensor to scan the room for nearby objects. The ultrasonic sensor can be used for detecting and avoiding objects. Programs for wheeled buggies like QuickStart are easily written. With a walking robot such as Alpha Rex, programming is a little more complicated because of the need to keep the motors in sync. The following program is an example of this.
Avoidance Routine for Alpha Rex This routine is intended for Alpha Rex fitted with a forwardly directed ultrasonic sensor (see Figure 8.1). Figure 8.1 Alpha Rex has an ultrasonic sensor facing forward, and is avoiding an object in its path.
www.syngress.com
Using the Ultrasonic Sensor • Chapter 8
The robot walks forward until it detects an object ahead. If the object is less than 35 centimeters (or any other preset distance) away from the robot, the robot turns to the left until it is no longer heading towards the object. It then resumes walking forward. The program consists of a switch block controlled by the ultrasonic sensor. If there is no object in view, the lower branch runs a move block for six revolutions. The loop repeats the action of moving the robot straight ahead. If an object is detected closer than 35 centimeters, the upper branch runs a motor block for motor B only and the robot turns left. Note that we use a move block for running straight ahead and a motor block for turning. Figure 8.2 An obstacle avoidance program for Alpha Rex.
For testing purposes, the program is enclosed in a loop, which is limited to 20 repetitions (Figure 8.2). Always let the robot run the full number of turns. If you stop it earlier, the two motors may get out of sync and the robot will not walk correctly. Because the robot turns instead of spinning on the spot, it needs to start avoiding the object while there is still room to turn. The minimum triggering distance for avoiding the object therefore depends on the width of the object. You will need to experiment by trying different distances. Also experiment with the number of rotations to find the best settings. www.syngress.com
83
84
Chapter 8 • Using the Ultrasonic Sensor
Ultrasonic Search In this program, the robot rotates left until it detects an object less than 40 centimeters away. Then it runs toward it at high speed. Figure 8.3 Alpha Rex getting tough with milk bottles.
This program (Figure 8.4) is very similar in structure to the avoidance program above, but operates in the reverse direction. The loop limits the session to 40 repeats. The switch block is controlled by the ultrasonic sensor. The lower branch is followed if there is no object within the 40 centimeters range. In this case, motor B turns the robot to the left. Then the loop returns to the beginning and reads the ultrasonic sensor again. This action repeats until the robot finds an object ahead of it and within 40 cm.
www.syngress.com
Using the Ultrasonic Sensor • Chapter 8
Figure 8.4 This program has the opposite action to that in Figure 8.2.
When an object is detected, the move block in the upper branch of the program drives the robot straight ahead at full speed until it strikes the object. With a suitably lightweight object, the robot either pushes it out of its path or knocks it over. In either event, the object disappears from view. Then Alpha Rex repeats the scanning action, looking for another object to attack. This robot likes to knock down skittles or other small objects that are fairly unstable. Figure 8.3 shows Alpha Rex attacking a collection of empty milk bottles. This makes a game for two or more human players. In turn, each player has to decide the best arrangement for the skittles, where Alpha Rex starts, and which direction it is facing. Then the program is run to see how many skittles Alpha Rex knocks to the floor. The winner is the player who topples the most skittles. Players may want to agree to some game rules. For instance, the robot must not be directly aimed at any skittle at the start of the round. You may also have rules about the minimum distance between skittles, or award more points for knocking over specified skittles.
www.syngress.com
85
This page intentionally left blank
Chapter 9
Sounds Received and Emitted
87
88
Chapter 9 • Sounds Received and Emitted
Introduction The NXT brick can receive sound using a sound sensor, and emit sound using its loudspeaker. First we will look at some of the things that we can do with a received sound. Sound is another way of communicating with a robot from a distance.The microphone in the sound sensor is better at picking up high-pitched signals, such as clapping or whistling, so we will confine ourselves to using this type of signal.
Start and Stop As an illustration of what can be done with a sound signal, the program in Figure 9.1 makes a mobile robot start running upon hearing a sound, and stop running when it hears a second sound. Sometimes when the robot is running it will hear the sound of its own motors and become confused. There are ways of overcoming this problem. Figure 9.1 Making the robot start or stop in response to sound signals such as clapping or whistling.
The program is enclosed in a loop that runs forever, so the mobile robot will continue to rush around the room until long after your hands get tired from clapping. The first block in the loop is a wait block set to respond to sounds of loudness greater than 20. A short single clap should do the trick. The robot moves forward in a straight line. The motor is set to run indefinitely so be ready to clap again at short notice. The general sound level is higher when the motors are running, so the threshold level is set to greater than 50 in the next sound block. You just need to clap louder. The second clap turns the motor off. This is known as a toggle action. Before we return to the beginning of the loop, there is another move block to make the action wait until the sound has died down. This has a double purpose. Firstly, we have to remember that, in most rooms, a sound such as a clap echoes for a fraction of a second. www.syngress.com
Sounds Received and Emitted • Chapter 9
We are used to this so we do not notice it. However, the robot’s microprocessor works so fast that it can mistake the echo for a separate sound. It loses count of the sounds and the program soon gets out of control. The processors will start the motors when we want to stop them and stop them when we want them to start. This consequence of microprocessor speed is one of the things we must always be thinking about when we are programming. A microprocessor system works very fast. The second reason for waiting for the sound to decrease below a certain level is that, although the motors are officially stopped, they still take time to slow down and stop. During that time, the motors may be making enough noise to trigger the first sound block in the loop as it repeats. Therefore, we must have this third sound block to be sure that everything is settled down before returning to the beginning of the loop. There are two modifications you can make to this program to make it easier to run. One thing you can do is make the motors run more slowly by reducing the power to 30 percent. Another thing is to set the steering so that the vehicle runs in a circle instead of straight ahead. This modification is useful when there is limited space for running the robot. This program was written for controlling the drive motors of a mobile robot by clapping, but it can be used for controlling other motors. For example, it can control the motors of the RoboArm. It can also be used to operate the motor of the QuickStart’s grabber.
Start, Stop, and Turn This takes the routine of the previous program a step further. The first five blocks have toggle action and are almost the same as in the previous program. We have an extra block to let echoes die away (see Figure 9.2). Figure 9.2 In this program, clapping or whistling makes the robot stop, start, and change direction. This is the starting and stopping part of the program.
www.syngress.com
89
90
Chapter 9 • Sounds Received and Emitted
The remaining five blocks (see Figure 9.3) wait for the sound to die away and then make the motors spin the robot through 180 degrees. This is done by making motor B run forward and motor C run backwards. Figure 9.3 This is the direction changing parts of the program of Figure 9.2.
One Clap or Two? This is a useful way of communicating with the robot while the program is running. For example, a program may have two main sections, one where it avoids light, and one where it runs towards light. You may want to choose between these two patterns of behavior. You can do this by clapping once or twice. The information that the robot gets from this signal is used later in the program to direct the microprocessors either to the avoidance routine or to the seeking routine. The first three blocks (see Figure 9.4) wait for the first clap, let the echoes die away, and then wait for 1 second before entering the loop to wait for the second clap. While waiting for the second clap, the program runs in the loop, continually sampling the output from the sound sensor. Note that here we are using the sound sensor block, not a wait block as we used before. If there is no sound within the next 2 seconds, the loop ends. If the sound sensor block detects a clap before the 2-second period has elapsed, this is registered by setting the flag variable to True.
www.syngress.com
Sounds Received and Emitted • Chapter 9
Figure 9.4 You can communicate with the robot by clapping once or twice. This part of the program waits for and accepts the first clap and then waits up to two seconds for the second clap.
Upon leaving the loop there are two possibilities. If there’s been a single clap the flag ( flag2) is left set to False. If there’s been two claps, the flag is set to True. If there have not been any claps, the program will still be waiting to enter the routine.You must clap at least once. Figure 9.5 shows one way of handling the output of this routine. It produces one or two tones, depending on whether the flag variable is False or True. The essential point of analyzing the output from this program is to have a switch that is controlled by the value of flag2. Figure 9.5 This is one way of dealing with the output from the program in Figure 9.4. It produces one or two tones depending on whether there were one or two claps.
www.syngress.com
91
92
Chapter 9 • Sounds Received and Emitted
For this program to work, the claps need to be timed accurately, which is equivalent to double-clicking with a mouse.
Playing a Tune (with a Little Dance) This is the first program in which the robot will be producing musical sounds, and occasionally dancing at the same time. The program (see Figures 9.6 and 9.7) is essentially a list of tones to be played together with their durations. There is a sound block for each note. The tones are set by using the piano keyboard in the configuration pane. The duration of the note is usually set to 0.5, 1, or 2 seconds. If you want to have the robot dancing as well, insert a few motor or move blocks among the sound blocks. Figure 9.6 The first half of the routine for playing the “Saints.” Where they are not shown on the diagram the duration of the tones is 0.5 seconds. The program is set out on a zigzag sequence beam so that a long program can be created without requiring an unduly wide page. Programming blocks are placed on the left-to-right segments of the beam. This allows for data wires (if any) to run from outputs to inputs in the usual way. The right-to-left segments have no program blocks.
www.syngress.com
Sounds Received and Emitted • Chapter 9
Figure 9.7 The second half of the routine for playing the “Saints.”
Most tunes comprise a large number of notes, and we usually need to create a block for each note. The programs tend to be long, which is a disadvantage. However, many tunes have repeating phrases and it’s possible to use loops to provide for the repetitions. In our example, the first phrase of four notes is repeated twice. For the full effect, we want the robot to be dancing at the same time as the tune is being played. This is why the motor and move blocks are set not to wait for completion before allowing the tune to continue. In Figures 9.6 and 9.7, switching on motor C alone makes the robot spin or turn to the right. Switching on motor B alone makes it spin or turn to the left. As a result, the robot twist strongly while the tune is playing. Try adding some more elaborate gyrations.
Choreography Programming Alpha Rex to sing and dance nearly always produces amusing performances. Below we outline some ways of achieving this. First of all, you need a melody for Alpha Rex to play. The easy way is to transcribe the tune from a published source such as sheet music or a book of musical scores. When choosing what to play, remember that Alpha Rex can sound only one tone at a time. It is strictly a one-finger virtuoso. Working from the score, pick out the main theme, usually in the treble clef, and ignore most of the remainder. As an example, Figure 9.6 shows a program for playing a few bars of the traditional jazz number, “When the Saints Come Marching In.” The first four notes are repeated, so they are put in a loop that runs twice. The default tone duration is 0.5 seconds, which seems to be about right for quarter notes. Half notes are set to sound for 1.0 seconds.
www.syngress.com
93
94
Chapter 9 • Sounds Received and Emitted
The example has the dance commands inserted at appropriate places in the musical score. Usually the motor block does not wait for completion. The instructions are followed by a series of sound blocks that play the tune to which to dance. The first dance instruction in the program is to run motor C for six revolutions. The robot stays in place rocking from side to side. We call this a “shimmy.” The second dance instruction is to run motor B, which makes it turn left. This is only the beginning of a much longer song and dance routine that you can build from the program snippets listed below.
Song Snippets ■ ■
Sound block to play tones. You can vary pitch, duration, and volume. Sound block set to play sound files. Files that produce suitable sounds include !Beats03, !Beats04, the !Blips, !Click, !Sonar, and !Ticktack. A typical way of obtaining a steady beat is to run a loop containing a sound block playing !Click followed by a 0.5 seconds wait. Something more sophisticated (or should we say syncopated?) is obtained from a loop containing a sound block playing !Beats04. Have fun with the rhythms by running a loop containing three sound blocks playing !Click alternating with waits of 0.2 to 0.6 seconds.
Dance Snippets ■
■
■
■
Walking Run a move lock either continuously or for a few steps, interrupted by standing still or by other dance snippets. The total number of revolutions in every sequence of steps should be a multiple of three. Turning Left Run a motor block for motor B only. The total number of revolutions in every sequence of steps should be a multiple of three. Turning Right Run a motor block for motor C only for 1.5 revolutions, then run B to turn for multiples of three revolutions and finally, run C for 1.5 revolutions. Shimmying Run a motor block for motor C only. The total number of revolutions in every sequence of steps should be a multiple of three.
www.syngress.com
Chapter 10
The Magnetic Compass Sensor
95
96
Chapter 10 • The Magnetic Compass Sensor
Introduction The magnetic compass sensor is great to have if you want to get involved in navigation routines. It provides a magnetic compass bearing accurate to 2 degrees. The manufacturer’s recommend that the sensor be mounted at some distance from sources of electromagnetic interference, such as electric motors. We decided to take it well out the range of the motors by mounting it on top of an upright mast (see Figure 10.1). This seems to have worked well. Figure 10.1 Using a traditional magnetic compass, Daniel marks the working area with a large arrow pointing north. The TriBot mobile robot has a magnetic sensor mounted at the top of a tall mast. This is to keep it away from magnetic fields caused by the motors of the robot. The spectators in the background are Quester and Robo, two home-constructed robots. How to build and program them is described in the author’s book, The Robot Builder’s Cookbook (Elsevier/Newnes, 2007).
The output of the sensor is plugged into input 2 of the brick and we treat the sensor as if it were the ultrasonic sensor when programming. Where the diagrams in this chapter show the ultrasonic icon, it’s really the magnetic compass that we are using. The output from the sensor ranges from zero to 180, representing compass bearings 0 degrees (due magnetic north) to 360 degrees.
www.syngress.com
The Magnetic Compass Sensor • Chapter 10
Heading in the Right Direction This is an essential routine for getting the robot heading in the direction we want it to go. We made it into a my block (see Figure 10.2). It runs in a loop, spinning the robot around until it is facing in the right direction. The first block in the loop looks like the ultrasonic sensor, but is actually the magnetic sensor. There are two variables. Course is the direction in which we want the mobile to face and bearing is the direction in which it is actually facing, as read by the magnetic sensor. Figure 10.2 The routine for the my block setcourse, which turns a mobile robot to face toward a specified compass bearing.
The reading from the magnetic sensor is fed to the bearing variable. Course holds the direction that we want robot to go in. This is set before the routine is called. The math block calculates the difference between course and bearing. The result of this calculation indicates whether the robot is already facing the right direction or has to turn. The idea of limits is important in a routine like this. It is unlikely that we will be able to change the bearing of the robot to make it exactly equal to course. This is because the robot turns through a small but significant angle each time that the loop repeats. Bearing might be slightly less than course before the turn, and then be increased to slightly more than course after the turn. It could have skipped over the “equals” point during the turn. This could go on indefinitely, with the routine never finding the “equals” point. So we have to be satisfied if the robot ends up aimed a few degrees either side of the course that was set.
www.syngress.com
97
98
Chapter 10 • The Magnetic Compass Sensor
In our program, the range block is set for inside the range −5 to +5.You may need to use different settings. Experiment with these before making the my block. The my block needs only the value of course to be set in that variable and the my block is called. The robot will turn to whatever course has been set.
Polygon This is a demonstration of what can be done using the magnetic sensor. The robot follows a path outlining a polygon, running straight ahead on the sides and using the magnetic sensor to turn through the correct angles to complete the polygon. In our version (see Figure 10.3), the robot follows the outline of a decahedron, that is to say, a 10-sided figure, with equal sides and turning through 36 degrees at each corner. Figure 10.3 The polygon program.
The program begins by setting the course variable to specify the direction of the first side of the figure. We set course to 20, but any value in the range zero to 180 is acceptable. Since this is to be a decahedron, the loop is set to 10 iterations. Within the loop, the move block is set to one rotation. With the QuickStart vehicle, this gives it a turning circle of just under 1 meter in diameter.You can make the figure bigger or smaller by adjusting the duration of the move block. The direction of the first side is held in the course variable block and this is fed to the my block. The robot turns until it is facing in the specified direction. The value of course is then fed into the math block where it is incremented by 18, this being equivalent to a turn of 36 degrees. This value is stored back in course, ready for navigating the second side. Now facing the new direction, the robot heads off along the first side of the polygon. The sequence repeats for each repetition of the group and eventually the robot comes to a halt having completed 10 sides. www.syngress.com
The Magnetic Compass Sensor • Chapter 10
Try Something New! This program can be adapted to polygons of the any size and to any number of sides. A two-sided polygon is simply “there and back.” Put your robot on guard duty and have it marching to and fro with a smart about turn at each end of its path. Adapt the program to take the robot on a zigzag path. Add sound effects at appropriate points in the program. You could try fixing a felt marker pen at the rear of the robot. Use a rubber band in the fixing structure, to help keep the pen pressed lightly on the paper. Let the robot draw its figures on sheets of paper. Now you can program the robot to draw all kinds of shapes. The only limit is your imagination.
Circle This takes the previous program a stage further and has the robot performing intricate routines. In the previous program, the motion of the robot was decidedly jerky. This program produces a much smoother action, one more suitable to drawing circles. The program comprises three subprograms operating in parallel. The upper branch (see Figures 10.4 and 10.5) begins with two blocks that turn the robot to face north. This uses the same programming technique as in the polygon program. Next comes a loop, which produces a value of course starting at 0 and gradually increasing by 1 at each repetition of the loop until it reaches 180. Then the program leaves the loop and the power to the motors is switched off.
www.syngress.com
99
100 Chapter 10 • The Magnetic Compass Sensor
Figure 10.4 The top branch of the circle program, first part.
Figure 10.5 The top branch of the circle program, second part.
In some applications, course may not begin at 0. In such cases, it might increase beyond 180, but this is taken care of by the switch block. When course reaches 180, the second compare block detects this and the program runs along the upper branch of the switch block. This restores the value of course to 0, and it is now ready to repeat from 0 upwards. www.syngress.com
The Magnetic Compass Sensor • Chapter 10 101
There are three settings to be made in this branch of the program, as indicated in the diagrams. The first (B = 1) controls the amount by which course is increased at each repetition. Giving this a bigger value will increase the tightness of the turning, therefore decreasing the diameter of the circle. If B is too large, we will produce polygons. The second setting decides when course is to be restored to 0, which will normally be at 180. The third setting decides when the loop will end, which will normally be when course reaches 0.You can experiment by altering some of these values to see what happens. To sum it up, the top branch of the program provides a value for course, which varies in time, and decides the direction in which the robot is heading at any given instant. The middle branch (see Figure 10.6) calculates the direction in which the robot is heading with respect to the compass bearing. It reads the compass, and calculates the difference between the actual direction and the direction in which it should be heading according to the course value. This difference is saved as the variable steer. This is the correction that the robot should make in order to stay on course. Remember that the course is being varied continually, so this routine keeps track of it. Figure 10.6 The middle and lower branches of the circle program.
www.syngress.com
102 Chapter 10 • The Magnetic Compass Sensor
The lower branch of the program switches on the motor to run continuously. While it is running, the steering controls receive input from the steer variable. This may be positive or negative in the range of −100 to +100. It is generally well within this range. It acts in the same way as a person at the helm of a boat, holding the vessel on course. When this program is run, you notice a difference between the jerky motion of the first phase and the smoother motion when the robot is circling. This is because in the circling phase, the motor is switched on continuously, not on and off repeatedly. Summing up the whole program the functions of the branches are: ■
Top Branch Generating a function to control the direction in which the robot moves.
■
Middle Branch Calculating the value of steer needed to keep it on course.
■
Lower Branch Steering the motors.
Try Something New! There is a lot of scope for adding to this program. Alter the size of the circle, or make the robot circle two or more times. Try adding other behaviors to the routine. For example, make the robot stop when it is halfway around the circle (or a quarter of the way round the circle), and perform some other action such as playing a tune. If you have added a felt marker pen to the robot, as described under the polygon program, all kinds of shapes and designs become possible. Try to program the robot to draw an oval, an ellipse, a wavy line, a figure eight, or a spiral.
www.syngress.com
Chapter 11
More Mathematics
103
104 Chapter 11 • More Mathematics
Introduction NXT-G provides the basic mathematical operations, but sometimes we need something more. For example, a navigation routine may need a function that NXT-G does not have. For instance, trigonometry functions are important in navigation, such as finding the quickest way from A to B. This chapter presents some additions to the Mindstorms repertoire.
Floating Point Arithmetic Most of the calculations in programming the NXT robots can be done with integer arithmetic, that is, using whole numbers. Sometimes we need floating point numbers, which are numbers that have a decimal point and digits after it. Some of the action blocks are able to accept floating point numbers. For instance, the motor block can be set to 1.5 revolutions and the sound block can generate a tone that is 0.2 seconds long. The programming built into NXT-G takes care of the floating point calculations in these instances. But the math block works only in integer numbers. If you multiply 27.6 by 3.12, you get 84, not 86.112. If you look back at the block in which you entered 27.6 and 3.12, you find that these values have been rounded to 28 and 3, respectively. The block has converted the original floating point values into integers before multiplying them together. There is a technique for improving this procedure. The first step is to multiply the number by 100 before entering it. For example, set the block to multiply 2760 × 312, and up comes the product, 861120. Because the two numbers were 100 times too big, their product is 100 × 100 times too big. Then divide 86112 by 10000 to get 86.112. Doing this with a math block drops the figures after the decimal point, giving 86. However, this answer is more accurate than the value obtained by using the original numbers without multiplication. This type of working depends on scaling up the numbers, multiplying them if required, and finally scaling down the temporary result to get the true result. This is where we introduce the idea of scale factor. In the example, the scale factor before multiplying is 100. After multiplying, it is 10000. We divide by the 10000 × scale factor to recover the true product, or leave the product scaled up if there are further calculations. Usually scaling down is done last. If it is done to soon in the calculation, you may lose some important significant figures.
www.syngress.com
More Mathematics • Chapter 11 105
There are several rules for using scale factors: 1. When adding or subtracting, both numbers must have the same scale factor. Their sum or difference will have that same scale factor. 2. When multiplying, the numbers need not have the same scale factor. The scale factor of the product is the product of the scale factors of the original numbers. 3. When dividing, the numbers need not have the same scale factor. The scale factor of the quotient is the quotient of the scale factors of the original numbers. If the numbers have equal scale factors, the quotient has a scale factor of 1. Example of rule 1: The two numbers are 7 and 4 and the scale factor is 10. We enter 70 and 40, which adds up to 110. This has the scale factor of 10 so getting back to the original scale we divide by 10 to obtain 11, which is the sum of 7 and 4.
■
Example of rule 2: As before, the two numbers are 7 and 4, and the scale factor is 10. We enter 70 and 40, which when multiplied gives us 2800. This has a scale factor of 10 × 10 that is a 100. To get back to the original scale, we divide 2800 by 100 to obtain 28. This is the product of 7 and 4.
■
Example of rule: The two numbers are 7 and 4 and the scale factor is 10. We enter 70 and 40, which when divided gives 1.75. This will be shortened to 1 by the division operation, which means we lose precision. It would be better to build a rounding routine into the calculation, and the result would be 2. However, we do not need to have the same scale factor for both numbers. We could have a scale factor of 100 for the 7 (enter 700), and a factor of 1 for the 4 (enter 4). The result of the division will be 175, which has all three significant figures, with a scale factor of 100.
■
Calculating Cosines Many useful functions can be calculated by using the standard equations of the math block. An example of this is the cosine function. One way to provide these functions is by setting up look-up tables, but a better way is to calculate the values whenever required.
www.syngress.com
106 Chapter 11 • More Mathematics
This program (see Figure 11.1) relies on the fact that the value of a cosine is the sum of a series of terms. For cos x (expressed in radians) the equation is: cos x = 1 −
x2 x 4 + − ... 2! 4!
Summing the first two terms is precise enough, when you remember all the other possible errors in navigating a robot. Figure 11.1 Program for calculating cosines.
Data wires connections are as listed in the table below. Source
Value held
Destination
Action
Math1
100x
Variable x
Storing 100x
Variable x
100x
Math2 A and B
10000x2
Math2 # output
10000x2
Math3 A
100x2/2!
Math3 # output
100x2
Math4 B
Sum series to give 100 cos x
When this routine has been checked, and if you think that it will be used several times in a program, it is best to convert it into a my block. Given an angle expressed in radians, this routine calculates the cosine. It works for positive or negative angles in the range −0.9 rad to +0.9 rad (−52 degrees to +52 degrees). Precision is lower with the larger angles. Because the routine must operate with integer values (and particularly because division loses the decimal places), the angle is multiplied by 100 before entering the routine. For example, the angle 0.56 rad is entered as 56. The result must be divided by 100. For example, entering 75 gives a result of 73. This means cos 0.75 = 0.73. (A rounding error here; it should be 0.72). www.syngress.com
More Mathematics • Chapter 11 107
To demonstrate the program, type a value for the angle (x) in the first math block. On running, this is stored in the variable x. The math2 block calculates x2 and math3 divides this by 200. This is equivalent to dividing by 2 (= 2!) and by 100, to bring the value down to the × 100 level. This is the value of the second term in the series, x2/2!. Math4 subtracts this from 1 and the final result appears at the output of math4. If you need greater precision, extend the program to calculate x4/24 and add this to the previous result.
Calculating Sines This program (see Figure 11.2) relies on the fact that the value of a sine is the sum of a series. For an angle of x radians: sin x = x −
x 3 x5 + ... 3! 5!
Summing the first two terms is precise enough, when you remember all the other possible errors in navigating a robot. Figure 11.2 Program for calculating sines.
Data wire connections are as in table below: Source
Value held
Destination
Action
Math1
100x
Variable x
Storing 100x
Variable x
100x
Math2 A and B
10000x2
Math2 A output
100x
Math3 A
Finds 1000000x3
Math2 # output
10000x2
Math3 B Continued
www.syngress.com
108 Chapter 11 • More Mathematics
Source
Value held
Destination
Action
Math3 # output
1000000x3
Math4 A
Finds 100x3/3!
Math4 # output
100x3/3!
Math5 A
Variable x
100x
Math5 B
Sums series to give 100 sin x
When this routine has been checked, and if you think that it will be used several times in a program, it is best to convert it into a my block. Given an angle expressed in radians, this routine calculates the sine. It works for positive or negative angles in the range −1.2 rad to +1.2 rad (−52 degrees to +52 degrees). Because the routine must operate with integer values (and particularly because division loses the decimal places) the angle is multiplied by 100 before entering the routine. For example, the angle 0.56 rad is entered as 56. The result must be divided by 100. For example, entering 75 gives a result of 68. This means sine 0.75 = 0.68. To demonstrate the program, type a 100 times scaled value for the angle (x) in the first math block. On running, this is stored in the variable x. The second math block calculates x2. Then math multiplies this by x, to give x3. Math4 divides this by 60000. This is equivalent to dividing by 6 (= 3!) and by 10000, to bring the value down to the × 100 level. This is the value of the second term in the series, x3/3!. All that remains to evaluate the series is to subtract 100x3/3! from x. The final result appears at the output of math5. If you need greater precision, extend the program to calculate x5/120 and add this to the previous result.
Square Root Given the number n stored in a variable called numbern, this program (see Figures 11.3 and 11.4) calculates the square root of n and puts it into a variable xk.
www.syngress.com
More Mathematics • Chapter 11 109
Figure 11.3 The first part of the square root program.
Figure 11.4 The second part of the square root program.
Data wires are as follows: Enter n to n. From n to 100n. 100n to 100n/xk A. Xk to 100n/xk B. 100n/xk to /2 to new xk. This program is based on what is known as the Newtonian iteration. An iteration is an equation with which you calculate the value of a number and then put the calculated value back into the equation and perform the calculation again. Keep on doing this over and over again until the result of one iteration is equal to the result obtained in the previous iteration. Then you know you have the most exact answer possible.
www.syngress.com
110 Chapter 11 • More Mathematics
The equation for the iteration is: xk +1 =
1 ( xk + n / xk ) 2
The initial (k = 0) value of x0 is 1. Then suppose we want to find the square root of 5. At the first iteration xk equals 1 and n equals 5, the value of expression is: x1 =
1 5 1 1+ = × 6 = 3 2 1 2
This result is obviously too big but try putting the 3 into the equation: x 2 = 1/ 2(3 + 5 / 3) =
1 × 4.67 = 2.33 2
This gives you almost the right answer, which is 2.24. For the next iteration, x3 is equal to 2.23 and the next iteration after that gives x4 = 2.24. This is the result you get using two significant figures, using a calculator. If you want greater precision, try some more iterations. Usually four iterations are good enough. This is used for navigation routines when we employ trigonometry functions to work out the position of a robot. To use it in these routines, it is best converted into a my block. Include all the stages shown in Figure 11.4, except for the last two blocks.
Factorials Sometimes in an equation we come across an expression such as “4!.” The exclamation mark is used to indicate that the value is not simply 4, but “factorial 4.” Factorial 4 is the result of calculating: 1×2×3×4 Its value is 24. Similarly, factorial 7, or 7! is: 1×2×3×4×5×6×7 Its value is 5040. Factorial numbers soon reach very large values. At the other end of the scale, 2! = 2 and 1! = 1. Surprisingly, 0! also equals 1, but we will not go into that here.
www.syngress.com
More Mathematics • Chapter 11 111
Figure 11.5 The first part of the factorial program.
Figure 11.6 The second part of the factorial program.
There is a large number of data wires in this program (see Figures 11.5 and 11.6): Source
Value held
Destination
Action
Math1
x
Argument1
Set input
Math2
1
Factorial1
Set Factorial = 1
Loop counter
Count
Math3 A
Number of repetitions + 1 Continued
www.syngress.com
112 Chapter 11 • More Mathematics
Source
Value held
Destination
Action
Factorial2
Accumulated count
Math4 B
New product
Math3
Accumulated current product
Math4 A
Math4
New product
Factorial 3
Store accumulating product
Argument2
x
Math5
x–1
Math5
x–1
Compare A
Equal?
Factorial2
Accumulated count
Compare B
Compare
Equal?
Loop exit
Ends looping
Factorial4
x!
dispResult
Display x!
Prior to running this routine, the number to be factorialized is stored in a variable block named Argument. It may have any integer value in the range 1 to 12. The routine calculates the factorial of Argument and stores it in the Factorial variable block. The routine works as follows. The first two blocks set Argument to x. The next two blocks set Factorial to 1, the initial value of x!. In the loop, the first four blocks generate x!, step-by-step. For the first run, count is 0. Math3 adds 1 to count (making it 1). Math4 multiplies count by Factorial giving 1 × 1 = 1. This is stored in Factorial. The last three blocks in the loop determine when the calculation is to end. Argument has 1 subtracted from it by Math5 and is then compared with count. If they are equal, the loop ends and we leave the loop with Factorial equal to 1. This is the result required for 1!. If they are not equal, the loop begins again. Factorial is still 1 but now count is 1. Math3 produces 2 and Math4 calculates 1 × 2 = 2. This is stored in Factorial. If Argument is 2, it is reduced to 1 and is equal to count, so the loop ends with Factorial holding 2! However, if Argument is 3, the loop runs again with count = 2 and Factorial = 2. Math3 gives 3 and Math4 calculates 2 ×3 = 6. If Argument is 3, then reduced to 2, it equals count. The loop ends with Factorial t = 3!.
www.syngress.com
More Mathematics • Chapter 11 113
If Argument is greater than 3, the loop continues, generating 4!, 5!, and so on. The program works for all values of x up to 12. After this, the numbers become too large for the NXT to handle. Factorial are used in the calculation of odds, especially in games or games-related artificial intelligence (AI) programs. They are also used as subroutines in programs of combinations and permutations.
Combinations Given n objects, in how many different ways can we select r objects? This program (see Figure 11.7) performs the calculation. For example, given ten CDs, in how many ways may we select three of these to play at a party? If n = 10 and r = 3, the number of ways is: nCr =
n! r!(n − r )!
which gives: nCr =
3628800 = 120 6 × 5040
There are 120 ways of making the selection. Figure 11.7 This program calculates the number of combinations of n objects taken r at a time.
www.syngress.com
114 Chapter 11 • More Mathematics
The Factorial! my block takes a number from Argument and the result appears in Factorial. Nine data wires are needed, as listed in this table: Sources
Value held
Destination
Action
Math1
n
Argument1
Sends n to Factorial
Math2
r
Argument2
Sends r to Factorial
Factorial!1
n!
Math3 A
Calculates n!/r!
Factorial!2
r!
Math3 B
Math1
n
Math4 A
Math2
r
Math4 B
Math4
n–r
Argument3
Sends (n – r)! To Factorial
Math3
n!/r!
Math5 A
Calculates nCr
Factorial!3
(n – r)!
Math5 B
Calculates n – r
Given n and r as input, these values are, in turn, put into variable Argument. Each time, Argument provides input to the my block Factorial!, which passes its output to a variable Factorial. In this way the top row calculates n! and r!. Math4 takes n and r and calculates (n – r). The factorial of this is then calculated by Argument3, Factorial!, and Factorial3. Math3 divides n! by r!, and Math5 divides this by (n – r)! to give the final result, nCr. The combination function is used in games to calculate the chance of success.
X modulo Y This math function is usually written “x mod y” or “x%y.” Its value for two integers x and y is the remainder obtained when x is divided by y. For example, if x = 23 and y = 4, then x/y = 4, remainder 3. This makes x mod y equal to 3. This calculation is performed by the program shown in Figure 11.8.
www.syngress.com
More Mathematics • Chapter 11 115
Data wires are as follows: Source
Value held
Destination
Action
Math1
x
Math3 A
Math2
y
Math3 B
x / y quotient, ignore remainder
Math3
x / y
Math4 A
Multiply quotient by y
Math2 (via Math3 B)
y
Math4 B
Math1 (via Math3 A)
x
Math5 A
Math4
Multiplied quotient
Math5 B
Subtract, giving x mod y
Math5
x mod y
Dispresult
Display result
Where the source is via another block, the data wire begins from the terminal on the right-hand side of the data hub. The data is relayed from the original source. Figure 11.8 The basic program for calculating x mod y.
The values of x and y are entered into math1 and math2. As an example, suppose that x = 20 and y = 3. The division (x/y) is performed by math3, but the remainder is lost, so the result is 6. Math4 multiplies this by y to obtain 18. Math5 subtracts this from x, giving 2 which is the value of x mod y.
www.syngress.com
116 Chapter 11 • More Mathematics
Modulo Counting This program (see Figures 11.9 and 11.10) applies the modulo function to a counting sequence. Figure 11.9 Program for generating a modulo counting series.
Figure 11.10 Displaying the output from the program of Figure 11.9.
www.syngress.com
More Mathematics • Chapter 11 117
The way this works is different from that of the program described above. It is driven by the counter of the loop that surrounds the whole program. The sequence of values of x (counter output) is: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 … Within the loop the first block is a variable called offset with an initial value of 0. This is added to the value of count, and the result is sent to modulo. For the first four counts, modulo holds the values: 0, 1, 2, 3. At that stage, the compare block, which is set to 3, gives a True output because its input is also equal to 3. This sends the program running along the upper line of the switch, where offset is reduced by 4. This means that the value stored in offset is now –4. For the next four counts: 4, 5, 6, 7. each is reduced by −4 so that modulo takes the values: 0, 1, 2, 3. The complete series so far is: 0, 1, 2, 3, 0, 1, 2, 3. This is beginning to look like a modulo counting series, and so it is. Because the last term is 3, the compare block sends the program along the upper branch, where offset is further reduced to –8. The next count is 8, which is now reduced to 0 again, and so the sequence continues with offset being reduced by four every fourth count. The program counts indefinitely: 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3,… which makes this a x mod y counter. When setting up the program load the value of y into modulo. Load y + 1 into the math block inside the switch block. As a my block, this routine is adapted to scan the NXT buttons.
www.syngress.com
This page intentionally left blank
Chapter 12
Navigation
119
120 Chapter 12 • Navigation
Introduction One of the problems with mobile robots is knowing where they are. This chapter explains some of the problems and offers some solutions.
Distance Traveled The calculations in this section apply to mobile robots with two independently powered motors, such as the Quickstart robot and the Tribot. If the wheels and tires that came with your LEGO Mindstorms kit are the same size as those supplied with our kit, the outer diameter of the tire is 55 millimeters. This is the basic dimension for the calculations. If the wheels on your robot are larger or smaller than this, adjust the calculations to keep things in proportion. Figure 12.1 shows a wheel running on a flat surface. The mark on the wheel is in contact with point A on the surface. Imagine the wheel running along to the right until the mark meets the surface again, at point B. The distance from A to B is equal to the circumference of the tire. If d is the diameter, the circumference C is calculated like this: C = πd
Where π is pi, with a constant value of 3.14 (to 2 decimal places). In the case of our robot: C = 3.14 × 55 = 173 mm
So, if the robot is running straight ahead and does not slip, one rotation of the wheel takes it forward by 173 millimeters. Figure 12.1 Calculating distance traveled.
Another rotation will take it another 173 millimeters, for a total of 346 millimeters, and so on, in proportion. We summarize some useful distances in this table: www.syngress.com
Navigation • Chapter 12 121
Rotations
Distance travelled (mm)
0.5
86.5
1
173
1.5
259.5
2
346
2.5
423.5
3
519
4
692
5
865
6
1038 or 1.038 m
Another useful table works the other way around. It shows how many rotations will make the robot travel a given distance. Distance travelled (mm)
Rotations
Degrees
50
0.29
104
100
0.58
208
150
0.87
312
200
1.16
416
300
1.73
624
400
2.31
832
500
2.90
1041
1000 (1 m)
5.78
2081
This table has an extra column, which gives the number of degrees through which the wheels turn. This is easily obtained by multiplying the number of rotations by 360. The third table (below) is the equivalent to the first table but, instead of rotations, it lists convenient numbers of degrees.
www.syngress.com
122 Chapter 12 • Navigation
Degrees of turn
Distance travelled (mm)
50
44
100
87
200
175
300
262
400
349
500
437
1000
873
Incidentally, the formula for converting degrees to distance is: C = πd/360 = d × π/360 = d × 0.873
Magnetic Compass This sensor is one of the most useful ones for navigation, as demonstrated in Chapter 8. It is possible to program a complex course for the robot and expect to have it followed with reasonable accuracy. The only problem might be that local magnetic fields will affect the precision of the in-built compass. Avoid running the robot on a surface supported by a cast-iron framework.
Edge Follower 1 This very simple routine gives your robot a rather strange gait, but it gets there eventually and is very economical on programming space. The line on the floor is usually painted black. However, you can also cut out strips of black card and stick them to the floor, or use adhesive tape. But remember that some types of black card reflect infrared radiation and so appear to the sensor to be white. So check the card carefully. Many of the programs in this book assume that the line is white on a dark background. If so, the programs can easily be adapted. The robot has a light sensor mounted with its sensor end pointing downwards about 1 centimeter above the surface (see Figures 12.2 to 12.5). The edge to be followed is painted on the surface in a contrasting shade, usually white on black or black on white. The edge can be a line about 2 centimeters wide or the edge of a larger area. www.syngress.com
Navigation • Chapter 12 123
Figure 12.2 This mobile robot with the light sensor mounted at the front pointing downward is ready to follow the line or an edge.
Figure 12.3 A closer view showing how the sensor is mounted.
www.syngress.com
124 Chapter 12 • Navigation
Figure 12.4 One way of mounting the light sensor.
Figure 12.5 Another close up view of the light sensor on the front of the vehicle.
When the program (see Figure 12.6) is run, the robot moves forward turning slightly to the left or right. If the sensor is more or less over the line, it spins the robot www.syngress.com
Navigation • Chapter 12 125
to take it off the line. If the sensor is off the line, it spins the robot to bring it on again. In this way, the robot pursues a rather wobbly course, roughly keeping to the line. Figure 12.6 A simple edge following routine.
The routine is controlled by a switch block that is programmed to switch at a preset light level. Below 50, the robot is spun to the right. If the level is above 50, the robot is spun to the left. After spinning left or right, the robot runs forward a short distance and then the routine is repeated. As a result of these opposing responses, the robot follows the right-hand edge of the line. It can also follow around the edge of a much larger area. Swapping the spinning blocks makes the robot follow along the left-hand side of the line. Alternatively, it follows the left-hand edge of a white line drawn on a dark background. There are many obvious applications for this routine, but you may find that some of the other line-following routines give better results.
No-go Response to a Line There’s more than one way to think about the line. Often it is a path to be followed, but sometimes it is a barrier. In this program (see Figure 12.7), it is a barrier. When it reaches the line, the robot backs away, turns through a small angle, and then heads off in a different direction. www.syngress.com
126 Chapter 12 • Navigation
The line on the floor is usually painted black. You can also cut out strips of black card and stick them to the floor, or use adhesive tape. But remember that some types of black card reflect infrared radiation and so appear to the sensor to be white. Check the card carefully before you use it. Figure 12.7 This program prevents the robot from crossing a line.
An area of floor is marked off by drawing a wide line around it. The robot is placed somewhere in this area. The robot runs forward. When it comes to the line it is not able to cross it. Instead, it stops, spins through a small angle, and then continues forward. It continues to wander in the marked off area. The entire program is enclosed in a loop, which is set to run indefinitely. The move block is set to make the robot run forward. After the motor has run for 30 degrees, it stops to allow the sensor to detect reflected light. If light is detected, the switch block takes the action directly to the end of the main loop. The move block then repeats the forward motion. The effect is that the robot moves forward in a series of small steps repeated so rapidly that it appears to be moving continuously. www.syngress.com
Navigation • Chapter 12 127
If no reflected light is detected (because the sensor is above a line), the program runs along the lower beam. It backs the robot a short distance and then (in this version of the program) there is a random block. This controls the next switch block. The random block generates either 0 or 1. If it is 0, the next move block spins the robot to the left. If it is 1, it spins to the right. The random choice of spinning direction gives the robot the appearance of being alive and unpredictable. It may even help get it out of difficult corners. But this part of the program is optional; you can omit the random block and the associated Switch block. Put in a single move block to spin the robot either left or right. This makes the program shorter but not as interesting. It is fun to draw the line with two or three gaps in it. The robot will wander in the area but eventually it will escape through one or other of the gaps. Take bets on which gap it will go through!
Steering Alpha Rex Several programs in this chapter are geared toward Alpha Rex, which has legs instead of wheels. Before we go on to describe these programs, we need to look at how to program Alpha Rex to walk, turn left, and turn right. Legs are more complicated than wheels, both to construct and to program. Wheels are much easier, which is the reason why most mobile robots are wheeled, like Tribot. They have two motors, both of which are used to propel the robot. We steer the robot by making the motors turn at different rates. In contrast, Alpha Rex uses only one motor (motor B) for propulsion. This motor swings the two legs backward and forward—left, right, left right and so on—marching steadily to its destination. The second motor used for walking (motor C) has an entirely different job to do. It swings the legs sideways so that the body of the robot is brought directly above the left foot or the right foot, alternately. The walking mechanism of Alpha Rex links the actions of the two motors so that the body weight is above the foot that is moving backward at that time. The foot grips the surface, without slipping, and propels the robot forward. Slipping of the backward moving foot is prevented by the L-shaped lever, which has a soft plastic tip. This tip slips easily over the surface as the foot moves forward. There is sufficient pressure on the foot to make the lever grip the surface as the foot moves backward. The function of motor C is to shift the body weight in time with the foot motion, but this happens only if the gear wheels are set up exactly as shown in diagram 46 of the building instructions. After checking that the gears are correctly www.syngress.com
128 Chapter 12 • Navigation
positioned, it is also essential to manually turn the weight-shifting mechanism on the right side of the robot as in diagram 47, so that it is correctly synchronized with the walking mechanism. If set up as described above, the robot walks forward in a straight line. Programming is simple. We use a single move block to run motors B and C simultaneously. To make the robot turn to the right, run motor B on its own. Use a single motor block set to run motor B for a given number of rotations. Make sure that the weight is definitely over one foot or the other. For example, the previous normal walking session may have ended with the left foot moving backward and the weight on that left foot. If we now run motor B only, its first step gets it nowhere because the right foot is supposed to move backward and grip the surface. But motor C is not running so the weight is still over the left foot (see Figure 12.8). The right foot slips. Figure 12.8 Turning right with the weight of the robot over the left foot.
On the subsequent steps, with motor B still running, only the left foot grips and propels. The right foot does nothing. The robot turns to the right. One very important point is that, if we run motor B on its own, the walking and weight-shifting mechanisms must still be correctly synchronized when the robot
www.syngress.com
Navigation • Chapter 12 129
resumes normal walking. To ensure this, we always program motor B so that the robot takes an integral number of double steps (left-right or right-left). In other words, the large gear wheels turn an integral number of rotations. The large gear has 24 teeth, and the small gear on the motor shaft has 8 teeth. The ratio 8:24 equals 1:3. For this reason, the number of rotations of the motors must be a multiple of three. If you keep to three or its multiples, the robot will always start walking or turning by moving the same foot. If you program other numbers of rotations, B and C will get out of sync, resulting in erratic motion of the robot. The motors will also lose sync if the program is interrupted by pressing the grey NXT button. Always allow a program to run to its end. If the robot is walking straight ahead or turning left and you want to make it turn right instead, use the changestep routine. This is a motor block set for motor C to run on its own for 1.5 rotations. Using this once makes the robot lean the other way (see Figure 12.9). Now running motor B on its own moves the robot forward as before, but turning on the other foot. Use changestep again when you want it to resume walking ahead to turn left. Figure 12.9 A short burst of power on motor C has put the weight of the robot on the right foot and it turns left.
www.syngress.com
130 Chapter 12 • Navigation
Surfaces for walkers The rate of progress of Alpha Rex depends a lot on the type of surface. It needs to be fairly rough to provide sufficient friction. The robot will also walk on smooth surfaces such as glazed tiles, timber flooring, and plastic-surfaced table tops, though on some of these it’s “two steps forward and one step backward.” The best surface we have found is hardboard, from the DIY store. It usually comes in sheets 1 meter × 1.5 meters, or 1 meter × 2 meters. Plenty of room for most robotic maneuverings. Turn it over and use the reverse side. In all the hardboard we have seen, this surface is imprinted with a weave pattern, which supplies just the right amount of “bite” to stop the robot’s feet from slipping on the backward strokes. Hardboard is dark brown, so markings on the board must be light, preferably white. The DIY store can also supply you with a reel of painter’s masking tape, which is white, and the adhesive grips very well on the rough reverse surface of hardboard. The tape remains firmly in place, yet is easily peeled off if you want to alter the pathway.
Figure 12.10 Laura is assembling Alpha Rex, ready for running the edge following routines.
www.syngress.com
Navigation • Chapter 12 131
Marching Orders This short demonstration program (see Figures 12.11 and 12.12) puts Alpha Rex through its paces. It will help you understand how the robot gets around.
Figure 12.11 Checking the edge following routine by running the robot along the edge of a zigzag path.
Figure 12.12 The program for marching orders is a sequence of motor blocks.
The robot walks forward, steers to the left, resumes walking forward, changes foot, steers to the right, and finally walks forward.
www.syngress.com
132 Chapter 12 • Navigation
The table below represents the sequence of this program:
Action Motor B Motor C Drive
Walk L R L R
L L
R R
Turn left L R L R R R
R R
Walk L R L R
L L
R R
Turn right L R L L L L
R L
Walk L R L R
L L
R R
Change foot
The table shows two left-right steps at each stage (6 revolutions), but the program has eight steps (24 revolutions) to make it easier to observe what is happening. The motor B row shows which foot is moving backward. The motor C row shows which way the robot is leaning. After normal walking, with forward motion (dark grey) on all steps, motor C is switched off (light grey). This leaves the robot leaning right and consequently it turns left. When C is turned on again, it is still in phase with B and normal walking is resumed. To turn right, C is left on for 1.5 revolutions while B is off. This puts C out of phase with B. Then C is off (light grey) while B comes on again. The change of phase (or foot) results in the robot turning right. To get back to walking we have to put C in phase with B again. We turn C on for 1.5 revolutions before switching on B and C to resume walking.
Rex On Line The robot walks straight ahead until it comes to an area or line that is lighter in tone than its normal walking surface. The amount of light being reflected from the surface is detected by the light sensor. The light sensor is mounted on the right foot, pointing downwards, and about 5 millimeters from the surface (see Figure 12.13).
www.syngress.com
Navigation • Chapter 12 133
Figure 12.13 Much of the testing of the edge-following routine was done with a headless, armless version of Alpha Rex. This made it easier to open the battery box to replace the cells. In this photo the robot has a light sensor mounted on the toe of the right foot.
The program (see Figure 12.14) has the following data wires: Light sensor block to variable intensity. Inside the loop: from the intensity output of the light sensor block to input B of the compare block. From the intensity variable to input A of the compare block. From the compare block to the input of the switch. Figure 12.14 The program for Rex on line.
www.syngress.com
134 Chapter 12 • Navigation
The robot is placed with the light sensor halfway over a small white square of tape stuck on the dark walking surface. In the first stage of the program, before the robot starts to move, the light sensor sets the trigger level to the light intensity it is currently receiving, which is halfway between dark and light. Then the robot walks forward on the dark background but, as soon as it comes to a light area or strip, it turns to the right. It continues to turn until it is once more on the dark background. Then it resumes walking forward. The halfway light intensity is stored in the intensity variable. Within the loop the light intensity is read by the sensor and compared with the stored value. If it is less, the switch block runs through the lower branch and the robot walks straight ahead. If it is greater, the block on the upper branch makes the robot turn. After a single left-right step, the routine repeats. The loop is set to a maximum count of 20. This is for testing purposes, so that you do not have to wait too long for the loop to finish, and do not need to press the grey button. This ensures that the robot will take an integral number of steps and its motors will not get out of sync. In your application, you may need to take other precautions to avoid loss of sync. To use this routine with dark markings on a light background, simply alter the compare block to “greater than.”
Rex On Edge This program (see Figures 12.15 to 12.17) could be described as a line-following routine, but in practice the robot is following along the edge of a line. Similarly, it will follow around the edge of a wider area of any shape.
www.syngress.com
Navigation • Chapter 12 135
Figures 12.15 to 12.17 The program for Rex on edge.
www.syngress.com
136 Chapter 12 • Navigation
This program is written for use on a dark brown hardboard surface with a line made from masking tape. For Alpha Rex it is about four strips wide. Data wires are as follows: ■ ■
■
In Figure 12.15: Light sensor to intensity variable. In Figure 12.16: Light sensor block to math block B. Intensity variable to math block A. Math block to end of the loop. Repeat this for both branches of the switch. In Figure 12.17: Direction variable to compare block A. Compare block output to exit of main loop.
To start with, the robot is placed on the edge of the line with the line to its left and facing diagonally away from the edge. When the program is run, the robot follows a zigzag course, continually crossing and re-crossing the edge of the line. This is a self-calibrating program. In the preliminary phase, the program sets the trigger level to the light intensity it is currently receiving, which is halfway between dark and light. The direction variable is set to True, ready to make the robot turn left the first time through the main part of the program. The block takes it two steps forward (3 rotations), to take it clear of the line. It then enters the main loop, which is set for ten iterations, a suitable number for testing purposes. You can increase the number later for running further. The motor block inside the loop makes the robot walk two more places and then the direction variable determines whether it is to turn right or left. If it is to go right (direction is True) the robot says “Right” and enters the upper branch of the switch. This contains a loop that makes the robot take one step turning to the right. This is followed by a sensor block, which is looking for low light intensity, because it is turning right, away from the line. The loop repeats, turning the robot to the right until it is clear of the edge and the sensor is above the dark background. In the math block, A is greater than B. The reverse happens if the robot is set to turn left. It turns left until A is less than B. On leaving the switch block, the direction variable is changed to its opposite state. This is done by reading it into the logic block, where the NOT operation inverts the current state and feeds it back to the direction variable.
www.syngress.com
Navigation • Chapter 12 137
If the robot comes to the end of the line, it runs around the end and then back along the opposite edge of the line. The program can be adapted to run with the line on the right instead of the left. It can also be adapted to run on a light background of dark markings.
Pathfinder Alpha Rex needs two light sensors for this program. This leaves only one input for a third sensor, but in most applications, such as maze running, a third sensor is not needed. The program consists of three nested switch blocks, running inside a continuous loop. Figure 12.18 shows the run up to the first switch block. The lower branch continues to the right with no more action blocks on it. Figure 12.19 shows the upper branch, which branches again twice. Figures 12.18 and 12.19 Pathfinder program, which uses two light sensors to follow the path and to locate the station where the robot is programmed to perform special actions.
www.syngress.com
138 Chapter 12 • Navigation
Figures 12.18 and 12.19 Continued.
The robot normally follows along the line with its sensors on either side of the line (See Figure 12.21). If the surface is dark, both sensors register darkness. When the robot veers towards one edge of the line, the left or right sensor detects it. The response is to turn the sensor away from the line so as to bring the robot back into position with the sensors on either side of the line. In this way, Alpha Rex pursues a slightly zigzag course along the line. The routine has an optional feature. A line drawn across the main pathway line can be used as a stopping point or station. At this point, the robot can be programmed to do a variety of things, including deciding whether to turn left or right at the next junction. In this example, we make the robot stop for 5 seconds and say “Hello,” before continuing along the path.
www.syngress.com
Navigation • Chapter 12 139
We use the logical outputs from the sensors. The outputs are True when the intensity is greater than 50. The outputs are read into two variable blocks: rightflag and leftflag. The variables are first ORed together by the outermost switch block. Assuming that the line is light on a dark surface, and that the robot is running with the line nicely between the sensors, neither sensor detects light and the result of the OR operation is False. The program continues along the lower branch, in which both motors run for 6 revolutions and the robot charges straight ahead. Figure 12.20 A flowchart of the part of the program that interprets the input from the two light sensors.
www.syngress.com
140 Chapter 12 • Navigation
If one or the other or both sensors detect light, some other action must be taken. The upper branch (see Figure 12.18) subjects the variables to the exclusive-OR operation. Figure 12.19 shows what happens at the next switch block. If the result is False (both light), the robot is at a station. It stops and does something special. In this example, the lower branch of the second switch block stops the motors, pauses for five seconds, and says “Hello.” It then sends the robot ahead a short distance to get clear of the cross strip before returning to beginning of the loop. You may decide not to implement this option and not draw lines across the main path.
Exclusive-OR operation Ex-OR has two inputs. The result is True if either one is True, but not if both of the inputs are True. This is its truth table: Input B (rightflag)
Input A (leftflag)
Output
Condition
False
False
False
False True
True False
True True
True
True
False
Centered (already detected by first switch block, so not applicable in second) Veering left or right. Third switch block determines which. At a station
Ex-OR is often called the “same or different” operator. Its output is True when the inputs are different; it is False when they are the same.
www.syngress.com
Navigation • Chapter 12 141
Figure 12.21 The four different possible combinations of input from the sensors.
The third switch block tests rightflag. If it is False, the program follows the lower branch because leftflag must be True. The robot turns to the left. If rightflag is True, the robot turns right. You may decide to simplify this to a basic path follower by not placing crossstrips and omitting the stop block and following blocks. However, it might be wise to retain the stop block. If the robot loses its way and tries to cross the path at right angles, both sensors will register light and the motors will be stopped. This prevents it from getting into worse difficulties. Similar but opposite logic is used when the path is a light color on a dark surface. It is fun watching the robot negotiating a curved path (see Figure 12.22), especially if the path forms a loop with stations at intervals along it. This routine is the basis of maze-solving programs. www.syngress.com
142 Chapter 12 • Navigation
Figure 12.22 Running the Pathfinder program, the robot prepares to negotiate a sharp curve, which it did successfully.
Cosine Rule This is a program (see Figure 12.23) for enthusiasts who want to explore what can be done with NXT-G programming in the absence of floating point arithmetic. The program tackles the problem of how to find the third side of a triangle, given two other sides and one angle. The given angle is the one between the two known sides, in other words the included angle. Figure 12.23 Given two sides of a triangle and the angle between them, this program calculates the length of the third side. This is an example of how to solve a navigational problem by using math.
www.syngress.com
Navigation • Chapter 12 143
There are so many data wires that the diagram cannot show them clearly. The values listed beside each math block indicate which quantities are inputs to the block and which are outputs. The description will guide you in making the connections. Figure 12.24 shows the situation. We are given the two sides b and c, and the included angle A. From this information we can calculate the length of the side using the cosine rule: a = b2 + c 2 − 2bc cos A
Having found a, we use the rule equation in its other form to find the size of angle C: a2 + b2 − c 2 C = cos −1 2ab
Figure 12.24 The path taken by the robot along two sides of a triangle. To find the third side, apply the program of Figure 12.23.
These two equations enable us to calculate the distance a of point B from point C and also the direction of point B from point C. For example, a mobile robot starts at point B, and runs a distance c (110 centimeters) to point A. It spins to head in a different direction. Angle A is the angle between sides b and c, which is 0.94 radians, but the actual angle of spin of the robot is π – A anticlockwise. It then runs a distance b (80 centimeters) to point C. How far is it from its starting point B? In what direction is point B from point C? This is a typical navigation problem.
www.syngress.com
144 Chapter 12 • Navigation
Distances Distances can be measured in any convenient unit (centimeters, inches, rotations of the motors, steps of Alpha Rex). In this example, we are working in tens of centimeters.
Angles The angle between the two sides must be measured in radians, not degrees. Use the table below to convert degrees into radians, noting that the maximum angle for acceptable precision is about 1.1 radians (or 63 degrees), which has a 10 percent error. Because we can’t operate with floating point numbers, we multiply the number of radians by 10, the scale factor for this program. Radians
Radians x scale factor (10)
Degrees
0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8
1 2 3 4 5 6 7 8
6 12 17 23 29 34 40 46 Continued
www.syngress.com
Navigation • Chapter 12 145
Radians
Radians x scale factor (10)
Degrees
0.9 1.0 1.1
9 10 11
52 57 63
Substituting these values of b, c, and cos A into the equation above gives: a = 1102 + 802 − 2 × 110 × 80 × 0.59 a = 8120 = 90
The robot has traveled a distance of 90 centimeters from its starting point. Working this out using integral arithmetic seems to present no problems except for calculating cos A. We could use the cosine program, but it is easier to use a simplified equation, including only the first two terms of the series, even though it may not be as precise: 2 cos A = 1 − A 2
The robot system has several in-built errors, for instance, wheels slipping on the surface, varying battery voltage, and other factors. The approximation to cosine is close enough and is much easier to work with when we need to convert cosines into angles. On a calculator, with A = 0.94 rad, we find cos A = 0.5898. In our example, the approximation makes cos A = 0.56, which is close enough. Summarizing so far: 1 Begin with b, c, and A. 2 Use the cosine rule to calculate side a. This includes using the simplified cosine equation to find the value of cos A. The third and final stage is to calculate angle C. cos C =
a2 + b2 − c 2 2ab
C = 2(1 − cos C )
www.syngress.com
146 Chapter 12 • Navigation
Substituting values: cos C =
8100 + 6400 − 12100 2400 = = 0.1667 2 × 90 × 80 14400
C = 1.4 rad (using a calculator) or 1.3 rad (using the approximation). This equals 80 degrees or 74 degrees. Using the approximate angle takes the robot back to a point 10 centimeters from its start. This is a reasonable result, given the inevitable mechanical imprecision’s of robot navigation. Although the program is long, each stage is very simple. We only have to keep a clear head and work through from stage to stage. In Figure 12.23, the action of each math block is given beside it. The value of the scale factor is given at each stage. To use the program, we enter b, c, and 10 times the angle A. We need to enter 10 times the angle because, as the table shows, A is reckoned in tenths of a radian. Each of these values is then transferred to a variable. Each of the variable values is multiplied by itself to give their squares. All this takes place on the top row of the diagram. On the bottom row, we multiply b by c, and then multiply this product by 2. The next step is to take 100 A2 from the top row, and divide it by 2. Taking this away from 1 gives 100 cos A. The remainder of the calculation is done in a similar fashion and the final result is loaded into a variable, numbern. This is the holding variable for the values that are to be entered into the my block. The my block calculates the square root of A2, which appears in variable xk and is displayed by dispresult. The last two stages are for demonstration purposes only and can be omitted. We now have the length of side a, which is the distance from point B. If this is all we need to know, we can stop here. To continue and calculate angle C, we need further lines of program. These can be written as a separate program or added to the one in the figure. The composition of this program is left to the reader as a programming exercise. If this routine is to be used more than once in a program, it is better to convert it into a my block. It is interesting to test the accuracy of the routine by programming the robot to run from B to A, a random distance, turn through random angle A, run a random distance to point C, calculate a and angle C, and return to point B, facing in its original direction.
www.syngress.com
Chapter 13
Games Robots Play
147
148 Chapter 13 • Games Robots Play
Introduction All the robots in the Mindstorms kit can be adapted in some way or other to play a game against a human opponent, or to play games against themselves. We may need to adapt the rules and mechanics of the game to the robot as well. The programs in this chapter are written with one particular robot in mind, but it is not too difficult to adapt them to a different robot. Most of the programs are full-length games programs, and there are a few shorter programs that you may find useful when designing games of your own.
Maze Runner—Version 1 Taking the programming of Pathfinder a stage further, this program controls a robot as it runs a maze. The maze consists of a path that branches repeatedly into two, as shown in Figure 13.1. It is made up of T-shaped segments. The stem of the T, which may be straight or curved, makes up the main path. The crossbar of the T acts as a station where the robot stops while it makes up its mind whether to go straight ahead or turn left. In this program the choice is random. Figure 13.1 This maze is made from T-shaped segments. The robot moves along the stem of a tee and stops when it comes to the crossbar. At that point it decides whether to go left or right. Two possible pathways are indicated on the diagram by dashed lines.
www.syngress.com
Games Robots Play • Chapter 13 149
Drawn as a system of branches, the maze looks very easy to solve. If redrawn in the conventional way (see Figure 13.2), it looks much harder. Figure 13.2 This maze is drawn in the conventional way on paper. It branches into two at each junction and it is two junctions deep, so there are four terminals. The way the maze is drawn hides its actual structure, and makes it more difficult to solve.
Alpha Rex needs to be fitted with a pair of light sensors. In our test, we used a rectangle of hardboard as the surface. We set out the maze with masking tape. The path branches once, and each branch branches again, making it two branches deep. Also, there are four destinations. Given a random choice of direction at each branch, we would expect the robot to arrive at any one of these destinations with an equal chance. The program works with any depth of branching; you just need to have a larger area of board for the maze and adapt the program to the greater number of branches. Figures 13.3 to 13.6 The program for Maze Runner.
www.syngress.com
150 Chapter 13 • Games Robots Play
Figures 13.3 to 13.6 Continued.
www.syngress.com
Games Robots Play • Chapter 13 151
Figures 13.3 to 13.6 Continued.
The robot is placed on the stem of the first T and the Run button is pressed. The robot travels along the first T until it comes to the cross bar. As it travels it keeps itself on the stem by using the routine of the Pathfinder program. When it gets to the crossbar, it stops for a few seconds and says “Hello.” Then it continues, moving either straight ahead or turning left until it comes to the next segment of the maze. In this way, it runs from segment to segment until it gets to one of the destination stations and the program ends. The overall structure of the program is illustrated in Figure 13.7. It has five switch blocks (grey toned) and the whole is enclosed in a loop that is programmed to run “forever.” Only it doesn’t, as explained later. Reading the twin sensors and interpreting them with the first three switch blocks operates in the same way as in Pathfinder. The difference is in the branch, which in Pathfinder has the comment “Insert other routine here” (see Figure 12.19).
www.syngress.com
152 Chapter 13 • Games Robots Play
Figure 13.7 The structure of the Maze Runner program. The four sections labeled A, B, C, D, correspond to Figures 13.3 to 13.6.
The first section of the new routine is shown in Figure 13.4. After stopping the motors, pausing, and saying “Hello,” the branches variable is incremented. This three-block unit is an easy way of keeping count. The value of the variable is read, has 1 added to it, and is stored back in the variable. Branches equal the current number of stations stopped at. In our maze, the destinations are the third stop on each journey. If branches are less than three, the routine proceeds to the next stage (see Figure 13.5) in which we randomly select a number 0 or 1. This is not as simple as it seems. When we tested our robot we first used the random block on its own, with the minimum set to 0 and the maximum set to 1. The robot always followed the same way, turning left at the first junction and going straight at the second. A test run of the random block showed it always delivering the same sequence: 1, 0, 1, 0, 1, 0, 1, and so on. We may be wrong, but it seems that its output is not random for 0 and 1. To overcome this we set the range at 1 to 100, and then fed the output to a compare block. If the random number is less than 51 it returns True, and motor B is turned on alone to steer the robot left. Otherwise, it returns False and it does not steer left. This is followed by a burst of both motors to send it clear of the crossbar. www.syngress.com
Games Robots Play • Chapter 13 153
If branches equal three, the robot has already counted two stations on its path and is now at one of the destination stations. The stop block ends the program (which is how we get out of the “forever” loop).
Maze Runner—Version 2 We can tackle the random selection of route in a different way. This program selects the turn direction just before the robot leaves the station. Another approach is to select everything in advance, before beginning to run the maze. The blocks shown in Figure 13.8 are added to the program before the main loop. Figure 13.8 Selecting the route before beginning the main program.
The data for the route is to be stored in a variable called routearray. To begin with, the variable is set to 1. We then enter the loop, which runs twice because the path has two branches to deal with. Inside the loop, routearray is first multiplied by 10. Then the random block operating sends the program to a switch. If the random block generates a 1, this is added to the routearray variable. Otherwise nothing is added. When the loop finishes, routearray holds 100, 101, 110, or 111, all equally likely. The figure 1 at the beginning of each group is a dummy, which is needed to make the algorithm work. If we start with 0 and then multiply by 10 we still have 0, with only one digit, but we really want two digits. So we have to begin with a dummy digit, which is not read when the robot is following its path. The data is read from routearray by substituting a new routine (see Figure 13.9) for that in Figure 13.6. The data from routearray is transferred to arraydata, ready for www.syngress.com
154 Chapter 13 • Games Robots Play
use by the readroute5 my block (see Figure 13.10). Within the my block, the number put into index is branches –1. This is because counting branches runs from 1 upward, but the corresponding locations in routearray and arraydata are numbered from 0 upward. Figure 13.10 shows that from then on the routines are identical to those in Figure 13.6, except that the final two blocks after the loop are omitted. Figure 13.9 A new routine for reading the route data from the array.
As can be seen in Figure 13.9, the my block reads the route data from arraydata and extracts the datum corresponding to the branch we are at. The result appears in datum. This value is then used to decide whether the robot turns left before proceeding forward. Figure 13.10 The program of the my block routearray5.
Maze Runner—Version 3 Like Version 2, this version provides another way of choosing the route. The route is saved as a file access block (see Chapter 14). This means that if the maze is part of a game or the program is demonstrating how a robot can learn to solve mazes, www.syngress.com
Games Robots Play • Chapter 13 155
the most recent choice of route can be saved in memory and perhaps used as the basis of the next training session or game. This version is the same as version 1, except for the very beginning and when the robot is stopped at a station. Figure 13.11 shows the initial phase in which the route is randomly selected. It begins by closing a File Access block called route, which will hold an array that lists the sequence of choices at the junctions of the maze. To start with, choices are random, though they may be given special values later in the program, as a result of the robot trying to solve the maze. In the loop we have the random number routine. The output of this is either 0 or 1. If it is 0, the program passes through the upper branch of the switch where 0 is added to the data, if any, stored in file access block route. Remember that this is adding an extra digit to what is already stored in the block, not an arithmetic addition of 0. If the output of the random generator is 1, the program passes along the lower branch in which 1 is added to the data. Figure 13.11 Setting up a random route in a file access block.
Because our trial maze is two branches deep, the loop is repeated, resulting in a two-digit datum in the file access block. Figure 13.12 shows the new version of the program when the robot is waiting at the station. First, the my block readroute4 (see Figure 13.13) is called. This takes the route data from the file access block and puts it in a variable arraydata. The value of www.syngress.com
156 Chapter 13 • Games Robots Play
branches has already been calculated in the main program. Here it is reduced by 1, because branches run upward from 1 whereas an index must run upward from 0. The remainder of readroute4 is the standard one for reading arrays. Returning to Figure 13.12, there is a block to close the file (always a good idea when in doubt). Readroute4 has already put the route into the datum variable. If this is False, the program runs through the lower branch, which does nothing, and then on to move block, which makes the robot move straight ahead at the junction. If, on the other hand, the data is True, the program runs through the upper branch, which uses a burst of motor B, making the robot turn slightly left. Figure 13.12 Using readroute4 to control the direction in which the robot leaves the station.
Figure 13.13 The first part of the readroute4 my block. The rest is the same as readroute5 in Figure 13.10.
www.syngress.com
Games Robots Play • Chapter 13 157
Maze Learner This program takes us as far as we can go in the direction of artificial intelligence applied to solving a basic maze. The program is based on Maze Runner, version 2. First of all we wrote the Maze Runner program to make the robot stop at every junction and make a random decision. Then we modified the program to bring all the decisions to the beginning. Now we are going to make the robot learn its route and repeat it if it is the correct one. The robot runs the maze in the normal way and finds its way to a destination. But when it gets there it waits for further instructions. These are given by pressing the left NXT button. The robot remembers the path it has just taken and repeats it for as long as the left button is being pressed. Pressing the right button ends the program. Then we return the robot to the start of the maze and the robot begins again with random directions. The program (see Figure 13.14) is the same as Maze Runner version 2, apart from what happens when it has reached a terminal. There is a brief round of applause and then the program calls the my block nexttrial (see Figure 13.15). The my block scans the buttons using x mod y. The code for the pressed button is stored in the press variable. A short burst of tone indicates that a button press has been registered. Pressed is used in the switch block that follows. If it is 1 (left button), the program runs along the lower branch where branches are reset to 0. Then the program runs to the end of the loop and repeats it without having changed the route data, because the initial random choice of route comes before the main loop. If the value pressed is 2 (right button), the program runs along the upper branch, which stops execution.
www.syngress.com
158 Chapter 13 • Games Robots Play
Figure 13.14 In the maze learner program, the robot awaits a button press before proceeding with the next round of maze solving.
The program illustrates the principle (though not necessarily the mechanism) of learning by trial and error. A successful trial leads to a reward (the pressing of the left button). Going to the wrong destination results in punishment (pressing the right button). Is this artificial intelligence? Figure 13.15 This is the content of the nexttrial my block.
www.syngress.com
Games Robots Play • Chapter 13 159
Scissors, Paper, Stone This is a traditional game of strategy played by children (and adults!) all over the world. Now you can play it with your robot. Its basic version can be played on any of the robots in the Mindstorms kit. Everything takes place on the NXT screen. The game is played like this. There are two players, traditionally both human but, in our case, one is human and one is a robot. When the game is played by two human players, each player indicates their play by making hand signals. There are three possible choices: scissors, paper, or stone. Each player decides which choice they will play. On a given word, players make their hand signals simultaneously. The winner is decided by the following rules: 1. Scissors cut paper, so scissors wins over paper. 2. Paper wraps stone, so paper wins over stone. 3. Stone blunts scissors, so stone wins over scissors. Having decided the winner, the game is repeated and the object is to win as many times as possible. In the robotic version of the game the robot indicates its choice by putting the words ‘scissors’, ‘paper’, or ‘stone’ on the NXT screen. The human indicates play by pressing one of the three NXT buttons, representing (from left to right) scissors, paper, or stone. When the game begins the word ‘Ready?’ appears on the screen and the robot waits for play to begin. It’s your turn to play first so, when you’re ready, press the orange button. The message “Your choice?” appears on the screen. Press one the three buttons to indicate your choice. There is a beep and your choice appears on screen— ‘Scissors’, ‘Paper’, or ‘Stone’. At this point you need to take it on trust that this information is not carried through to the part of the program in which the robot decides its own choice. After a short delay the robot responds with the words ‘I say…’ followed by the name of its choice. A little while later it announces whether you or the robot has won. At this point you hear an appropriate sound effect. The game repeats automatically as many times as you want. In its final form the program of the game is a sequence of six My Blocks (Figure 13.16). We will look at these in turn.
www.syngress.com
160 Chapter 13 • Games Robots Play
Figure 13.16 The Scissors, Paper, Stone program consists of a series of my blocks.
Block SPSA (Figure 13.17) controls the starting sequence of the game. The display block puts the message ‘Ready?’ on the screen. Then there is a delay waiting for a button to be pressed. After this the random block generates a number in the range from 1 to 3. This provides the input to a switch block with three branches. The switch block is displayed in the figure in its compact form. It has three branches and they are identical except for the values that are generated. Figure 13.17 The first my block, SPSA, waits for the first button press and then makes a random choice of play for the robot’s first turn.
The condition table in the loop settings display shows that a random input of 1, 2, 3 directs the program to branches 1, 2, 3. The settings of the blocks are: Branch number
Message (rmessage)
Choice (rchoice)
1 2 3
Stone Scissors Paper
1 2 3
www.syngress.com
Games Robots Play • Chapter 13 161
These are the data for the robot’s first turn, chosen at random. The sound block then produces a beep. Block SPSB (Figures 13.18 and 13.19) begins with the display block set to produce the message ‘Your choice!’. Then the scanbuttons my block waits for the player to press one of the buttons. The result, 1 to 3, controls the switch block which has three branches. The name of the play you have chosen is displayed. In the second part of the block, the text ‘I say’ is concatenated with the choice made by the robot at the beginning of the program. This too is displayed on screen. Figure 13.18 A second my block, SPSB, scans the buttons for the player’s choice and displays it on the screen.
Figure 13.19 A continuation of the second my block.
Block SPSC (Figures 13.20 and 13.21) this is where the play is analyzed and the result of the contest decided. The basis of the analysis is set out in the table below:
www.syngress.com
162 Chapter 13 • Games Robots Play
Player’s choice Robot’s choice Scissors (2) Paper (3) Stone (1)
Scissors (2)
Paper (3)
Stone (1)
Draw, 0 Win, –1 Lose, 1
Lose, 1 Draw, 0 Win, 2
Win, –1 Lose, –2 Draw, 0
Figure 13.20 The third my block, SPSC, calculates and displays the result of the contest.
Figure 13.21 The continuation of the third my block.
The table shows the three possible choices for each player and the nine possible outcomes. The outcomes may be reduced to a single figure by subtracting the robot’s choice number from the player’s choice number. The values of the choices are shown in parentheses in the table and the result of subtracting the player’s choice number www.syngress.com
Games Robots Play • Chapter 13 163
from the robot’s choice number is shown beside each of the nine possible outcomes. The results range from -2 to +2. The outcomes are, from the point of view of the player, as in this table: Value
Player’s result
–2 –1 0 1 2
Lose Win Draw Lose Win
The blocks in Figure 13.20 calculate the values in the table above, and put them in the result variable block. At this stage they are increased by 2, so that they run from 0 to 4. The value of result decides which of the five branches of the switch block is to be followed. The switch block (Figure 13.21) decides which messages are to be displayed and the appropriate sound effect to go with each. The messages and sound effects are as follows: value + 2
Message
Sound effect
0 1 2 3 4
You lose! You win! It’s a draw You lose! You win!
Laughter Applause Error02 Laughter Applause
In each branch, the variable restext is set to one of the messages listed above. The sound block in each branch is set to give a sound effect according to the branch it is in. After this, the player is invited to play another round. Having completed my block SPSC, which brings the players to the end of the first turn, the program enters the main loop. This begins with my block SPSDM. This takes the place of block SPSA in subsequent rounds of the game. In the first round
www.syngress.com
164 Chapter 13 • Games Robots Play
the robot’s choice was at random. From now on, it depends on what happens in the round that is just finished. Exactly how this is done is left to the reader to discover, either by examining the program closely (Figures 13.22 and 13.23), or by playing a few rounds of the game and trying to work out how your robot opponent decides what to do. Is it’s a strategy better than yours? If not, try modifying the program to implement your (winning?) strategy. The details of my block SPSDM are as follows (Figure 13.22). It begins by setting the variable samechoice to False. Then the value of rchoice controls a switch block with four branches. Inside all except for one of its branches there is another 4-branched switch block controlled by pchoice. The four branches of the first switch block (1, 2, 3, and 4) are selected by values 0, 1, 2, and 3. The zero branch is the default and would not normally be selected. The other branches each lead to a second switch block, the branches of which are empty except when the choices would result in the game being lost by the player. There are three such situations: the robot chooses stone (1) and the player chooses scissors (2); the robot chooses scissors (2) and the player chooses paper (3); the robot chooses paper (3) and the player chooses stone (1). For each of those three combinations of choices the branch contains a variable block setting samechoice to True. Figure 13.22 The beginning of the fourth my block, SPSDM.
www.syngress.com
Games Robots Play • Chapter 13 165
Figure 13.23 The continuation of the fourth block.
The rest of SPSDM consists of a switch block with two branches. If samechoice is False, the upper branch is followed and there is no action. If samechoice is True the lower branch is followed, in which rchoice for the current round takes the value of pchoice in the previous round. Also, the text in message takes the value of the text in pmessage. Figure 13.16 shows that the main loop of the program contains SPSDM, as just described, and followed by SPSB and SPSC. These two my blocks are the same as in the initial segment of the program.
Try Something New! The Scissors, Paper, Stone program can be run on the bare NXT brick. It demonstrates the power of the brick, but can hardly be classed as a Mindstorms application. It could be made more interesting by programming the brick to communicate with the player by means of semaphore. In its simplest form, the robot has a movable arm with which to indicate its choice. This is what humans do when they play the game. They stand with one arm behind them and, chanting “One, Two, Three, GO!” raise the arm quickly, with the hand formed into the shape which indicates the choice. We can do this with a robot by building a small simple robot with an arm rotated by a motor. The position of the arm is normally vertically downward. It can be rotated upwards by 40°, 80°, or 120° to indicate scissors, paper, or stone respectively. A program segment for doing this is illustrated in Figure 13.24 and described below. It assumes that the value of rchoice has been calculated already. When the time comes to display the robot’s choice, this routine multiplies rchoice by 40 and sends it by a data wire to control the duration of www.syngress.com
166 Chapter 13 • Games Robots Play
rotation of the motor, in seconds. The arm is rotated upward by 40° or more and a beep sounds at the same time. After a delay of five seconds, the motor turns the arm in the opposite direction by the same amount to restore it to its original position.
Signalling by Semaphore A NXT robot normally communicates with humans by displaying messages on its screen, or by producing beeps and other sounds from its sound system. Here is another way of communication, which has the advantage that it can be seen from a distance. The robot can be roaming around the room and you don’t have to wait until the screen comes into view at close range. This method of communication is semaphore which, in its original two-flag form, was first used by the British navy in the 18th century and later adopted by navies throughout the world. It is ideal for communication at long distances provided there is a clear line of sight. Here we present a one-flag form or, rather, a one-arm form which can be used to signal many kinds of information including the robot’s choice in the game of Scissors, Paper, Stone. The hardware consists of one of the NXT motors with a small lever attached at a right-angle to its spindle. In its default state the lever points vertically downward. It can be rotated through a small angle to convey a message. The program (Figure 13.24) accepts a coded input, ranging from 1 to 3. These might indicate the robot’s choice of play according to the codes used in the Scissors, Paper, Stone game. The code is stored in the rchoice variable block. The code is then multiplied by 40 and used to set the duration for running the motor, in degrees. The result of this is that the motor, and therefore the lever or arm is rotated by 40°, 80°, or 120°. This is an easily recognizable signal. There is a delay to give the player time to notice the signal. Then the second motor block, which is set to the reverse direction, rotates the arm back to its original vertical position. Figure 13.24 A program segment for a semaphore, which indicates the robot’s choice.
www.syngress.com
Games Robots Play • Chapter 13 167
Although this routine was written with a particular game in mind, it has many applications for turning a lever or wheel by a fixed amount, depending upon the value of the code.
Try Something New! Why stop at one arm? Why not have two driven by a pair of motors? Let them drive the arms of a small humanoid robot. Teach it the international semaphore code. Then write a text-to-semaphore program.
Magic Give your robot magic powers! Program it to read the human mind! Well, that’s what it looks like but really it is an ingenious magic trick normally performed by a human magician at a family magic show. The trick is what is called a self working one, and no mind reading capabilities are required. Now we have a version that sets the robot up as a ‘mind reader’. The trick goes like this. The magician (human or robot) shows a spectator a rectangle of card on which is drawn pictures of six different animals. The animals are dog, bear, tiger, parrot, giraffe, and tortoise. They are scattered over the card (not in the order just listed) with their names beside them. The magician asks the spectator to choose one of the animals but not to say which one. The magician explains that they are going to point to the pictures in turn. As the magician points to each picture, the spectator is to silently spell one letter of the animal’s name, and to say “Stop!” as the last letter of the name is reached. The magical effect is that when the spectator is saying “Stop!”, the magician is pointing at the animal chosen by the spectator. How did the magician know when to point to that particular animal? Did the magician read the spectator’s mind? The secret of the trick is the order in which the magician points to the pictures, and silently counts 1, 2, 3, and so on. For the first two counts, the magician can point to any two of the animals. On the count of three, the magician points to the dog. On the count of four, the magician points to the bear. On the count of five, to the tiger. Each time, from the count of three onward, the number of letters in the animal’s name is equal to the magician’s silent count. This automatically results in the magician pointing to the chosen animal’s picture at the same time as the spectator spells the last letter of its name. www.syngress.com
168 Chapter 13 • Games Robots Play
The first stage in preparing for this program is to draw out the chart showing the coordinates of the pictures (Figure 13.25). The arrows show that we planned a complicated route which makes it difficult for observers to spot how the trick works. Figure 13.25 shows the initial planning. Use this diagram or a similar one when setting out the animal drawings on a rectangle of card. But do not include the grid, the coordinates, or the arrows. Include just the drawings and the names of the animals. Figure 13.25 Preparation for the magic trick. This shows the coordinates of the six animals and the order in which the pointer moves to point to them.
The most suitable robot for this trick is RoboArm. This is driven by two motors. Motor C rotates the arm, left to right and right to left, on it vertical axis. Motor B extends and retracts the arm. If the arm has a pointer on its end, motor C moves the pointer across the chart of animal drawings, while motor B moves the pointer up and down the chart. www.syngress.com
Games Robots Play • Chapter 13 169
The arm of the robot is modified for this program. Remove the grabber and, in its place, install a lazy tongs mechanism ending in a pointer (Figure 13.26). As motor B extends the arm, the lazy tongs amplify this movement and the pointer can reach up to 30 cm away from the axis of rotation. As motor C swings the arm, left to right, the pointer moves about 30 cm. Setting the number of degrees turned by the motors makes it possible to point to drawings anywhere within a 20 cm square. It is preferable not to have a larger square because slackness in the mechanism makes it difficult to locate the extreme positions precisely. With our robot we found that, to move the pointer a given number of centimeters, we needed to set the motor duration to the same number of degrees. Figure 13.26 The RoboArm robot modified by fitting a lazy tongs pointer.
Figure 13.27 shows the pointer in action. The arm is positioned behind the chart from the spectator’s point of view. To begin the trick, the pointer is located at the origin (0, 0), which is the top left. The arm is positioned by manually turning the two small handles of the mechanism.
www.syngress.com
170 Chapter 13 • Games Robots Play
Figure 13.27 The robot is pointing at one of the animal pictures.
The Program All the time the program is running the buttons of the NXT are being scanned by a short routine running continuously in a loop. The variable Logic 1 is normally False but, when a button is pressed, it becomes True. The main program moves the pointer to each animal in turn and waits for a few seconds to detect the button press, if any. For the first two animals, we do not test the buttons but simply wait for one second after sounding the beep. The diagram has comments to indicate the position to which the pointer is moved. These are the same as in Figure 13.25. The values entered when setting the motor blocks are the differences between one position in the next, according to this table: B
C
Difference B
Difference C
0 17 11 1 16 11 7 17 8
0 12 18 19 3 18 2 12 13
– 17 –6 –10 15 –5 –4 10 –9
– 12 6 1 –16 15 –13 10 1
www.syngress.com
Games Robots Play • Chapter 13 171
Where the table shows a negative difference the motors are run in the reverse direction. Figure 13.28 The first stage of the Magic program, pointing at the first two animals. This runs in parallel with the loop and is waiting for a response from the spectator.
The program continues (figure 13.29) by taking the pointer to the third animal (in our case, the dog), beeping, and testing Logic 1. The switch block follows the lower branch if a button has not been pressed. This takes the pointer to the next animal. If a button has been pressed, the top branch is followed, returning the pointer to the origin and sounding a fanfare, after which the stop block ends the program. Figure 13.29 Pointing at the third animal with the switch block that analyzes the spectator’s response, if any. This is followed by four more switch blocks with the same structure but different settings.
www.syngress.com
172 Chapter 13 • Games Robots Play
Following this, the program has four more such switch blocks, each preceded by a sampling of Logic 1. In each block the lower branch has the motor settings that take the pointer to the next animal. The settings are those in the third and fourth columns of the table above. The upper branch in each case takes the pointer back to the origin. The settings are the negatives of those in the first and second columns of the table. The result is that, at each switch block, the pointer is either returned to the origin because the spectator has pressed a button, or is moved on to the next animal. If the spectator does not press the button at any stage, the last sequence of the program (Figure 13.30) takes the pointer back to the origin and the program ends.
Figure 13.30 The final sequence takes the pointer back to the origin.
Try Something New! There are quite a lot of self working magic tricks, particularly in books intended for beginner magicians. Try to adapt one of these so that it can be performed by one of your Mindstorms robots. Or you could design and build your own magic robot!
www.syngress.com
Chapter 14
Databases for Robots
173
174 Chapter 14 • Databases for Robots
Introduction It is often necessary for an item of data (numeric, logic, text) to be stored away somewhere, and to be retrievable when required. The variable block is useful for this purpose, but has the disadvantage that the stored value is lost when the power is switched off. You might want to keep a value obtained during the running of a program so that it is available the next time the robot is switched on. Examples of this are settings used in calibrating the sensors, and data acquired in games programs. Another feature that may be required is the ability to store data in an array, so that one particular item of data can be picked out simply by referring to its index (the number of its position) in the array. What we need is a look-up table. This chapter shows how to implement look-up tables in NXT-G. For example, this is a look-up table of the names of the days of the week. Index
Name of weekday
0
Monday
1
Tuesday
2
Wednesday
3
Thursday
4
Friday
It is usual for indices to run from 0 upward rather than from 1. When using the software version of this table, you key in or calculate the index, a number in the range 0 to 4. For instance, you key in a “2” and the table returns “Wednesday.” In this example, the table holds text, but it could hold numbers or logical states. The next section shows how to generate this table as software.
Lookup Table for Weekdays The makearray program is illustrated in Figure 14.1. Its main element is a switch block that holds the array data. This program will hold the names of five weekdays, so we need five branches in the switch block. When the switch block is first put on the screen, it is in its default state. It has only two branches, numbered 1 and 2, and these are allocated input condition values 0 and 1. To increase the number of branches, deselect the “flat view” option, and then press the small + button three times. www.syngress.com
Databases for Robots • Chapter 14 175
This adds three more branches, numbered 3, 4, 5, and these are allocated input condition values 2, 3, and 4 automatically. Figure 14.1 The structure of a my block, makearray, which functions as a lookup table.
Taking each block in turn by selecting the tab on the switch block, place one variable block on each branch, and name it datum. Set it to hold text and put it in the write mode. Write into each one the name of a day of the week, in order from Monday (Branch 1) to Friday (Branch 5). At this stage, turn the program (the index block plus the switch block) into a my block. To demonstrate the use of the my block shown in Figure 14.2, edit the value stored in index to a number in the range 0 to 4. Run the program and check that the corresponding day of the week appears on the screen of the brick. Figure 14.2 Demonstrating the action of makearray.
This program operates on the principle of having a single variable, index, which can be given any one of a number of values, depending on the values inserted when www.syngress.com
176 Chapter 14 • Databases for Robots
the switch block was constructed. A number is loaded into an index and, when the my block is called, the corresponding value of datum is returned. In this demo, the value returned is displayed on the screen. The data in this table is put into it when it is programmed. It is not possible to alter the data during the running of the program. Each time the program is run as part of a bigger program, the same data is stored in the table ready to reference. The next program allows the data to be changed during runtime.
Writable Lookup Table Another approach to data storage is to have individual variable blocks, which for convenience, we might name datum0, datum1, datum2, and so on. The switch block has several branches as before, all with the same structure as in Figure 14.3. The set of variables listed above is put into branch 1, branch 2, and so on, one variable in each branch. Each branch also has a block for the variable datum (just as in the previous program), which will eventually contain the required item of data. The individual “datum x” block in each branch is connected by data wire to the datum variable block of that branch. In this way, one of the data items that are stored in datum0, datum1, and so on, is written into datum and may be read from datum elsewhere in the program. Figure 14.3 If the switch block of makearray is modified by including these two action blocks in each branch, it becomes possible to load data into a lookup table while the program is running.
www.syngress.com
Databases for Robots • Chapter 14 177
The advantage of this variation of the program is that it allows the content of any one or more of the individual blocks to be changed independently during the running of the program, without affecting the other blocks in the array.
Another Way of Using a Lookup Table You have just seen how to obtain a piece of data by quoting the index number. Instead of using the table in this way, we might want to specify a piece of data and find its index number. This program (see Figures 14.4 and 14.5) operates in this way. The first four blocks of the program declare the variable blocks to be used in the array. It is not necessary to give them a value when the program is being written, because the program allows values to be changed one time at run time. The variable findno is also set at runtime. Figure 14.4 This program has the opposite action to makearray. If we quote the value that the variable should have, the program returns the corresponding index number.
The main program is enclosed in a loop, which is ended by a logical True value. The switch block is controlled by the output of the loop counter, so that the branches of the switch block are run in turn, putting each of the corresponding stored variable values into the datum variable. At the same time, count is being put into the index variable.
www.syngress.com
178 Chapter 14 • Databases for Robots
Figure 14.5 Continuing the program of Figure 14.4.
The program is designed to discover which index number corresponds with the given value. This is done by comparing datum with findno. Incidentally, this routine can be used for storing numbers but not for storing text, because the compare block does not operate on text. As soon as the compare block detects a match between datum and findno, the loop ends. Outside the loop we have the required value of the index.
Reading Data from a File Access Block NXT-G action blocks include the file access block for writing data to a file. This can be the basis of lookup tables, with the advantage that the data is not lost when the power is switched off. This is very useful for programs in which the robot is trained to perform certain actions, and needs to remember them the next time the program is run, without having to retrain the robot. More data can be added to data already in the file; the new data is simply tacked on to the end of the existing data. This program differs from the previous ones, because the data for the whole table is stored in a single file. Data may be in the form of numbers or text, but not logic. A file access block is intended to store a single item of data. For example, it might store a numerical value, such as 2562, or it might store a string of text, such as “Good morning everybody!” Here we present a technique for storing more than one item of numerical data as a single numerical value.
www.syngress.com
Databases for Robots • Chapter 14 179
Setting up the look-up table is easy. Drag a file access block on the working area and, in its configuration panel, select “Write,” give it a name, and select “Number” as the data type. At this stage, you can give it a value. At any time later in a program you can add data to this block. The interesting point is that when you write to the same block again, the data you write to it is added to that which is already there. When we say “added” we mean “appended.” For instance, if the block holds “265,” and you write “32” to the same block, the block now holds “26532.” Once data has been stored in a file, it can only be cleared as a whole. This is done by using the file access block set to “delete.” Although data can be accumulated one numeral or character at a time, there is no facility for recovering individual numerals or characters. File access can read only “the lot.” However, the routine described below reads individual digits from a number stored in a NXT data file. It is an elementary but a very useful and accessible equivalent to the data array, or look-up table in other languages such as BASIC or Java. The program is illustrated in Figures 14.6, 14.7, and 14.8. Data wires are connected as follows: ■ ■
■
In Figure 14.6: Read file to arraydata. In Figure 14.7: Output terminal of the loop counter to compare block B (in Figure 14.7). Arraydata to math divide A and to math subtract A. Math divide to math multiply A. Math multiply to math subtract B and to datum. Math subtract to arraydata. In Figure 14.8: Index to compare A. Compare to loop exit terminal. Datum to the my block, dispresult.
Because this is a demo version, we begin by erasing any files that were set up in previous runs. The blocks in Figure 14.6 then set up the data file array1. The index is the position in the data of the single numeral to be read. These are numbered from 0 (the last digit) counting to the left. For example, if the data is “26418” and the index is “3,” the extracted digit is “6.” The reading routine is enclosed in a loop, which runs until the required digit has been extracted and stored as datum. Leaving the loop, this demo version uses dispresult to display datum.
www.syngress.com
180 Chapter 14 • Databases for Robots
Figure 14.6 By using a file access block, the data stored in the array is retained when the power is switched off.
Figure 14.7 Continuation of the program of Figure 14.6.
www.syngress.com
Databases for Robots • Chapter 14 181
Figure 14.8 Continuation of the program of Figure 14.6.
The algorithm makes use of the fact that NXT-G division retains the quotient but drops the remainder. Follow through this example: Start with the data:
4287
Divide by 10
428
Multiply by 10
4280
Subtract from data
4287 – 4280 = 7
Note: the 7 is dropped. Data extracted, store in datum.
The next digit is extracted by repeating the above, but starting with the ‘428’. Start with the data:
428
Divide by 10
42
Multiply by 10
420
Subtract from data
428 – 420 = 8
Note: the 8 is dropped. Data extracted, store in datum.
www.syngress.com
182 Chapter 14 • Databases for Robots
The loop repeats the process until the loop counter equals the pre-set index. The value in datum is that of the required digit. The routine is limited to 10 digits with the maximum value of 2147483648. Note that there is one restriction on what can be stored where. It is not possible to store values higher than 2 at the index 9 location, because this would make the stored number larger than the file can hold. However, provided that index 9 is not used, there are no restrictions on what can be stored at the other locations. The routine can be adapted to extract 2-digit numbers. Divide and multiply by 100 instead of by 10. For example, if the data is “1462771804” and index is “2,” the routine returns “77.” The algorithm is the equivalent of a one-dimensional array of single-digit values and can be used whenever such a facility is wanted. It has many applications as a look-up table. It can store irregular data such as scores and moves in games, and solutions to mazes. If you want to read data at several places within a program, it is best to create a my block from the loop in Figures 14.7 and 14.8. We have called ours readdata, and Figure 14.9 shows how to use it. First we have the delete block, which may or may not be necessary, but we include it in this demo program to clear the memory before starting to run. Suppose that we have already created a file called array1 with data in it. Edit the filename of each of the three file access blocks to array1. Enter the index, or obtain it from some other source. Call the my block, which processes the information in array1 and index and returns the result in datum. The result is the value stored at the indexed location in the file access block is displayed on the NXT screen. Figure 14.9 Using the readdata my block to access a look-up table during runtime.
www.syngress.com
Databases for Robots • Chapter 14 183
There may be several files (array1, array2, array3, and so on) in your program, which you can access by using their names. All you have to do is load arraydata from the file (remembering to close the file before reading from it) and then use the my block to process the file and extract the required data from it.
Acknowledgements Thanks are due to Dr Christine Bishop for suggesting hardboard as a suitable surface for walking robots. Brilliant! Thanks are also due to Dr Daniel Bishop and to Laura Bishop for acting as models for two of the photographs.
www.syngress.com
This page intentionally left blank
Index A Alpha Rex robot avoidance routine for, 82–83 dance snippets for, 94 obstacle avoidance program for, 83 pathfinder, 137–142 program for playing tune, 92 to sing and dance, 93 song snippets for, 94 steering, 127–130 ultrasonic search, 84 arithmetic operators, 28
E exclusive-OR operation, 140
B Bluetooth, robot connection with, 17 bumper program, 74
L LEGO® Mindstorms® kit, 120 for building robots, 2 LightFinder1 program, 63 LightFinder2 program, 64 LightFinder3 program, 66 LightFinder4 program, 67–69 light sensor, 24, 122 application in edge-following routine of robots, 133 directed downward, 54 directed forward, 63 directed upward, 60 LED, 52 mounted on front beam of Quickstart, 56 as pathfinder, 137 trigger point of, 58 LinedIn program, 57 logical operator, 28–29 logical signal, for loop, 38 look-up tables, 105 procedure for using, 177–178
C changestep routine, for robots, 129 compiler program, 6 cosine rule, for NXT-G programming, 142–146 D dance some more program, for loop counter, 34–36 data hub, 54 data plugs, 54 data wires connections, 106 for NXT-G program, 19–21 source of, 24–26 types of, 24 diagnostic programming, 46–49 displogic (debugging programs), 48 down-pointing light sensor, 57
F flag variable, 29 floating point data, 24 forever loop program, 32–33 four rules. See NXT-G program, arithmetic operation H Hello World program, 16 Housefly program, 60
185
186 Index
look-up tables, (Continued) for weekdays, 174–176 writable, 176–177 loop program dance some more program for, 34–36 logical signal for, 38 for logical variable change, 37 microcontrollers in, 32 nested loop, 38–39 outside events, 33–34 time limit and counting, 32 tone burst generation (See tone burst generation, by loop) for waiting, of event occurrence, 38 M magnetic compass, 122 magnetic compass sensor, 96 circular navigation using, 99–102 polygon navigation using, 98–99 makearray program, 174–175 math block, 24–25 for arithmetic operation, NXT-G operation, 28 MaxIteration, 68, 70 Maze Learner, 157–158 Maze Runner program for, 149 structure of, 152 Maze Runner-Version 1, 148–153 Maze Runner-Version 2, 153–154 Maze Runner-Version 3, 154–156 maze-solving programs, 141 memory management, after NXT-G program compilation, 18 microcontrollers, 42 entering in loop, 32 in NXT, 6 mobile robots calculation for distance traveled, 120 www.syngress.com
edge following routine, 131 in-built compass, 122 no-go response to a line, 125–127 modulo counting series, program for generating, 116 N nested loop program, 38–39 Newtonian iteration, 109 numbern, 108 numeric data, source, 24 NXT brick, 8 NXT buttons, program for scanning, 77 NXT-G program, 2–3, 5, 12, 142 arithmetic operation, 28 compilation of, 13–18 memory management after, 18 data wires use, 19–21 for icons representation, 4 microcontrollers for, 6 on Tribot, 4 NXT robots calculating cosines for, 105–107 combinations, 113–114 factorials, 110 floating point arithmetic, 104–105 program for modulo counting, 115–117 square root, 108 X modulo Y, 114 P pathfinder program, for robot navigation, 137 photodiode, 56 programming blocks, 12–13. See also NXT-G program program module, for reading logical values when debugging, 49
Q quickstart robot, 19, 57–58, 60 bumper mechanism of, 72 quickstart vehicle, 54, 74, 98 R resstring, for storing value in variable block, 48 RoboArm robot, 2, 9, 79, 163. See also robots, types by LEGO® Mindstorms® NXT-G program on, 4 robot designing, 6 edge follower, 59–60 edge follower 1 routine, 122–125 environment specification of, 7 games Maze Learner, 157–158 Maze Runner-Version 1, 148–153 Maze Runner-Version 2, 153–154 Maze Runner-Version 3, 154–156 line follower, 58–59 loop block in, 34 NXT-G program for, 16 types, by LEGO® Mindstorms®, 2 ultrasonic sensor of, 7 weight-shifting mechanism of, 128 S ScanTurn, 67, 70 self-calibrating program, 136 semaphore, 166–167 snippet program, 26 sound sensors, 24, 88 Spike, 61 switch block
Index 187
controlled by logic value, 44 controlled by numeric value, 43 for controlling flow of program, 42 execution along alternative pathways, 44 working of, 42 T text data, source, 25 tone burst generation, by loop, 38 touch sensor, 72 for navigation, 74 Tribot, 2, 9. See also quickstart robot; robots, types by LEGO® Mindstorms® NXT-G program on, 4 U ultrasonic sensor, 82 for robot navigation, 7 USB cable, robot connection with, 17 V variable block arithmetic operation on, 28 configuration, 27–28 variables data storing capacity of, 27 program identification, 26 W wait block categories, 39 receiving of data, 40 writable lookup table, 176–177 X xmody cycles, 78
www.syngress.com