You are previewing Make: Lego and Arduino Projects.

Make: Lego and Arduino Projects

Cover of Make: Lego and Arduino Projects by John Baichtal... Published by O'Reilly Media, Inc.
  1. Special Upgrade Offer
  2. A Note Regarding Supplemental Files
  3. Foreword
  4. Preface
    1. Assumptions This Book Makes
    2. Contents of This Book
    3. Conventions Used in This Book
      1. Lego CAD Conventions
    4. Using Code Examples
    5. Safari® Books Online
    6. How to Contact Us
    7. Acknowledgments for John
    8. Acknowledgments for Matthew
    9. Acknowledgments for Adam
  5. 1. Project: Drawbot
    1. Parts List
      1. Tools & Electronics
      2. Lego Elements
    2. Assembly Instructions
      1. Build the Lego Model
      2. Attach the Arduino and Bricktronics Shield
      3. Attach the Pen
    3. Program the Robot
      1. Processing and Arduino
      2. Setting Up the Programming Environment
      3. Don’t Forget Your Libraries!
      4. The Arduino Sketch
    4. The Next Chapter
  6. 2. Anatomy of Lego Robotics
    1. Mindstorms
      1. The NXT Brick
      2. Sensors
      3. Motors
      4. Wires
      5. Technic Beams, Mechanics & Connectors
    2. Expanding on the Mindstorms Set
      1. Buying More
      2. Add-On Electronics
      3. Third-Party Bricks
      4. Non-Mindstorms Lego Bricks
      5. Power Functions
    3. Programming Your Brick
    4. The Next Chapter
  7. 3. Arduino Interlude
    1. History of the Arduino Project
    2. What Is OSHW?
    3. Anatomy of the Uno
    4. The Arduino Ecosystem
      1. Uno Alternatives
      2. Older Models
      3. Shields
    5. Arduino Resources
      1. Books
      2. Websites
      3. Code
    6. The Next Chapter
  8. 4. Project: Clock
    1. Parts List
      1. Tools & Electronics
      2. Lego Elements
    2. Assembly Instructions
      1. Prepare the Gear
      2. Build the Lego Model
      3. Install the Arduino
    3. Program the Robot
    4. Setting the Clock
    5. The Next Chapter
  9. 5. Project: Chocolate Milk Maker
    1. Parts List
      1. Tools & Electronics
      2. Beverage Handling
      3. Food
      4. Lego Elements
    2. Assembly Instructions
      1. Build the Pump Assembly
      2. Build the Lego Model
      3. Attach the Syrup Bottle
      4. Build the Mixing Attachment
      5. Wire up and Install the Electronics
    3. Program the Robot
    4. The Next Chapter
  10. 6. Basic Electronic Theory
    1. Basic Concepts in Electricity
      1. Voltage, Current & Resistance
      2. Ohm’s Law
      3. Other Concepts
    2. Know Your Electronic Components
      1. Resistors
      2. Capacitors
      3. Diodes and LEDs
      4. Inductors
      5. Transistors
      6. Integrated Circuits
    3. Sensors 101
      1. Digital Sensors
      2. Analog Sensors
    4. Further Study
  11. 7. Gripperbot
    1. Parts List
      1. Electronics Parts
      2. Lego Elements
    2. Building Instructions
      1. Bracers
      2. Gripperbot
    3. Assembling the Gripperbot’s Electronics
    4. Programming the Gripperbot
    5. The Next Chapter
  12. 8. Project: Keytar
    1. Parts List
      1. Tools & Electronics
      2. Lego Elements
    2. Assembly Instructions
      1. Build the Lego Model
      2. Install the Electronics
    3. Program the Keytar
    4. Play Some Music!
    5. The Next Chapter
  13. 9. Project: Lamp
    1. Parts List
      1. Tools & Electronics
      2. Lego Elements
    2. Assembly Instructions
      1. Build the Lego Model
      2. Install the Electronics
      3. Download and Install the App
    3. Program the Lamp
    4. The Next Chapter
  14. 10. Advanced Techniques
    1. Wiring Up Bricktronics Equivalents
    2. Mounting PCBs to Legos
    3. Adding Molex Connectors to Lego Wires
    4. All About Motors
      1. DC Brushed Motors
      2. Stepper Motors
      3. Hobby Servo Motors
    5. Powering Your Robot
      1. DC Power Jack
      2. USB Connector
      3. Batteries
      4. Battery Dos and Don’ts
    6. NXT to Arduino Communication
    7. XBee Wireless Modules
    8. Epilogue
  15. Index
  16. About the Authors
  17. Colophon
  18. Special Upgrade Offer
  19. Copyright
