Hardware Reference
In-Depth Information
Controlling a Processing Sketch from Your Arduino
For your first experiment with Processing, you use a potentiometer connected
to your Arduino to control the color of a window on your computer. Wire up
your Arduino with a potentiometer, referencing Figure 6-6 again. You already
know the Arduino code necessary to send the analog values from the potenti-
ometer to your computer. The fact that you are now feeding the serial data into
Processing does not have any impact on the way you transmit it.
Reference the code in Listing 6-6 and load it on to your Arduino. It sends an
updated value of the potentiometer to the computer's serial port every 50 mil-
liseconds. The 50ms is important; if you were to send it as fast as possible, the
Processing sketch wouldn't be able to handle it as quickly as you are sending it,
and you would eventually overflow the serial input buffer on your computer.
Listing 6-6: Arduino Code to send Data to the Computer—pot_to_processing/arduino_
read_pot
//Sending POT value to the computer
const int POT=0; //Pot on analog pin 0
int val; //For holding mapped pot value
void setup()
{
Serial.begin(9600); //Start Serial
}
void loop()
{
val = map(analogRead(POT), 0, 1023, 0, 255); //Read and map POT
Serial.println(val); //Send value
delay(50); //Delay so we don't flood
//the computer
}
Now comes the interesting part: writing a Processing sketch to do something
interesting with this incoming data. The sketch in Listing 6-7 reads the data
in the serial buffer and adjusts the brightness of a color on the screen of your
computer based on the value it receives. First, copy the code from Listing 6-7
into a new Processing sketch. You need to change just one important part. The
Processing sketch needs to know which serial port to expect data to arrive on.
This is the same port that you've been programming the Arduino from. In the
Search WWH ::




Custom Search