epubjs
Version:
Render ePub documents in the browser, across many devices
724 lines (423 loc) • 31 kB
HTML
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta charset="utf-8"/>
<title>Getting Started with Processing</title>
<script type="text/javascript">
if(!window.atlasplugins) window.atlasplugins = {}
atlasplugins.codeMirrorSettings = {
theme: "3024-day"
}
</script>
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700" rel="stylesheet" type="text/css"> </link>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script>
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"> </script>
<link rel="stylesheet" type="text/css" href="theme/html/html.css"/>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/4.4.0/codemirror.min.css"/>
<link rel="stylesheet" type="text/css" href="https://d2uogd9jz9k9zm.cloudfront.net/processingjs-0.0.3.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"> </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/4.4.0/codemirror.min.js" type="text/javascript"> </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/4.5.0/mode/clike/clike.min.js" type="text/javascript"> </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js" type="text/javascript"> </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/processing.js/1.4.8/processing.min.js" type="text/javascript"> </script>
<script src="https://d2uogd9jz9k9zm.cloudfront.net/processingjs-0.0.3.min.js" type="text/javascript"> </script>
<script type="text/javascript">
$(function() {
// Make all non runnable examples readonly codemirrors
$('pre:not(*[data-executable], .CodeMirror pre)').each(function(i, el) {
var textArea = $('<textarea>' + el.innerHTML + '</textarea>')
$(el).replaceWith(textArea);
var editor = CodeMirror.fromTextArea(textArea[0], {
mode: "text/x-java",
theme: "3024-day",
readOnly: true,
viewportMargin: 0
});
});
});
</script>
<style type="text/css">
/* This needs to come last to set auto height, and html.css is always included first */
.CodeMirror {
height: auto;
font-size: 14px;
padding: 15px;
border-radius: 5px;
}
.CodeMirror-scroll {
overflow-y: hidden;
overflow-x: auto;
height: auto;
}
</style>
<script type="text/javascript" src="theme/html/epub.js"> </script>
<script type="text/javascript" src="theme/html/reader.js"> </script>
</head>
<body data-type="book" id="viewer">
<section data-type="chapter" data-pdf-bookmark="Chapter 11. Extend" id="extend">
<h1>Extend</h1>
<p>This book focuses on using Processing for interactive graphics, because that’s the core of what Processing does. However, the software can do much more and is often part of projects that move beyond a single computer screen. For example, Processing has been used to control machines, export images for high-definition films, and export models for 3D printing.</p>
<p>Over the last decade, Processing has been used to make music videos for Radiohead and R.E.M., to make illustrations for publications such as <em>Nature</em> and the <em>New York Times</em>, to output sculptures for gallery exhibitions, to control a 120×12-foot video wall, to knit sweaters, and much more. Processing has this flexibility because of its system of libraries.</p>
<p>A Processing <em>library</em> is a collection of code that extends the software beyond its core functions and classes. Libraries have been important to the growth of the project, because they let developers add new features quickly. As smaller, self-contained projects, libraries are easier to manage than if these features were integrated into the main software.</p>
<p>In addition to the libraries included with Processing (these are called the <em>core</em> libraries), there are over 100 <em>contributed</em> libraries that are linked from the Processing website. All libraries are listed online at <a href="http://processing.org/reference/libraries/"><em class="hyperlink">http://processing.org/reference/libraries/</em></a>.</p>
<p>To use a library, select Import Library from the Sketch menu. Choosing a library will add a line of code that indicates that the library will be used with the current sketch. For instance, when the OpenGL Library is added, this line of code is added to the top of the sketch:</p>
<pre data-type="programlisting">import processing.opengl.*;</pre>
<p>Before a contributed library can be imported through the Sketch menu, it must be downloaded from its website and placed within the <em>libraries</em> folder on your computer. Your <em>libraries</em> folder is located in your sketchbook. You can find the location of your sketchbook by opening the Preferences. Place the downloaded library into a folder within your sketchbook called <em>libraries</em>. If this folder doesn’t yet exist, create it.</p>
<p>As mentioned, there are more than 100 Processing libraries, so they clearly can’t all be discussed here. We’ve selected a few that we think are fun and useful to introduce in this chapter.</p>
<section data-type="sect1" data-pdf-bookmark="3D" id="d">
<h1>3D</h1>
<p>There are two ways to draw in 3D with Processing; both require adding a third parameter to the <em>size()</em> function to change the way graphics are drawn. By default, Processing draws using a 2D renderer that is very precise, but slow. This is the <em>JAVA2D</em> renderer. A sometimes faster but lower-quality version is <em>P2D</em>, the Processing 2D renderer. You can also change the renderer to Processing 3D, called <em>P3D</em>, or OpenGL, to allow your programs to draw in one additional dimension, the z-axis (see <a data-type="xref" href="#processing_apostrophy_s_3d_coordinate_sy">Figure 11-1</a>).</p>
<p>Render with Processing 3D like this:</p>
<pre data-type="programlisting">size(800, 600, P3D);</pre>
<p>And OpenGL like this:</p>
<pre data-type="programlisting">size(800, 600, OPENGL);</pre>
<figure id="processing_apostrophy_s_3d_coordinate_sy">
<img src="images/Fig_11_01.png" alt="Fig 11 01"/>
<figcaption>Processing’s 3D coordinate system.</figcaption>
</figure>
<p>The <em>P3D</em> renderer is built-in, but the OpenGL renderer is a library and requires the <em>import</em> statement within the code, as shown at the top of <a data-type="xref" href="#example_11-1_colon_a_3d_demo">“Example 11-1: A 3D Demo”</a>. The OpenGL renderer makes use of faster graphics hardware that’s available on most machines sold nowadays.</p>
<div data-type="note">
<p>The OpenGL renderer is not guaranteed to be faster in all situations; see the <em>size()</em> reference for more details.</p>
</div>
<p>Many of the functions introduced in this book have variations for working in 3D. For instance, the basic drawing functions <em>point()</em>, <em>line()</em>, and <em>vertex()</em> simply add z-parameters to the x- and y-parameters that were covered earlier. The transformations <em>translate()</em>, <em>rotate()</em>, and <em>scale()</em> also operate in 3D.</p>
<section data-type="sect2" data-pdf-bookmark="Example 11-1: A 3D Demo" id="example_11-1_colon_a_3d_demo">
<h2>Example 11-1: A 3D Demo</h2>
<p>More 3D functions are covered in the Processing Reference, but here’s an example to get you started:</p>
<figure>
<img src="images/Ex_11_01.png" alt="Ex 11 01"/>
<figcaption/>
</figure>
<pre data-type="programlisting">import processing.opengl.*;
void setup() {
size(440, 220, OPENGL);
noStroke();
fill(255, 190);
}
void draw() {
background(0);
translate(width/2, height/2, 0);
rotateX(mouseX / 200.0);
rotateY(mouseY / 100.0);
int dim = 18;
for (int i = -height/2; i &lt; height/2; i += dim*1.2) {
for (int j = -height/2; j &lt; height/2; j += dim*1.2) {
beginShape();
vertex(i, j, 0);
vertex(i+dim, j, 0);
vertex(i+dim, j+dim, -dim);
vertex(i, j+dim, -dim);
endShape();
}
}
}</pre>
<p>When you start to work in 3D, new functions are available to explore. It’s possible to change the camera, lighting, and material properties, and to draw 3D shapes like spheres and cubes.</p>
</section>
<section data-type="sect2" data-pdf-bookmark="Example 11-2: Lighting" id="example_11-2_colon_lighting">
<h2>Example 11-2: Lighting</h2>
<p>This example builds on <a data-type="xref" href="#example_11-1_colon_a_3d_demo">“Example 11-1: A 3D Demo”</a> by replacing the rectangles with cubes and adding a few types of lights. Try commenting and uncommenting different lights to see how each works by itself and in combination with others:</p>
<figure>
<img src="images/Ex_11_02.png" alt="Ex 11 02"/>
<figcaption/>
</figure>
<pre data-type="programlisting">import processing.opengl.*;
void setup() {
size(420, 220, OPENGL);
noStroke();
fill(255);
}
void draw() {
lights();
//ambientLight(102, 102, 102);
//directionalLight(255, 255, 255, // Color
// −1, 0, 0); // Direction XYZ
//pointLight(255, 255, 255, // Color
// mouseX, 110, 50); // Position
//spotLight(255, 255, 255, // Color
// mouseX, 0, 200, // Position
// 0, 0, −1, // Direction XYZ
// PI, 2); // Concentration
rotateY(PI/24);
background(0);
translate(width/2, height/2, −20);
int dim = 18;
for (int i = -height/2; i &lt; height/2; i += dim*1.4) {
for (int j = -height/2; j &lt; height/2; j += dim*1.4) {
pushMatrix();
translate(i, j, -j);
box(dim, dim, dim);
popMatrix();
}
}
}</pre>
<p>There are four types of lights in Processing: spot, point, directional, and ambient. Spot lights radiate in a cone shape; they have a direction, location, and color. Point lights radiate from a single point like a lightbulb of any color. Directional lights project in one direction to create strong lights and darks. Ambient lights create an even light of any color over the entire scene and are almost always used with other lights. The <em>lights()</em> function creates a default lighting setup with an ambient and directional light. Lights need to be reset each time through <em>draw()</em>, so they should appear at the top of <em>draw()</em> to ensure consistent results.</p>
<p>Working in 3D introduces the idea of a “camera” that is pointed at the three-dimensional scene being constructed. Like a real-world camera, it maps the 3D space into the flat 2D plane of the screen. Moving the camera changes the way Processing maps the 3D coordinates of your drawing onto the 2D screen.</p>
</section>
<section data-type="sect2" data-pdf-bookmark="Example 11-3: The Processing Camera" id="example_11-3_colon_the_processing_camera">
<h2>Example 11-3: The Processing Camera</h2>
<p>By default, Processing creates a camera that points at the center of the screen, therefore shapes away from the center are seen in perspective. The <em>camera()</em> function offers control over the camera location, the location at which it’s pointed, and the orientation (up, down, tilted). In the following example, the mouse is used to move the location where the camera is pointing:</p>
<figure>
<img src="images/Ex_11_03.png" alt="Ex 11 03"/>
<figcaption/>
</figure>
<pre data-type="programlisting">import processing.opengl.*;
void setup() {
size(420, 220, OPENGL);
noStroke();
}
void draw() {
lights();
background(0);
float camZ = (height/2.0) / tan(PI*60.0 / 360.0);
camera(mouseX, mouseY, camZ, // Camera location
width/2.0, height/2.0, 0, // Camera target
0, 1, 0); // Camera orientation
translate(width/2, height/2, −20);
int dim = 18;
for (int i = -height/2; i &lt; height/2; i += dim*1.4) {
for (int j = -height/2; j &lt; height/2; j += dim*1.4) {
pushMatrix();
translate(i, j, -j);
box(dim, dim, dim);
popMatrix();
}
}
}</pre>
<p>This section has presented the tip of the iceberg of 3D capability. In addition to the core functionality mentioned here, there are many Processing libraries that help with generating 3D forms, loading and exporting 3D shapes, and providing more advanced camera control.</p>
</section>
</section>
<section data-type="sect1" data-pdf-bookmark="Image Export" id="image_export">
<h1>Image Export</h1>
<p>The animated images created by a Processing program can be turned into a file sequence with the <em>saveFrame()</em> function. When <em>saveFrame()</em> appears at the end of <em>draw()</em>, it saves a numbered sequence of TIFF-format images of the program’s output named <em>screen-0001.tif</em>, <em>screen-0002.tif</em>, and so on, to the sketch’s folder. These files can be imported into a video or animation program and saved as a movie file. You can also specify your own file name and image file format with a line of code like this:</p>
<pre data-type="programlisting">saveFrame("output-####.png");</pre>
<div data-type="note">
<p>When using <em>saveFrame()</em> inside <em>draw()</em>, a new file is saved each frame—so watch out, as this can quickly fill your <em>sketch</em> folder with thousands of files.</p>
</div>
<p>Use the <code>#</code> (hash mark) symbol to show where the numbers will appear in the file name. They are replaced with the actual frame numbers when the files are saved. You can also specify a subfolder to save the images into, which is helpful when working with many image frames:</p>
<pre data-type="programlisting">saveFrame("frames/output-####.png");</pre>
<section data-type="sect2" data-pdf-bookmark="Example 11-4: Saving Images" id="example_11-4_colon_saving_images">
<h2>Example 11-4: Saving Images</h2>
<p>This example shows how to save images by storing enough frames for a two-second animation. It runs the program at 30 frames per second and then exits after 60 frames:</p>
<figure>
<img src="images/Ex_11_04.png" alt="Ex 11 04"/>
<figcaption/>
</figure>
<pre data-type="programlisting">float x = 0;
void setup() {
size(720, 480);
smooth();
noFill();
strokeCap(SQUARE);
frameRate(30);
}
void draw() {
background(204);
translate(x, 0);
for (int y = 40; y &lt; 280; y += 20) {
line(-260, y, 0, y + 200);
line(0, y + 200, 260, y);
}
if (frameCount &lt; 60) {
saveFrame("frames/SaveExample-####.tif");
} else {
exit();
}
x += 2.5;
}</pre>
<p>Processing will write an image based on the file extension that you use (<em>.png</em>, <em>.jpg</em>, or <em>.tif</em> are all built in, and some platforms may support others). A <em>.tif</em> image is saved uncompressed, which is fast but takes up a lot of disk space. Both <em>.png</em> and <em>.jpg</em> will create smaller files, but because of the compression, will usually require more time to save, making the sketch run slowly.</p>
<p>If your output is vector graphics, you can write the output to PDF files for higher resolution. The PDF Export library makes it possible to write PDF files directly from a sketch. These vector graphics files can be scaled to any size without losing resolution, which makes them ideal for print output—from posters and banners to entire books.</p>
</section>
<section data-type="sect2" data-pdf-bookmark="Example 11-5: Draw to a PDF" id="example_11-5_colon_draw_to_a_pdf">
<h2>Example 11-5: Draw to a PDF</h2>
<p>This example builds on <a data-type="xref" href="#example_11-4_colon_saving_images">“Example 11-4: Saving Images”</a> to draw more chevrons of different weights, but it removes the motion. It creates a PDF file called <em>Ex-11-5.pdf</em> because of the third and fourth parameters to <em>size()</em>:</p>
<pre data-type="programlisting">import processing.pdf.*;
void setup() {
size(600, 800, PDF, "Ex-11-5.pdf");
noFill();
strokeCap(SQUARE);
}
void draw() {
background(255);
for (int y = 100; y &lt; height - 300; y+=20) {
float r = random(0, 102);
strokeWeight(r / 10);
beginShape();
vertex(100, y);
vertex(width/2, y + 200);
vertex(width-100, y);
endShape();
}
exit();
}</pre>
<p>The geometry is not drawn on the screen; it is written directly into the PDF file, which is saved into the sketch’s folder. This code in this example runs once and then exits at the end of <em>draw()</em>. The resulting output is shown in <a data-type="xref" href="#pdf_export_from_example_11-5">Figure 11-2</a>.</p>
<p>There are more PDF Export examples included with the Processing software. Look in the <em>PDF Export</em> section of the Processing examples to see more techniques.</p>
<figure id="pdf_export_from_example_11-5">
<img src="images/Fig_11_02.png" alt="Fig 11 02"/>
<figcaption>PDF export from <a data-type="xref" href="#example_11-5_colon_draw_to_a_pdf">“Example 11-5: Draw to a PDF”</a>.</figcaption>
</figure>
</section>
</section>
<section data-type="sect1" data-pdf-bookmark="Hello Arduino" id="hello_arduino">
<h1>Hello Arduino</h1>
<p>Arduino is an electronics prototyping platform with a series of microcontroller boards and the software to program them. Processing and Arduino share a long history together; they are sister projects with many similar ideas and goals, though they address separate domains. Because they share the same editor and programming environment and a similar syntax, it’s easy to move between them and to transfer knowledge about one into the other.</p>
<p>In this section, we focus on reading data into Processing from an Arduino board and then visualize that data on screen. This makes it possible to use new inputs into Processing programs and to allow Arduino programmers to see their sensor input as graphics. These new inputs can be anything that attaches to an Arduino board. These devices range from a distance sensor to a compass or a mesh network of temperature sensors.</p>
<p>This section assumes that you have an Arduino board and that you already have a basic working knowledge of how to use it. If not, you can learn more online at <a href="http://www.arduino.cc"><em class="hyperlink">http://www.arduino.cc</em></a> and in the excellent book <em>Getting Started with Arduino</em> by Massimo Banzi (O’Reilly). Once you’ve covered the basics, you can learn more about sending data between Processing and Arduino in another outstanding book, <em>Making Things Talk</em> by Tom Igoe (O’Reilly).</p>
<p>Data can be transferred between a Processing sketch and an Arduino board with some help from the Processing Serial Library. <em>Serial</em> is a data format that sends one byte at a time. In the world of Arduino, a <em>byte</em> is a data type that can store values between 0 and 255; it works like an <em>int</em>, but with a much smaller range. Larger numbers are sent by breaking them into a list of bytes and then reassembling them later.</p>
<p>In the following examples, we focus on the Processing side of the relationship and keep the Arduino code simple. We visualize the data coming in from the Arduino board one byte at a time. With the techniques covered in this book and the hundreds of Arduino examples online, we hope this will be enough to get you started.</p>
<figure id="an_arduino_duemilanove_board">
<img src="images/Fig_11_03.png" alt="Fig 11 03"/>
<figcaption>An Arduino Duemilanove board.</figcaption>
</figure>
<section data-type="sect2" data-pdf-bookmark="Example 11-6: Read a Sensor" id="example_11-6_colon_read_a_sensor">
<h2>Example 11-6: Read a Sensor</h2>
<p>The following Arduino code is used with the next three Processing examples:</p>
<pre data-type="programlisting">// Note: This is code for an Arduino board, not Processing
int sensorPin = 0; // Select input pin
int val = 0;
void setup() {
Serial.begin(9600); // Open serial port
}
void loop() {
val = analogRead(sensorPin) / 4; // Read value from sensor
Serial.print(val, BYTE); // Print variable to serial port
delay(100); // Wait 100 milliseconds
}</pre>
<p>There are two important details to note about this Arduino example. First, it requires attaching a sensor into the analog input on pin 0 on the Arduino board. You might use a light sensor (also called a photo resistor, photocell, or light-dependent resistor) or another analog resistor such as a thermistor (temperature-sensitive resistor), flex sensor, or pressure sensor (force-sensitive resistor). The circuit diagram and drawing of the breadboard with components are shown in <a data-type="xref" href="#attaching_a_light_sensor_to_analog_in_pi">Figure 11-4</a>. Next, notice that the value returned by the <em>analogRead()</em> function is divided by 4 before it’s assigned to <em>val</em>. The values from <em>analogRead()</em> are between 0 and 1023, so we divide by 4 to convert them to the range of 0 to 255 so that the data can be sent in a single byte.</p>
<figure id="attaching_a_light_sensor_to_analog_in_pi">
<img src="images/Fig_11_04.png" alt="Fig 11 04"/>
<figcaption>Attaching a light sensor to analog in pin 0.</figcaption>
</figure>
</section>
<section data-type="sect2" data-pdf-bookmark="Example 11-7: Read Data from the Serial Port" id="example_11-7_colon_read_data_from_the_se">
<h2>Example 11-7: Read Data from the Serial Port</h2>
<p>The first visualization example shows how to read the serial data in from the Arduino board and how to convert that data into the values that fit to the screen dimensions:</p>
<pre data-type="programlisting">import processing.serial.*;
Serial port; // Create object from Serial class
float val; // Data received from the serial port
void setup() {
size(440, 220);
// IMPORTANT NOTE:
// The first serial port retrieved by Serial.list()
// should be your Arduino. If not, uncomment the next
// line by deleting the // before it. Run the sketch
// again to see a list of serial ports. Then, change
// the 0 in between [ and ] to the number of the port
// that your Arduino is connected to.
//println(Serial.list());
String arduinoPort = Serial.list()[0];
port = new Serial(this, arduinoPort, 9600);
}
void draw() {
if (port.available() &gt; 0) { // If data is available,
val = port.read(); // read it and store it in val
val = map(val, 0, 255, 0, height); // Convert the value
}
rect(40, val-10, 360, 20);
}</pre>
<p>The Serial library is imported on the first line and the serial port is opened in <em>setup()</em>. It may or may not be easy to get your Processing sketch to talk with the Arduino board; it depends on your hardware setup. There is often more than one device that the Processing sketch might try to communicate with. If the code doesn’t work the first time, read the comment in <em>setup()</em> carefully and follow the instructions.</p>
<p>Within <em>draw()</em>, the value is brought into the program with the <em>read()</em> method of the Serial object. The program reads the data from the serial port only when a new byte is available. The <em>available()</em> method checks to see if a new byte is ready and returns the number of bytes available. This program is written so that a single new byte will be read each time through <em>draw()</em>. The <em>map()</em> function converts the incoming value from its initial range from 0 to 255 to a range from 0 to the height of the screen; in this program, it’s from 0 to 220.</p>
</section>
<section data-type="sect2" data-pdf-bookmark="Example 11-8: Visualizing the Data Stream" id="example_11-8_colon_visualizing_the_data">
<h2>Example 11-8: Visualizing the Data Stream</h2>
<p>Now that the data is coming through, we’ll visualize it in a more interesting format. The values coming in directly from a sensor are often erratic, and it’s useful to smooth them out by averaging them. Here, we present the raw signal from the light sensor illustrated in <a data-type="xref" href="#attaching_a_light_sensor_to_analog_in_pi">Figure 11-4</a> in the top half of the example and the smoothed signal in the bottom half:</p>
<figure>
<img src="images/Ex_11_08.png" alt="Ex 11 08"/>
<figcaption/>
</figure>
<pre data-type="programlisting">import processing.serial.*;
Serial port; // Create object from Serial class
float val; // Data received from the serial port
int x;
float easing = 0.05;
float easedVal;
void setup() {
size(440, 440);
frameRate(30);
smooth();
String arduinoPort = Serial.list()[0];
port = new Serial(this, arduinoPort, 9600);
background(0);
}
void draw() {
if ( port.available() &gt; 0) { // If data is available,
val = port.read(); // read it and store it in val
val = map(val, 0, 255, 0, height); // Convert the values
}
float targetVal = val;
easedVal += (targetVal - easedVal) * easing;
stroke(0);
line(x, 0, x, height); // Black line
stroke(255);
line(x+1, 0, x+1, height); // White line
line(x, 220, x, val); // Raw value
line(x, 440, x, easedVal + 220); // Averaged value
x++;
if (x &gt; width) {
x = 0;
}
}</pre>
<p>Similar to <a data-type="xref" href="ch05.html#example_5-8_colon_easing_does_it">“<a href="http://examples.oreilly.com/0636920000570/interactive_examples/index.php?example=Ex_05_08">Example 5-8: Easing Does It</a>”</a> and <a data-type="xref" href="ch05.html#example_5-9_colon_smooth_lines_with_easi">“<a href="http://examples.oreilly.com/0636920000570/interactive_examples/index.php?example=Ex_05_09">Example 5-9: Smooth Lines with Easing</a>”</a>, this sketch uses the easing technique. Each new byte from the Arduino board is set as the target value, the difference between the current value and the target value is calculated, and the current value is moved closer to the target. Adjust the <em>easing</em> variable to affect the amount of smoothing applied to the incoming values.</p>
</section>
<section data-type="sect2" data-pdf-bookmark="Example 11-9: Another Way to Look at the Data" id="example_11-9_colon_another_way_to_look_a">
<h2>Example 11-9: Another Way to Look at the Data</h2>
<p>This example is inspired by radar display screens. The values are read in the same way from the Arduino board, but they are visualized in a circular pattern using the <em>sin()</em> and <em>cos()</em> functions introduced earlier in <a data-type="xref" href="ch07.html#example_7-12_colon_sine_wave_values">“<a href="http://examples.oreilly.com/0636920000570/interactive_examples/index.php?example=Ex_07_12">Example 7-12: Sine Wave Values</a>”</a> to <a data-type="xref" href="ch07.html#example_7-15_colon_spirals">“<a href="http://examples.oreilly.com/0636920000570/interactive_examples/index.php?example=Ex_07_15">Example 7-15: Spirals</a>”</a>:</p>
<figure>
<img src="images/Ex_11_09.png" alt="Ex 11 09"/>
<figcaption/>
</figure>
<pre data-type="programlisting">import processing.serial.*;
Serial port; // Create object from Serial class
float val; // Data received from the serial port
float angle;
float radius;
void setup() {
size(440, 440);
frameRate(30);
strokeWeight(2);
smooth();
String arduinoPort = Serial.list()[0];
port = new Serial(this, arduinoPort, 9600);
background(0);
}
void draw() {
if ( port.available() &gt; 0) { // If data is available,
val = port.read(); // read it and store it in val
// Convert the values to set the radius
radius = map(val, 0, 255, 0, height * 0.45);
}
int middleX = width/2;
int middleY = height/2;
float x = middleX + cos(angle) * height/2;
float y = middleY + sin(angle) * height/2;
stroke(0);
line(middleX, middleY, x, y);
x = middleX + cos(angle) * radius;
y = middleY + sin(angle) * radius;
stroke(255);
line(middleX, middleY, x, y);
angle += 0.01;
}</pre>
<p>The <em>angle</em> variable is updated continuously to move the line drawing the current value around the circle, and the <em>val</em> variable scales the length of the moving line to set its distance from the center of the screen. After one time around the circle, the values begin to write on top of the previous data.</p>
<p>We’re excited about the potential of using Processing and Arduino together to bridge the world of software and electronics. Unlike the examples printed here, the communication can be bidirectional. Elements on screen can also affect what’s happening on the Arduino board. This means you can use a Processing program as an interface between your computer and motors, speakers, lights, cameras, sensors, and almost anything else that can be controlled with an electrical signal. Again, more information about Arduino can be found at <a href="http://www.arduino.cc"><em class="hyperlink">http://www.arduino.cc</em></a>.</p>
</section>
</section>
<section data-type="sect1" data-pdf-bookmark="Community" id="community">
<h1>Community</h1>
<p>We’ve worked hard to make it easy to export Processing programs so that you can share them with others. In the second chapter, we discussed sharing your programs by exporting them. We believe that sharing fosters learning and community. As you modify the programs from this book and start to write your own programs from scratch, we encourage you to review that section of the book and to share your work with others. At the present, the groups at OpenProcessing, Vimeo, Flickr, and the Processing Wiki are exciting places to visit and contribute to. On Twitter, searches for #Processing and <a href="http://processing.org">Processing.org</a> yield interesting results. These communities are always moving and flowing. Check the main Processing site (<a href="http://www.processing.org"><em class="hyperlink">http://www.processing.org</em></a>) for fresh links as well as these:</p>
<ul class="">
<li>
<p><a href="http://www.openprocessing.org"><em class="hyperlink">http://www.openprocessing.org</em></a></p>
</li>
<li>
<p><a href="http://www.vimeo.com/tag:processing.org"><em class="hyperlink">http://www.vimeo.com/tag:processing.org</em></a></p>
</li>
<li>
<p><a href="http://www.flickr.com/groups/processing/"><em class="hyperlink">http://www.flickr.com/groups/processing/</em></a></p>
</li>
<li>
<p><a href="http://www.delicious.com/tag/processing.org/"><em class="hyperlink">http://www.delicious.com/tag/processing.org/</em></a></p>
</li>
</ul>
</section>
</section>
</body>
</html>