O'Reilly logo

Chapter 1. Project: Drawbot

IN THIS CHAPTER

Parts List

Assembly Instructions

Program the Robot

The Next Chapter

The Drawbot project consists of a small, wheeled robot that creates drawings as it rolls
Figure 1-1. The Drawbot project consists of a small, wheeled robot that creates drawings as it rolls

Our first project consists of a Drawbot (Figure 1-1), a small robot that rolls around with a marking pen trailing behind it, leaving a line that traces the path the Drawbot took. We’ll program the robot to react to obstacles by turning away and trying another path, allowing it to keep drawing even after it hits an obstruction.

We’ll tackle a very basic method of creating art. Essentially, we’ll program the robot to respond to input from its touch sensor to create a series of circles, arcs, and spirals, as seen in Figure 1-2.

Robot-created art!
Figure 1-2. Robot-created art!

This is how it works. When the bumper is pushed the first time, each motor is assigned a random speed, from 255 (full speed forwards) to -255 (full speed backwards). There is also a random timeout assigned, between 1 and 10 seconds. If the bumper is hit, the two speeds for the motors are reversed, and slowed down a little. If the motors are already going very slowly, or when the timeout runs out, new random speeds are assigned for each motor, as well as a new random timeout. Isn’t art cool?

Parts List

While not as complicated as other models, the Drawbot packs a lot of detail into a small package. Let’s go over what you’ll need to create the robot.

Tools & Electronics

  • Arduino Uno

  • Bricktronics Shield (see Figure 1-3 and the INTRODUCING BRICKTRONICS sidebar)

  • Several #2, 0.25″ wood screws

  • 2.1 mm DC Plug (we used CP3-1000-ND from Digi-Key)

  • Battery pack (We used Mouser P/N 12BH361A-6R)

  • Bricktronics mounting plates (see the ATTACHING THE ARDUINO & BATTERY PACK sidebar)

  • Clothespin, the standard wooden kind with a spring

  • Marking pen

  • One 8-32, 1.5″ machine screw with washer and nut

The Bricktronics Shield (the board to the right) is your path to combining Lego and Arduino technologies! The Bricktronics Motor Controller (left) helps you control a mess of motors
Figure 1-3. The Bricktronics Shield (the board to the right) is your path to combining Lego and Arduino technologies! The Bricktronics Motor Controller (left) helps you control a mess of motors

Lego Elements

We used the following Lego parts (Figure 1-4) to build our Drawbot. Gather together what you need and follow the directions later in this chapter to build your robot.

We developed the models over a few months, fixing and changing as we tested them. We’re proud of them, and they work well. However, they’re only one of many valid designs for each of our projects! Feel free to make adjustments and see how they change the project!

A. Touch sensor

B. 2 interactive servo motors

C. 3 Mindstorms wires (not shown in Figure 1-4)

D. 2 rims

E. 2 tires

F. 2M Technic beams[1]

G. 2 7M Technic beams

H. 4 Technic angle beams 3x5

I. 2 double angle beams 3x7

J. 2 Technic levers 3M[2]

K. 4 Technic levers 4M[3]

L. 2 Technic triangles[4]

M. 2 halfbeam curves 3x5[5]

N. 18 half bushes

O. 9 bushes

