482 Programming Interactivity, 2nd Edition

Gratis

0
0
728
3 months ago
Preview
Full text

SECOND EDITION

  Where those designations appear in this book, and O’Reilly Media, Inc., was aware of atrademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information con-tained herein.

Table of Contents

  1 What This Book Is For 1 Programming for Interactivity 2 The Nature of Interaction 3 Messages and Interaction 5 Interfaces and Interaction 6 Languages of Interaction 7 Design and Interaction 15 Art and Interaction 16 Data Exchange and Exploration 17 Working Process 21 2. 93 Starting with Arduino 94 Installing the IDE 95 Configuring the IDE 97 Touring an Arduino Board 71 The mouseReleased() and mouseDragged() Methods 70 The mouseX and mouseY Variables 45 Overloading Functions 58 The setup() Method 46 Objects and Properties 48 Scope 51 Review 52 3.

Preface

  The first introduces the three projects that will be used throughout this book, the second introduces some of the most common themesin creating interaction in designs and applications, and the third introduces some of the more advanced topics that you may want to explore further. Covering such a massive range of topicsmeans that this book doesn’t go into great depth about most of them, but it is filled with references to other books, websites, designers, and artists that you may find helpfulor inspiring.

What Is—and Isn’t—in This Book

  My excitement about the ideas and rapid growth of the field of interaction design is hard to contain. However, as exciting and far-reaching as interaction design is, thelimitations of time and physical book size dictate that I be selective about what is and isn’t covered in this book.

What’s In

  To help novice pro- grammers, it covers some of the core elements of programming in C and C++ for Ar-duino and openFrameworks and also covers the Processing language. We also introduce some of the basics of electronics and how computer hardware functions, as well as many tools and components that you can use with an Arduino.

What’s Not In

  Again, though,listed in them all in depth; the book mentions the Mega, the Nano, Fio, and several other boards only in passing and leaves out many of the Arduino-compatible boards that are notcreated by the Arduino team. Though these are all potentially interesting areas for artists and designers, the focus of the book is on teaching some of the theory and techniques for interactiondesign as well as the basics of hardware and programming.

Conventions Used in This Book

  Constant width Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables,statements, and keywords. Constant width bold Shows commands or other text that should be typed literally by the user.

Companion Website

Using Code Examples

  All the code included in this book is available for download from the book’s companion website, http://www.oreilly.com/catalog/9781449311445 . Copyright 2012 Joshua Noble, 978-1-449-31144-5.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com .

Safari® Books Online

How to Contact Us

  Safari Books Online is an on-demand digital library that lets you easily search over 7,500 technology and creative reference books and videos tofind the answers you need quickly. Access new titles before they are available for print, and get exclusive access to manuscripts in development and postfeedback for the authors.

Acknowledgments

  This book is a humble attempt to thank you all for everything you’ve given to me— and to every other programmer, artist, or designer interested—for working with com-puting in novel and interesting ways and bringing more people into the conversation. I would also like to extend my deepest thanks to all my interviewees for taking the time This book is as much my effort as it is the sum of the efforts of the editorial team that worked on it.

CHAPTER 1 Introducing Interaction Design The scientist and philosopher Alfred Korzybski once remarked, “The map is not the

  It’s also a territory that is becoming more and more accessible thanks to excellent projects like the ones that we’ll be exploring in the book—tools that have been created to make code and coding easier to do. This book will also give you the technicalunderstanding to know how to find information on almost any kind of project that you want to explore and what to do with that information once you find it.

What This Book Is For

  This book was created under the premise that technology and code are not tools solely for computer scientists or engineers to create applications and that no one be intimi-dated by or shy away from working with and exploring electronics, hardware, and code. Artists and designers can be interested in enabling interaction between users and be- tween applications in ways that can be accentuated by the addition of custom computerapplications or that can be realized only through the use of custom computer applica- tions.

Programming for Interactivity

  There are many styles of programming, and some tech- niques and ways of thinking about code are better suited to programming servers ordatabases than interaction. One of the great challenges in interaction design is actually creating real interactions between what you’re designing and the user who will be using it.

