Hardware Reference
In-Depth Information
Figure 6-13: Example windows from Processing sketch
Like the Arduino, Processing has a setup() function that runs once at the
beginning of the sketch. In this sketch, it sets up the serial port and creates a
window of size 500n500 pixels with the command size(500,500) . The command
port = new Serial(this, "COM3", 9600) tells Processing everything it needs
to know about creating the serial port. The instance (referred to as “port”) will
run in this sketch and communicate on COM3 (or whatever your serial port is)
at 9600 baud. The Arduino and the program on your computer must agree on
the speed at which they communicate; otherwise, you'll get garbage characters.
port.bufferUntil('\n') tells Processing to buffer the serial input and not do
anything with the information until it sees a newline character.
Instead of loop() , Processing defines other special functions. This program uses
draw() and serialEvent() . The draw() function is similar to Arduino's loop() ;
it runs continuously and updates the display. The background() function sets the
color of the window by setting red, green, and blue values (the three arguments
of the function). In this case, the value from the potentiometer is controlling the
blue intensity, and red and green are set to 0 . You can change what color your pot
is adjusting simply by swapping which argument brightness is filling in. RGB
color values are 8-bit values ranging from 0 to 255 , which is why the potentiometer
is mapped to those values before being transmitted.
serialEvent() is called whenever the bufferUntil() condition that you
specified in the setup() is met. Whenever a newline character is received, the
serialEvent() function is triggered. The incoming serial information is read
as a string with port.readStringUntil('\n') . You can think of a string as an
array of text. To use the string as a number, you must convert it to a floating-
point number with float() . This sets the brightness variable, changing the
background color of the application window.
To stop the application and close the serial port, click the Stop button in the
Processing IDE; it's the square located next to the Run button.
Search WWH ::




Custom Search