P. 5 2M cross axles (red)

Q. 3 connector pegs 3M (blue)

R. 12 cross connector pegs (blue)

S. 1 cross connector peg w/o friction tabs (beige)

T. 3 3M cross axles

U. 6 3M cross axles with knob

V. 5 4M cross axles

W. 2 4M cross axles with end stop[6]

X. 6 5M cross axles

Y. 1 8M cross axle[7]

Z. 2 tubes[8]

AA. 2 cross axle extensions

BB. 1 catch with cross hole

CC. 7 double cross blocks[9]

DD. 4 180-degree angle elements

EE. 1 Technic cross block fork

FF. 1 2x3 cross block

GG. 1 3x3 connector block[10]

HH. 2 3M Technic beams with snaps

II. 2 belt wheels[11]

These are the Lego parts you need to build your Drawbot
Figure 1-4. These are the Lego parts you need to build your Drawbot

Assembly Instructions

While the robot itself is relatively small, its construction can be a bit complicated. However, the following instructions will guide you through the steps.

Build the Lego Model

Let’s tackle the Drawbot’s Lego chassis. It’s a fun little robot with three wheels and a nice big platform for holding the battery pack as well as the Arduino and Bricktronics Shield.

  1. Let’s begin with the bumper assembly. Connect an angle element to the triangular 3x3 block as shown in Figure 1-5.

  2. Slide one of those red 2M cross axles through the block. Figure 1-6 shows where it goes.

  3. Add a triangular plate to the bumper assembly, held in place by the bottom of the 2M axle, as shown in Figure 1-7.

    Step 1: Bumper assembly
    Figure 1-5. Step 1: Bumper assembly
    Step 2: Continuing with the bumper
    Figure 1-6. Step 2: Continuing with the bumper
    Step 3: Adding a triangular plate
    Figure 1-7. Step 3: Adding a triangular plate
  4. Add two more 2M cross axles as shown in Figure 1-8.

  5. Add the angle beams shown in Figure 1-9; they’ll serve as the business end of the bumper!

    Step 4: More axles
    Figure 1-8. Step 4: More axles
    Step 5: Rounding out the bumper
    Figure 1-9. Step 5: Rounding out the bumper
  6. Add another triangular plate to the top to secure the various elements as shown in Figure 1-10.

  7. Slide a 3M cross axle through the top hole of the triangular plates, leaving enough room for a half bush on the top and bottom. Figure 1-11 shows the arrangement.

    Step 6: Topping it off
    Figure 1-10. Step 6: Topping it off
    Step 7: Inserting a cross axle with a bit coming out of both ends
    Figure 1-11. Step 7: Inserting a cross axle with a bit coming out of both ends
  8. Add the half bushes as shown in Figure 1-12. The bumper assembly is complete!

    Step 8: Finishing the bumper
    Figure 1-12. Step 8: Finishing the bumper
  9. Next, let’s work on the Drawbot’s motors. Slide two 5M axles through the motor’s holes, while holding an L-shaped beam in place as you do, as shown in Figure 1-13.

    Step 9: Attaching the axles and L beam
    Figure 1-13. Step 9: Attaching the axles and L beam
  10. Add two cross-axle extenders as shown in Figure 1-14.

  11. Connect two 5M beams to the extenders as shown in Figure 1-15.

    Step 10: Adding extenders
    Figure 1-14. Step 10: Adding extenders
    Step 11: Extending the axles
    Figure 1-15. Step 11: Extending the axles
  12. Next, add a 3M beam with pegs to the motor as shown in Figure 1-16.

  13. Then, add a couple of tubes as shown in Figure 1-17.

    Step 12: Attaching the 3M beam
    Figure 1-16. Step 12: Attaching the 3M beam
    Step 13: Adding a couple of tubes
    Figure 1-17. Step 13: Adding a couple of tubes
  14. Then, another 3M beam with pegs! Figure 1-18 shows how it goes in.

  15. Connect another motor as you see in Figure 1-19. Make sure to hold another angle beam in place as you slide the cross axles through the new motor’s holes.

    Step 14: Attaching another beam
    Figure 1-18. Step 14: Attaching another beam
    Step 15: Connecting the second motor
    Figure 1-19. Step 15: Connecting the second motor
  16. Secure the cross axles with bushes (see Figure 1-20). Now you’re done connecting the two motors.

    Step 16: Securing the cross axles
    Figure 1-20. Step 16: Securing the cross axles
  17. Next, let’s tackle the rear wheel. Begin by adding a beige cross connector (the kind without friction tabs) to a catch. Figure 1-21 shows this arrangement.

  18. Next, add one of the cross blocks and secure it with a 2M cross axle, as shown in Figure 1-22.

    Step 17: Starting the rear wheel
    Figure 1-21. Step 17: Starting the rear wheel
    Step 18: Securing the assembly
    Figure 1-22. Step 18: Securing the assembly
  19. Add two 3M connector pegs (see Figure 1-23).

  20. Slide a 2M beam onto the pegs as shown in Figure 1-24.

    Step 19: Adding connector pegs
    Figure 1-23. Step 19: Adding connector pegs
    Step 20: Sliding the beam on
    Figure 1-24. Step 20: Sliding the beam on
  21. Connect a 2x3 cross block to the ends of the pegs. Figure 1-25 shows how they go together.

  22. Add a 2M cross axle and a belt wheel (Figure 1-26).

    Step 21: Connecting the cross block
    Figure 1-25. Step 21: Connecting the cross block
    Step 22: Attaching the wheel
    Figure 1-26. Step 22: Attaching the wheel
  23. Connect another belt wheel (Figure 1-27). The rear wheel assembly is complete! Set it aside for now; we’ll attach it at the end.

    Step 23: Adding another wheel
    Figure 1-27. Step 23: Adding another wheel
  24. Next, let’s work on the main chassis. Connect a 7M beam, a halfbeam curve, and a 4M cross axle as shown in Figure 1-28. Note that this won’t stay on—you’ll have to hold it in place with your finger for now.

  25. Add a cross block and a 3M liftarm on the back, as shown in Figure 1-29.

    Step 24: Beginning the main chassis
    Figure 1-28. Step 24: Beginning the main chassis
    Step 25: Attaching cross block and liftarm
    Figure 1-29. Step 25: Attaching cross block and liftarm
  26. And another 4M axle (Figure 1-30)!

  27. Connect a 3M peg to a 180-degree angle element, as shown in Figure 1-31.

    Step 26: Adding one more axle
    Figure 1-30. Step 26: Adding one more axle
    Step 27: Connecting the peg to the angle element
    Figure 1-31. Step 27: Connecting the peg to the angle element
  28. Add two more angle elements to the peg (Figure 1-32).

  29. Next attach the angle elements to the ends of the two 4M axles as shown in Figure 1-33.

    Step 28: Two more angle elements
    Figure 1-32. Step 28: Two more angle elements
    Step 29: Connecting the assemblies
    Figure 1-33. Step 29: Connecting the assemblies
  30. Shove two more 4M cross axles into the angle elements (Figure 1-34).

  31. Then, shove another halfbeam curve onto the ends of the axles as shown in Figure 1-35.

    Step 30: Two more axles
    Figure 1-34. Step 30: Two more axles
    Step 31: Adding another halfbeam curve
    Figure 1-35. Step 31: Adding another halfbeam curve
  32. Add another 7M beam as shown in Figure 1-36.

  33. Add a cross block and 3M liftarm to the cross axles (Figure 1-37).

    Step 32: Adding another 7M beam
    Figure 1-36. Step 32: Adding another 7M beam
    Step 33: Adding cross block and liftarm
    Figure 1-37. Step 33: Adding cross block and liftarm
  34. Slide a pair of 3M axles through the holes of a cross block. Figure 1-38 shows this step.

  35. Next, pop on a pair of 3x5 angle beams (Figure 1-39).

    Step 34: Connecting two axles to a cross block
    Figure 1-38. Step 34: Connecting two axles to a cross block
    Step 35: Attaching L-shaped beams
    Figure 1-39. Step 35: Attaching L-shaped beams
  36. Position the assembly you created as you see in Figure 1-40; the next step shows you how to secure it.

  37. Slide a 5M axle through the cross-holes of the halfbeam curves as shown in Figure 1-41.

    Step 36: Lining the beams up with the assembly
    Figure 1-40. Step 36: Lining the beams up with the assembly
    Step 37: Securing things in place
    Figure 1-41. Step 37: Securing things in place
  38. Add another 5M axle, but this time, hold a bush in place in the middle with your fingers as you slide the axle through, as shown in Figure 1-42.

  39. Add half bushes to keep everything in place (Figure 1-43). The back assembly is done!

    Step 38: Adding another axle
    Figure 1-42. Step 38: Adding another axle
    Step 39: Finishing the assembly
    Figure 1-43. Step 39: Finishing the assembly
  40. This is a tricky step. Hold a touch sensor in place and slide an 8M cross axle through it as well as two bushes and two half bushes. The sensor will swing freely (Figure 1-44).

  41. Then secure the ends with two more bushes as shown in Figure 1-45.

    Step 40: Connecting the sensor
    Figure 1-44. Step 40: Connecting the sensor
    Step 41: Securing the assembly
    Figure 1-45. Step 41: Securing the assembly
  42. Swing the bump sensor forward and shove in a 5M axle.

  43. Add rims! Secure them in place with the 4M axles with end stops (Figure 1-47).

    Step 42: Adding the 5M axle
    Figure 1-46. Step 42: Adding the 5M axle
    Step 43: Adding rims
    Figure 1-47. Step 43: Adding rims
  44. Next, add tires as shown in Figure 1-48.

  45. Add a couple of 4M plates, secured with 3M cross axles with knobs (Figure 1-49).

    Step 44: Then, tires
    Figure 1-48. Step 44: Then, tires
    Step 45: Adding and securing the plates
    Figure 1-49. Step 45: Adding and securing the plates
  46. Add the back assembly as shown in Figure 1-50. Note that you’ll have to hold it in place until the next step!

  47. Add four more 3M cross axles with knobs, as well as two cross connectors (Figure 1-51).

    Step 46: Adding the back assembly
    Figure 1-50. Step 46: Adding the back assembly
    Step 47: Adding more axles
    Figure 1-51. Step 47: Adding more axles
  48. Add double cross blocks as shown in Figure 1-52.

  49. Add two 4M liftarms to the ends of the cross axles as shown in Figure 1-53.

    Step 48: Adding the double cross blocks
    Figure 1-52. Step 48: Adding the double cross blocks
    Step 49: Adding liftarms
    Figure 1-53. Step 49: Adding liftarms
  50. Pop in 10 cross connectors as shown in Figure 1-54. Your Bricktronics mounting plates will connect to these pegs.

  51. Add the bumper (Figure 1-55). You’re almost done!

    Step 50: Adding cross connectors
    Figure 1-54. Step 50: Adding cross connectors
    Step 51: Connecting the bumper
    Figure 1-55. Step 51: Connecting the bumper
  52. Connect the rear wheel as shown in Figure 1-56.

  53. You’re all done (Figure 1-57). Let’s add electronics and the pen! Note that the robot will want to flex a bit in the middle, but the Bricktronics mounting plate will keep it rigid.

    Step 52: Connecting the rear wheel
    Figure 1-56. Step 52: Connecting the rear wheel
    Step 53: Admire your work!
    Figure 1-57. Step 53: Admire your work!