The Nature of Interaction

  When you give a user a way to accomplish a task or input data into the system that changes it in a substantial way and you create a means for that system to respond towhat the user is doing, then you’re creating interaction. A simple but good example of this is navigating using a mobile device: the device is constantly updating its position and displaying that back to the user and providingdirections, while the user is actively traveling and querying the device for information.

Messages and Interaction

  There is a correlation between the richness of interactive systems and the difficulty of creating it: the richer the interaction, the more that can go wrong. Popular slogans in design, like “principle of least surprise,” express the notion that the familiar interaction is the preferable interactionbecause the learning curve for the user is much more shallow than a truly novel inter- action.

Interfaces and Interaction

  If you think about how you talk to someoneon the phone versus how you talk to them in person, you’re probably using more hand gestures, facial expressions, and other forms of nonverbal communication in person It’s important to remember that interaction is more than the use of an interface. There aren’t a great deal of true revolutions in user interfaces: the creation of the key- board, Doug Engelbart’s mouse (the prototype of the mouse we know today), IvanSutherland’s sketchpad, the desktop GUI, and now the capacitive touchscreen.

Languages of Interaction

  If you think of how you delete something from the desktop with a mouse, you might say, “I select the file and drag itto the trash.” The actual actions that you’re performing when you do this are a little different from what the system understands you to be doing, but that’s not really what’s Physical manipulation These are the first interfaces that were created for electronics and some of the first designed multifunction man/machine interactions. Input using code At the dawn of the age of computing, the classic user interaction model was a terminal where a user input code commands that were then run and the resultswere reported to the screen in the form of text.

Design and Interaction

  Interaction is sometimesconfused with “doing something with a tool,” and although that’s important, it’s a little less specific than “how we do things with a tool.” Thinking about tools in terms of how, rather than just what, when, or why, isolates those things about the interaction that define the experience of doing that task. The design of an interaction is a complex process that involves a lot of modeling of how a system will work, how a user will approach the goal she’s trying to accomplish, andhow the interface needs to be configured to allow for all of these different operations.

Art and Interaction

  Deciding which end of that spectrum is more interestingto you has a lot of bearing on how you think about the interaction, but it doesn’t change the code that you write or the way that you design your hardware. You also have a great dealof control over the context of what that art is; an artwork can be viewed or experienced in any location that the user chooses, altered to become something unrecognizable, orused in a way that it was not intended to be used when it was first created.

Data Exchange and Exploration

  Again, the types listed here aren’tbeing included to make a list of types of interactive work, but to show some of the common themes that run through interactive art and design and to help you get an ideaof what you’ll be exploring in this book: Supporting data visualization Data visualization is an increasingly relevant theme given the amount of data that we as members of an increasingly information-centric society must process. It is important, though, to always consider the appropri-ateness of an application for the space in which it exists and how the user engages Telling a narrative or story One of the more interesting themes beginning to emerge in interactive design is the notion of using interaction to tell a story or narrative.

Working Process

  The actual process of creating interactive work generally follows a combination of any of the following processes: Conception Conception can consist of sketches in a notebook, a daydream, a product or process of research or something developed in consultation with a client who wants theapplication for commercial purposes, or any combination of the three. You should try to map out in as much detail as possible what you would like the applicationto do, how the interaction should feel to the user, and the goals of the application.

CHAPTER 2 Programming Basics Writing code is never extremely easy; however, it is also not as difficult as you might

  The first says, “I just want it to work.”For you, this chapter will explain just enough that you’ll be able to follow along with the examples in this book and the ones that you find online, and be able modify themslightly to get them to do what you need them to do. If you are familiar with the basics of these languages, you might want to skip ahead to the chapters on the toolsthemselves or to Chapter 5 for some more advanced material on programming.

Why You’ll Read This Chapter More Than Once In all likelihood, the first time you read this chapter, some of it will not make sense

