Hardware Reference
In-Depth Information
following listing, replace
"COM3"
with your serial port number. Remember that
on Linux and Mac it will look like
/dev/ttyUSB0
, for example. You can copy the
exact name from within the Arduino IDE if you are unsure.
port = new Serial(this, "COM3", 9600); //setup serial
Listing 6-7:
Processing Code to Read Data and Change Color on the Screen—pot_to_
processing/processing_display_color
//Processing Sketch to Read Value and Change Color on the Screen
//Import and initialize serial port library
import processing.serial.*;
Serial port;
float brightness = 0; //For holding value from pot
void setup()
{
size(500,500); //Window size
port = new Serial(this, "COM3", 9600); //Set up serial
port.bufferUntil('\n'); //Set up port to read until
//newline
}
void draw()
{
background(0,0,brightness); //Updates the window
}
void serialEvent (Serial port)
{
brightness = float(port.readStringUntil('\n')); //Gets val
}
After you've loaded the code into your Processing IDE and set the serial
port properly, make sure that the Arduino serial monitor isn't open. Only one
program on your computer can have access to the serial port at a time. Click
the Run button in the Processing IDE (the button in the top left of the window
with a triangle); when you do so, a small window will pop up (see Figure 6-13).
As you turn the potentiometer, you should see the color of the window change
from black to blue.
Now that you've seen it working, let's walk through the code to gain a better
understanding of how the Processing sketch is working. Unlike in Arduino,
the serial library is not imported automatically. By calling
import processing
.serial.*;
and
Serial port;
you are importing the serial library and mak-
ing a serial object called
port
.
Search WWH ::
Custom Search