Attach the Arduino and Bricktronics Shield

Adding the Arduino and shield are ridiculously easy. Just connect up your Mindstorms wires to the shield as seen in Figure 1-58. Don’t have a Bricktronics Shield? Don’t worry, we show you how to wire up a breadboarded equivalent in Chapter 10, Advanced Techniques.

Connect the Mindstorms wires as you see here
Figure 1-58. Connect the Mindstorms wires as you see here
These connector plates, prototyped in wood, allow you to connect your electronics to Lego beams
Figure 1-59. These connector plates, prototyped in wood, allow you to connect your electronics to Lego beams
Attach the battery pack to the robot’s platform; note that this photo shows a prototype cut out of thick wood, so the bushes aren’t necessary
Figure 1-60. Attach the battery pack to the robot’s platform; note that this photo shows a prototype cut out of thick wood, so the bushes aren’t necessary
The Arduino’s mounting plate fits on top of the battery pack and is secured by four cross connectors
Figure 1-61. The Arduino’s mounting plate fits on top of the battery pack and is secured by four cross connectors

Attach the Pen

Next, let’s connect the marking pen to the robot with the help of a clothespin. Take the machine screw we specified and attach the clothespin to one of the battery pack mounting plate’s free Technic holes. Depending on the clothespin you used, you may be able to thread the screw through the hole in the spring; otherwise, position the screw next to the spring as seen in Figure 1-62. This arrangement will give the pen the maximum flexibility to move as the robot changes direction.