The Nature of Code

  Of course, the goal throughout this book is to try toprovide code that will just work and thereby satisfy the first kind of reader, those of you who simply want it to work and be done with it. You can imagine the process of writingcode as a series of translations in which you tell the compiler what you want to do with the program that it will create in a high-level programming language likeProcessing or C++ and the compiler then creates a machine language file that will run that file.

Variables

  That’s a little different than the algebra example because that example didn’t need to say that x is going to be a number; it just says, “x is anumber.” If you wanted to use code to make a number called x and use it as a variable, you would do it like this: int x; The int indicates (or sets) the type of the variable. The kind of variable is called its type; types are dealt with a lot more in the next section, so for right now, let’s concen- trate on getting the basics of variables down: int x = 5; This code creates a variable named x that is an integer and has the value of 5 .

Simple Types

  That’s why if you run the following snippet of code through a C++ compiler or through Processing or Arduino, it’ll happily say thatcis 195:char a = 'a'; char b = 'b';int c = a+b; // notice that a+b is being stored as an int You can store the result of two characters being added together if you store the value ofthe result as an int because adding the characters together is really adding the numbers that they are stored as together. Bytes are a convenient datatype for sending information that can’t or shouldn’t be represented by strings or other kindsof numbers such as the contents of a file, data sent to or from hardware, data about the pixel of an image, or a millisecond of sound.

Arrays The array is a slightly more complex datatype than the ones that were shown earlier

  When you want to access an element in the array, you use the access operators [] to access the indexposition in the array that is specified within the square brackets: int x = numbers[0];x 1 numbers 1 The previous sets to , because the first item in our array is :int y = numbers[1] + numbers[2]; The previous sets y to the values of the second plus the third elements of numbers , that = is, 2 + 3, which equals 5. If you use the operator in front of the array with the access operator, it sets the value of the element in the array at that point: numbers[0] = 1; numbers[0] = 5; 1 , it is now 5 .

Casting

  Forinstance, if you want to cast a char to a float and then back, you do the following: char ch = 'f'; int fAsInt = (int)ch;// now fAsInt is 102char newChar = char(fAsInt); // newChar is now 'f' One important thing to note is that you cannot cast an array: char[] foo = {'a', 'b', 'c', 'd'}; int[](foo); // ERROR To cast anything in an array, you need to cast every element of the array. We’ll cover this in greater detail in the sections on loops, but for now, we’ll look at this: char[] foo = {'a', 'b', 'c', 'd'}; int i = int(foo[0]); Here you create an array of char variables and then read one of those char values out of the array and cast it as an int.

Operators

  &&Checks the truth of the expression to the left of the operator and to the right; if both are true, the entire expression istrue . ||Checks the expression to the left of the operator and to the right of the operator; if either is true, the entire expression is true .

Control Statements

  This is going to be particularly useful when dealing with the pixels in images or frames of video, as well as sounds, data from the Internet, and manyother kinds of information that needs to be sorted through: true ; otherwise, you don’t do anything. For instance, if you wanted to loop through a certain number ofitems and process only odd numbers, you could do this: for(int i = 0; i< 10; i++) { if( i % 2 == 0){continue; }println(i + " is not divisible by 2"); } This will print the following: 1 is not divisible by 2 3 is not divisible by 25 is not divisible by 2 7 is not divisible by 29 is not divisible by 2 The continue statement here starts the loop over again.

Functions

  A function is a name for a grouping of one or more lines of code and is somewhat like a variable in that it has a type and a name. Going back to the basic algebra analogy you saw earlier when first looking at variables, a variable is something like this: x A function is something more like an instruction with something that is given at the beginning of the instruction and something that is expected in return.

Defining a Function

  To turn the written example into code, you would define a variable to be used to keep track of all the money that you have: int myBank = 0; Then you create a function that takes money, adds it to myBank , and returns that value: int moneyReceived(int money){ myBank += money;return myBank; } Now, you have defined a function called moneyReceived() . Declaring a function Notice that the return statement is returning something that is of the same type as the type listed in front of the function name.