Attaching the clothespin to hold the pen
Figure 1-62. Attaching the clothespin to hold the pen

Program the Robot

Coding up an Arduino sketch (as Arduino programs are called) can be surprisingly easy. You may not know how to program, or understand the rules most programming languages operate by, but getting to this point may be quicker than you think. We can’t teach you how to program in this book, but we can get you to a place where you can learn for yourself, either by following tutorials or by adapting other hackers’ programs for your own use.

Processing and Arduino

The language and development environment used to program the Arduino board is also called Arduino (Figure 1-63), and it’s inspired by another language called Processing. Casey Reas and Benjamin Fry created Processing in 2001 as a tool to get nonprogrammers such as artists interested in programming. (Processing is based on Java, while Arduino is based on C++; this means that you won’t be able to run most Processing code on Arduino or vice-versa.)

Processing features a quick turnaround between coding and results, allowing rookies the rapid gratification of seeing their Processing sketch displayed on screen after only a few seconds. As open source initiatives, Processing and Arduino encourage the sharing of code, allowing relative newbies to quickly get up to speed on how to program their boards.

For the purposes of this book, the information presented in this section is mostly informational—all you have to do is download the code for the robots in this book, though we encourage you to play around with the program. You’d be surprised what you can learn just by modifying someone else’s code! We’ll get into Arduino in much more detail in Chapter 3.

Arduino code might look scary, but it’s actually easy for nonprogrammers to learn
Figure 1-63. Arduino code might look scary, but it’s actually easy for nonprogrammers to learn

Setting Up the Programming Environment

In order to upload code to your Arduino, you must take a few minor steps to make sure you’re ready.

1) Download the Arduino Programming Environment

Your first step is to download Arduino. It’s simple! Go to http://arduino.cc/en/Main/Software and choose your operating system to download what you need. If you have an older machine, you can even grab legacy versions of the software, though we don’t necessarily encourage this.

2) Connect the Board

Use a USB A-B cable to connect your Arduino Uno (the Leonardo uses a microUSB cable) to the computer. Note that, through the magic of USB, your board will be powered through the cable, so you won’t have to worry about the power supply while you’re loading code.

3) Configure Arduino

Go to the Tools menu in the menu bar and choose your board type as well as which serial port you want to use (although Arduino uses USB, it looks like a serial port—the same kind of connection used for dialup modems). If you don’t know which serial port Arduino is using, unplug the Arduino from your computer, look at the menu, and make a note of which serial ports are in the list. Next, plug the Arduino back into your computer, and use the serial port that wasn’t there last time you looked.

4) Load the Code

Use the File menu option to load the sketch you want. Try this out now with the Blink sketch (File | Examples | 01.Basics | Blink). Upload the sketch by clicking in the right-arrow icon in the toolbar or by choosing File | Upload. One of the Arduino’s on-board LEDs will flash frantically as the code uploads, but when it’s done (it should just take a few seconds unless you have a monster sketch) you’ll be good to go!