Passing Parameters to a Function

  Both of the following examples are legal: moneyReceived(4); or: int priceOfDinner = 17; moneyReceived(priceOfDinner); This next one is not legal: float f = 1.32; moneyReceived(f); because the variable being passed to the function is not the correct type. The return statement indicates the type of value that the method will return, just as a type for a variable determines what kind of value the variable will store.

Some Suggestions on Writing Functions

  A function called square is very well named if it takes an int or float as a parameter and returns the square of that value. The less stuff you have to look at, the more quickly you’ll be able to find things, locateproblems, and remember where you left off in a piece of code.

Overloading Functions

  The compiler treats functions that sameway, which makes it easier for us to name functions with the same functionality by the same name and rely on the compiler to differentiate between them using the contextof the kinds of parameters passed. Here it is in Processing: println(multiplyByTwo('z'));// this will print ô println(multiplyByTwo(5)); // this will print 10println(multiplyByTwo("string"));// this will print stringstring int[] foo = {1, 2, 3, 4};println(multiplyByTwo(foo));//this will print 2, 4, 6, 8 Overloading functions is a great tool because it allows you to make a single way to do something and modify it slightly to take different kindsof variables as parameters.

Objects and Properties

  For the moment, you want to focus on these two lines: img.x = 300; // set the x position of the image img.y = 300; // set the y position of the imagePImage x What you know after looking at these lines is that the has an property and a y property. You’ll need to read the rest of the PImage documentation on the Processingwebsite to know what parameters you need to pass to each of these functions, but the s shown in Figure 2-7 for the first function, you see several parameters with an appended to them and several with a d appended to them.

Scope

  If you have a variable within a function, you have this:void someFunction() { int anInt;} The variable anInt is going to exist in that function, until the closing bracket for the } function, which is the at the end of the function. Variables have a type that describes what kind of information can be stored in them and specified when the variable is declared, for instance: int weight = 150; or: float f = 1.12; Variables are declared and then initialized.

CHAPTER 3 Processing Processing was one of the first open source projects that was specifically designed for

  One of the reasons that we brought up the Java Virtual Machine (JVM) in the intro- duction is that Processing is a Java application; that is, it runs in the JVM. In this chapter, we’ll cover the basics of getting started with Processing, including the following: downloading and installing the environment, writing some simple pro-grams, using external libraries that let you extend what Processing is capable of, and running applications on the Internet and on the desktop.

Downloading and Installing Processing

  Download the appropriate archive for your operating system, and move the files in the archive to somewhere you normally store applications. Go ahead and start the application, and then type the followingsimple program in the window.

Exploring the Processing IDE

  As you can see in Figure 3-1 , the Processing IDE has four main areas: the controls, the Code window, the Messages window, and the Console window. After you’ve entered any code in the Code window and you’reready to see what it looks like when it runs, click the Run button, which opens a new window and runs your application in that window.

The Basics of a Processing Application

  The second, draw() , is invoked over and over again from right after startup until the application closes. Let’s take a look at the first of these and dissectwhat a method really is.

The setup() Method

  In terms of our Processing application, the setup() method makes sure any information you want to use in the rest of the application is preparedproperly, as shown in Example 3-2 . Well, the number you pass to the frameRate() method is the number of times per second that the draw() method is called.

The draw() Method

  You could also write x = x+2; , but the following is simpler and does the same thing: x += 2;x Now that you’ve made a little bit bigger, you can use it to draw a circle into the window: ellipse(150, 150, x, x); Look ahead in this chapter to the section “The Basics of Drawing withProcessing” on page 63 for more information about the ellipse() method. If the value of x is too high, the circle will be drawn too large for it to show up correctly in your window (300 pixels); you’ll want to reset x to 0 so that the circles placed in thewindow begin growing again in size: if(x > 300) { x = 0;} } In Figure 3-3 , you can see the animation about halfway through its cycle of incrementing the x value and drawing gradually larger and larger circles.