Don’t Forget Your Libraries!

One thing many new Arduino hackers forget is to make sure they have the right libraries for their sketch. A software library is a grouping of computer code that is intended for reuse. A library can provide a layer of abstraction, reducing the need to understand every line of code inside of it.

While there are about twenty libraries that come with the Arduino software, there are many more available online. Some of them require specific hardware, but some do not. There are libraries for connecting to LCD screens, and outputting black and white TV signals. There are motor control libraries and PS2 keyboard libraries. There are libraries for generating audio, keeping track of the date and the time, and using SD cards. There are even libraries for connecting to the Internet.

They’re easy to install—simply download the library, unzip/extract it if needed, and then copy it into a libraries subdirectory of your “sketchbook” directory. To find this directory, go into Arduino’s preferences (Arduino | Preferences on Mac, File | Preferences on Linux or Windows), and note the Sketchbook Location listed there. If there is no libraries subdirectory, you’ll have to create it. Finally, every time you add a library you’ll have to exit Arduino and restart the application. There are more detailed instructions at the Arduino website if you need more help.

Arduino libraries are easy to write—if you find yourself writing the same code in multiple programs, it may make sense for you to create a library. The extra work consists of a little standard setup code, and then some labeling of what parts of the library should be able to be accessed from other programs, and which parts should be protected. There’s a good tutorial on adapting code into a library at http://arduino.cc/en/Hacking/LibraryTutorial.

The final step is to program the Arduino with the code needed to operate the Drawbot. First, however, you need to download and install the Bricktronics library. You can find it at http://www.wayneandlayne.com/bricktronics.

The Arduino Sketch

The Drawbot code is relatively simple. The main loop checks if a timeout has occurred. If it has, it randomizes the motor speeds and chooses a new random timeout. It also checks if the front bumper has been hit. If it has, it reverses the direction of both motors, slows them down a bit, and checks if the motors are going very slowly. If they are, it randomizes the motor speeds and chooses a new random timeout.

This sketch is included in the sample code that you can download for this book (see How to Contact Us in the Preface for more information on this).

With the Arduino connected to your computer with USB (and the battery pack disconnected), open the sketch up in Arduino, then upload the code by clicking in the right-arrow icon in the toolbar or by choosing File | Upload. Unplug the Arduino from the computer, plug in the battery pack, set down the robot, press the front bumper, and watch your robot go!

#include <Wire.h> 
#include <Adafruit_MCP23017.h>
#include <Bricktronics.h>

// Make: Lego and Arduino Projects
// Chapter 1: Drawbot
// Website: http://www.wayneandlayne.com/bricktronics/

long timeout = 0;

Bricktronics brick = Bricktronics(); 
Motor r = Motor(&brick, 1); 
Motor l = Motor(&brick, 2);
Button front = Button(&brick, 1); 

void setup() 
{
  randomSeed(analogRead(A3)); 
  brick.begin();
  r.begin();
  l.begin();
  front.begin();
}

void bumpers_hit() 
{
 int r_speed = r.get_speed() * -0.9;
 int l_speed = l.get_speed() * -0.9;
 r.set_speed(r_speed);
 l.set_speed(l_speed);

 delay(500);
 if (abs(l_speed) < 25 && abs(r_speed) < 25)
 {
   timeout_expired();
 }
}

void timeout_expired() 
{
  r.set_speed(random(-127, 127));
  l.set_speed(random(-127, 127));
  timeout = millis() + random(1, 10) * 1000;
}

void loop() 
{
 if (timeout != 0 && timeout < millis()) 
 {
   timeout_expired();
 }
 if (front.is_pressed()) 
 {
  bumpers_hit();
 }
}
  1. These 3 lines let the Arduino sketch use the Bricktronics library code that simplifies working with motors and sensors.

  2. The Bricktronics object manages many of the Bricktronics library calls.

  3. The r and l Motor objects correspond to the motors plugged into Motor Port 1 and 2, respectively, of the Bricktronics Shield.

  4. The front Button object corresponds to the button plugged into Sensor Port 1.

  5. The setup() function is called once, on power on. Here, it’s used to initialize all the Bricktronics objects.

  6. This line seeds the pseudorandom number generator with an analog reading from a disconnected pin, A3. This helps the numbers be more random.

  7. This function is called when the bumpers are hit. The idea is to reverse each motor, and slow it down a bit, but if it slows down too slowly, to start over with new random values, so it doesn’t get boring.

  8. This function sets the motors going at a random speed, and it determines a timeout between 1 and 10 seconds, after which it will be called again.

  9. In Arduino, your loop() function is called over and over again, until the Arduino runs out of power.

  10. If the timeout has been set, and the current time is past the timeout, run the timeout_expired() function.

  11. If the front bumper is pressed, then call the bumpers_hit() function, which reverses the robot unless the motors are going too slowly.

The Next Chapter

In Chapter 2 we’ll brush up on our Lego lore. What’s up with the Mindstorms set? When was it introduced? What do you get and what can you do with it? The answers to these questions (and more!) will bring you up to speed on this fascinating set.



[1] The parts marked with an asterisk are either not found in the Lego Mindstorms NXT 2.0 set or aren’t included in the listed quantity. Note that the quantities found in Lego sets sometimes differ from their official numbers, due to packing errors.

[2] The parts marked with an asterisk are either not found in the Lego Mindstorms NXT 2.0 set or aren’t included in the listed quantity. Note that the quantities found in Lego sets sometimes differ from their official numbers, due to packing errors.

[3] The parts marked with an asterisk are either not found in the Lego Mindstorms NXT 2.0 set or aren’t included in the listed quantity. Note that the quantities found in Lego sets sometimes differ from their official numbers, due to packing errors.

[4] The parts marked with an asterisk are either not found in the Lego Mindstorms NXT 2.0 set or aren’t included in the listed quantity. Note that the quantities found in Lego sets sometimes differ from their official numbers, due to packing errors.

[5] The parts marked with an asterisk are either not found in the Lego Mindstorms NXT 2.0 set or aren’t included in the listed quantity. Note that the quantities found in Lego sets sometimes differ from their official numbers, due to packing errors.

[6] The parts marked with an asterisk are either not found in the Lego Mindstorms NXT 2.0 set or aren’t included in the listed quantity. Note that the quantities found in Lego sets sometimes differ from their official numbers, due to packing errors.

[7] The parts marked with an asterisk are either not found in the Lego Mindstorms NXT 2.0 set or aren’t included in the listed quantity. Note that the quantities found in Lego sets sometimes differ from their official numbers, due to packing errors.

[8] The parts marked with an asterisk are either not found in the Lego Mindstorms NXT 2.0 set or aren’t included in the listed quantity. Note that the quantities found in Lego sets sometimes differ from their official numbers, due to packing errors.

[9] The parts marked with an asterisk are either not found in the Lego Mindstorms NXT 2.0 set or aren’t included in the listed quantity. Note that the quantities found in Lego sets sometimes differ from their official numbers, due to packing errors.

[10] The parts marked with an asterisk are either not found in the Lego Mindstorms NXT 2.0 set or aren’t included in the listed quantity. Note that the quantities found in Lego sets sometimes differ from their official numbers, due to packing errors.

[11] The parts marked with an asterisk are either not found in the Lego Mindstorms NXT 2.0 set or aren’t included in the listed quantity. Note that the quantities found in Lego sets sometimes differ from their official numbers, due to packing errors.

The best content for your career. Discover unlimited learning on demand for around $1/day.