The Basics of Drawing with Processing

  Because Processing is a tool for artists, one of the most important tasks it helps you do easily is drawing. You’ll find much more information on drawing using vectors andbitmaps in 9 and 10 , and you’ll find information about OpenGL, some of the basics of 3-D, and how to create complex drawing systems in learn how to draw simple shapes, draw lines, and create colors to fill in those shapes and lines.

The rect(), ellipse(), and line() Methods

  This keeps in line with the general rule in computer graphics of referring to the upper-left corner as 0,0 (to anyone with a math background this is a little odd, sinceCartesian coordinates have the y values flipped). Finally, the line() method uses the following syntax: line(x1, y1, x2, y2)x1 y1x2 y2 The and values define where the line is going to start, and the and values define the end of the line.

RGB Versus Hexadecimal

  For example, the following defines white: int fullred = 255; int fullgreen = 255;int fullblue = 255; color(fullred, fullgreen, fullblue); Conversely, the following defines black: int fullred = 0; int fullgreen = 0;int fullblue = 0; color(fullred, fullgreen, fullblue); All red and no green or blue is red, all green and blue and no red is yellow, and anytime all the numbers are the same the color is a gray (or white/black). The alpha value controls the transparency of a color and is indicated in hexadecimal by putting two more numbers at the beginning of the number to indicate, on a scale of 0–255 (which is really 0–FF), how transparent the color should be.

The fill() Method

  fill() The method has many different ways of letting you set the color that will be used to fill shapes: fill(int gray) This is an int between 0 (black) and 255 (white).fill(int gray, int alpha) This is an int between 0 (black) and 255 (white) and a second number for the alpha of the fill between 0 (transparent) and 255 (fully opaque). fill(color color) The fill() method can also be passed a variable of type color , as shown here: void draw(){ color c = color(200, 0, 0);fill(c); rect(0, 0, 100, 100);}fill(color color, int alpha) When passing a variable of type color , you can specify an alpha value: This is a fill using a hexadecimal value for the color, which can be represented by using the 0x prefix or the # prefix in the hexadecimal code.

The background() Method

  To set the color of the background window that your application is running in, use the background() method. The background() method uses the same overloaded methods as the fill() method, with the method name changed to background() , of course.

The line() Method

  The first is for any two-dimensional lines: line(x1, y1, x2, y2) The second is for any three-dimensional lines: line(x1, y1, z1, x2, y2, z2) Now, of course, a three-dimensional line will simply appear like a two-dimensional line until you begin moving objects around in three-dimensional space; we’ll cover that in line from the point described in the first two (or three parameters) to the point. You can set the color of the line using the stroke() method, and thickness of the line usingthe strokeWeight() method.

The stroke() and strokeWeight() Methods

  The stroke() method uses the same parameters as the fill() method, letting you set the color of the line either by using up to four values from 0 to 255 or by using hexa-decimal numbers. strokeWeight.pdevoid draw(){ stroke(0xFFCCFF00); // here we set the color to yellowstrokeWeight(5); // set the stroke weight to 5 // draw the linesline(0, 100, 600, 400); line(600, 400, 300, 0);line(300, 0, 0, 100); } This draws a rectangular shape with yellow lines, 5 pixels thick.

The curve() Method

  The curve() method draws a curved line and is similar to the line() method except it requires you to specify anchors that the line will curve toward. The x3 , y3 , and z3 parameters are the coordinates for the second point, that is, where the line ends, and the x4 , y4 , and z4 parameters are the coordinates for the second anchor, that is, the second point that the curve will bend toward.

The vertex() and curveVertex() Methods

  In Processing, you can use any three or morevertices to create a shape with or without a fill by calling the beginShape() method, endShape() beginShape() creating the vertices, and then calling the method. Example 3-8 creates three vertices:one at 0, 0, which is the upper-left corner of the window; one at 400,400, which is the lower-right corner of the window; and one at the user’s mouse position.

Capturing Simple User Interaction

  To capture interactions withthese two tools, what you really need to know is when the mouse is moving, when the mouse button has been pressed, when the user is dragging (that is, holding the mousebutton down and moving the mouse), whether a key has been pressed, and what key has been pressed. All you need to do is invoke them, that is, to tell the Processing environment that you want to do something when the method is invoked, or access the variableeither when one of the methods is invoked or in the draw() method of your application.

The mouseX and mouseY Variables

  If the mouse pointer is in the lower-right corner of a window that is 300 × 300 pixels, then mouseX is 300 and mouseY is 300. You do this by using the text() method, which takes three parameters:void text(string message, xPosition, yPosition); The first parameter is the message, and the second and third parameters can be floats or ints and are for positioning the location of the text.

The mousePressed() Method

  First, you have the declaration of the name of the class, Point , and the bracket that indicates you’re about to define all the methods and types of that class: class Point{ Next, you have the two values that are going to store the x and y values of Point : float x; float y; Here is the constructor for this class: Point(float _x, float _y){ x = _x;y = _y; } The constructor takes two values, _x and _y , and sets the x and y values of Point to the two values passed into the constructor. Let’s change the Point class con- structor slightly so you can see it better: Point(float _x, float _y){ println(" x is: "+_x+" and y is "+_y);x = _x; y = _y;} Now, when you click in the Processing window, you’ll see the following printed out in the Console window (depending on where you click, of course): x is: 262.0 and y is 51.0 x is: 234.0 and y is 193.0x is: 362.0 and y is 274.0 x is: 125.0 and y is 340.0x is: 17.0 and y is 155.0 So, why is this happening?

Downloading Libraries

  To change the sketchbook location, youcan open the Preferences window from the Processing application and set the value in the “Sketchbook location” field. Once the library is in the correct location, restart the Processing IDE, and type the following code in the IDE window: import controlP5.*; Then run the application.

Loading and Displaying Images

  image.pdePImage img; void setup() {size(400, 400); img = loadImage("sample.jpg");image(img, 0, 0); } As soon as the setup() method is called, the window is given a size, the sample.jpg file is loaded into the PImage , and the PImage is placed in the window at the 0,0 position(that is, in the upper-left corner of the window). Like so many methods in Processing, the method is overloa- ded, letting you pass optional width and height values that will size the image: image(img, x, y, width, height) By default, the image is displayed in the Processing window at its default height and width, but you can also set the height and width of the image.

Displaying Videos in the Processing Environment

Using the Movie Class

  The movieEvent() method is the QuickTime playernotifying the Processing environment that a frame is ready to be displayed in much the mousePressed() same way that the method is the machine notifying the Processing en- vironment that the mouse has moved. This reads the information for the frame into the Movie class and prepares the frame for display in the Processing environment: void movieEvent(Movie m) { m.read();} To draw the current frame of the movie into the window, you use the image() method PImage again just the same as you did for a that contained all the information for a picture: void draw() { image(mov, 0, 0);} This draws the current frame of the movie into the 0,0, or upper-left, corner of the window.

Reading and Writing Files

  To load a picture, loadImage() you would use the method; to load a simple text file, you would use the loadStrings() method; and to load a file that isn’t a text file, you would use the load Bytes() method. First, you makean array of strings: String[] lines = new String[4]; lines[0] = "hello";lines[1] = "out"; lines[2] = "there";lines[3] = "!"; After creating an array, you can write the data back to a file by passing its name to the saveStrings() method:saveStrings("data/greeting.txt", lines); This creates and saves a file called greeting.txt with each element from the lines array on a separate line in the file.

Running and Debugging Applications

  To run your application, simply click the Run button in the Processing IDE; you’ll see the output shown in Figure 3-8 . Viewing an error in the Message window You’ll see the following in the Console window: Perhaps you wanted the overloaded version "void frameRate(float $1):" instead?

Exporting Processing Applications

  Now, while running and debugging certainly helps when you want to see how the application is doing and check for errors in the code, it doesn’t much help when you’retrying to share it with a friend. If you have a friend who has a Windows computer that you want to send theProcessing application to, you would simply compress the folder and all the files it contains into an archive and send it to that person.

Conclusion

  Processing defines mouseX and mouseY variables to report the position of the user’s mouse, as well as a key variable and a keyPressed() method to help you capture theuser’s keyboard input. Once thelibrary has been loaded, you can use it in your application with the import statement to import all of its information, as shown here: import ddf.minim.*; // just an example, using Minim The PImage object and loadImage() method allow you to load image files into your Processing application and display and manipulate them.

CHAPTER 4 Arduino The word Arduino refers to three separate tools, which, bundled together, create the

  Second, there is the language and compiler, which creates code for this microcontroller, and which, much like the Processing lan-guage, simplifies many of the tasks that challenge designers and developers alike when working with hardware and physical interaction. It’s a goal, and that goal is to simplify the creation of interactive applications or objects by simplifying the programming languageused to create instructions and by providing a powerful yet basic controller that can easily be used for many common programming tasks while still being robust enoughto support more complex projects.

Starting with Arduino

  There is also the Arduino Nano, Pro, and the Pro Mini, all of which are smaller and easier to operate; you might explore these later after you’ve grown morecomfortable with the Arduino. USB A (left) and USB B (right) cables You’ll use the USB cable to connect the Arduino controller to your computer, since theArduino controller connects only with the USB B (the square shape), and most com- puters use only the USB A (the rectangular shape).

Installing the IDE

  Windows The easiest way to install the Windows drivers for the Arduino controller is simply to plug the controller in to your computer and wait for the Found New Hardware Wizardto appear. Selecting devices Continue to the “Please choose your search and installation options” window, and add the location of the drivers folder to the locations that Windows will search for the driverby adding it to the “Search for driver software in this location” field, as shown in Figure 4-4 .

Configuring the IDE

  To select the board, go to Tools →Board, and select the board type, as shown in Figure 4-5 . Selecting a port on Mac OS X On a Windows computer, the ports will have the word COM in the title.

Touring an Arduino Board

  Now that you know how to install the Arduino IDE and drivers, you can move on to looking at the boards themselves. Since the Uno is the easiest and most straightforwardof the boards, we’ll contrast that one with some of the other Arduino controllers so you understand not only what the Uno is, but what makes it unique.

The Controller

Uno Versus Mini Versus Mega

  Of course, all of these things are on a far smaller scale than a laptop or desktop computer, which means thatthe engineering is quite different in some respects, and there are many different issues that you need to consider with a microcontroller that you would not need to considerwith a normal computer, particularly when working with powering other devices and powering the controller itself. These function in the same way as the connectors on the Uno, butwhere you can simply insert a wire into the Uno, you’ll need to insert the Mini into a prototyping board and then attach a wire to the same line on the board, as shown in Figure 4-10 .

Touring the Arduino IDE

  If you select the Stepper library, for example, you’ll see the followingline appear in the code window: #include <Stepper.h> This imports the Stepper library into the project, making all of its functionality available to your application. You should see the TX and RX lights on your con-troller blink as the code is being uploaded and the memory for the program initialized, and you’ll then see a message displayed in the Console window of the IDE that sayssomething like this: Binary sketch size: 1092 bytes (of a 14336 byte maximum) If that works, you’ll see the LED on your board start blinking, and you’re ready for the next section.

The Basics of an Arduino Application

  In fact, the Arduino language is structured quite similarly to the Processing language with regard to how the application itself is structured. Almostall Arduino applications consist of the declaration of some variables that will be needed throughout the lifetime of the application, one-time initialization to set things up readyto run, and functions to use in the main loop.

The setup Statement

The loop Method

  The loop() method contains anything that needs to happen repeatedly in the applica- tion; that could be checking for a new value from a control, sending information to acomputer, sending a signal to a pin, or sending debug information. Recall that if a variable is declared within a method, then it exists only setup This element contains the code to configure the pin for the button to receive in- formation from a control and set the pin for the light to send information.

Features of the Arduino Language

  This means that while C++ may not be friendly to read and write for the new programmer, it certainly is stingy with its resources,making it perfect for doing things on a microcontroller where resources are more limited than on a desktop machine or laptop. Now, it’s important to note that Arduino is not quite C++, which is to say that if you find some neat C++ code somewhere that youwant to run, pasting it into the Arduino IDE and expecting it to work might lead to disappointment.

Constants

  These make your code more readable: Remember that the digital pins of the Arduino controller can be set to either input or output, which is to say that they’ll send values to a controller or receive valuesfrom a controller. These are predefined, never change, and are always available: false and true You can always use true/false The Arduino language has the following constant variables that can be used throughout any Arduino application: Some of the other features of the Arduino language aren’t going to be so immediately familiar, but the next few paragraphs will help explain some of the more importantones.

Methods

  This means that the value sent to this method can be used as an adjustable voltage andsent through the pin to any controller on the side: analogWrite(11, 122);delay(ms) This method tells the program to wait for a given number of milliseconds before executing the next instruction. This can be useful if you need to keep track of time, which you can do by storing theresult of the millis call and then comparing with another millis call at some later point, as shown here: long timer = 0; void setup() {timer = millis();// get the timer the first time }void loop() { int lengthOfALoop = millis() - timer; // compare ittimer = millis(); // now set the timer variable again } Of course, you might want to do something more interesting with millis , but it’s a start.

Arrays

  Arduino treats arrays in much the same way as C++ and somewhat like Processing, though you cannot use the constructor with an array as with Processing. The same rulesabout what can be stored in the array apply: int intArray[10]; // now the array is ready, no need to call new Array() intArray[4] = 4;intArray[3] = "hello!"; // doesn't work!

Strings

  A couple of his students joined the discussion, and one of them, David Mellis, started to craft the software in a very neat way, wrapping functionality togetherin a way that was very easy for people without a true technical background to under- stand. We want to help people make their own pieces, and that requires an extra effort in How do you see the relationship between industrial design and engineering and fine arts and more visual design changing now and also in the next few years?

How to Connect Things to Your Board

  There are lots of situations in electronics where you don’twant to use a prototyping board because they can allow stray current to leak around places you might not want it, but since the controller of the Arduino is already some-what protected, a breadboard is fine to use. The rows on the edge of the board travel the length of the board, as you can see in Figure 4-19 .

Resistors

  You can read the resistor by looking at the colored stripes on the bodyof the resistor, called the resistor color code, but they’re difficult to understand at first. Now the math: the ratio of the voltage applied across resistor’s terminals to the intensity of current flowing through the resistor is called resistance.

Hello World

  To get this to Once you’ve attached the pin to the controller, put the following in the code window of the IDE, and click Run. We’re going to use the INPUT mode of the pin that a button is connected to so we can send a signal and control the LED with the button, as shown in Example 4-3 .

Debugging Your Application

  Uploading code to the Arduino boardSerial print() to monitor, you can use the method to allow you to check the values of variables or the execution of code and see those messages in real time using the Serialwindow of the Arduino IDE. Once you’ve called the begin() method of the serial,you can send data from your Arduino controller to your computer using the print() method: Serial.print(data) The print() method is more or less like the Processing print() method that you en- countered in Chapter 3 and the printf() you’ll encounter in Chapter 6 , but it is opti- mized to save space for Arduino and so works slightly differently.

Running Your Code

  Once you have loaded your program onto the board, it is saved in the program memory of the board whether the board is being powered or not. You can clear the RAM memory of the board either by grounding the reset pin, which works on the Uno and the Mini, or by simply pressing the reset button, which worksonly on the Uno.

Running Your Board Without a USB Connection

  You’ve seen the beginnings of the Arduino; now you can either flip ahead to Chap- ter 8 , where you will work with the Arduino to create some real interactivity, or you can read the next chapter, which delves a little deeper into programming to get you ready for openFrameworks and C++. The Arduino project is several different components: a microcontroller board, a sim- plified version of C and C++ for nonengineers to use in programming their microcon-troller, and an IDE and compiler used to create and load code onto the microcontroller board.

Dokumen baru