Connecting Arduino to Processing

Pages
Contributors: b_e_n
Favorited Favorite 36

...to Arduino

Ok! On this page we're going to look for those 1's coming in from Processing, and, if we see them, we're going to turn on an LED on pin 13 (on some Arduinos, like the Uno, pin 13 is the on-board LED, so you don't need an external LED to see this work).

At the top of our Arduino sketch, we need two global variables - one for holding the data coming from Processing, and another to tell Arduino which pin our LED is hooked up to.

language:cpp
 char val; // Data received from the serial port
 int ledPin = 13; // Set the pin to digital I/O 13

Next, in our setup() method, we'll set the LED pin to an output, since we're powering an LED, and we'll start Serial communication at 9600 baud.

language:cpp
 void setup() {
   pinMode(ledPin, OUTPUT); // Set pin as OUTPUT
   Serial.begin(9600); // Start serial communication at 9600 bps
 }

Finally, in the loop() method, we'll look at the incoming serial data. If we see a '1', we set the LED to HIGH (or on), and if we don't (e.g. we see a '0' instead), we turn the LED off. At the end of the loop, we put in a small delay to help the Arduino keep up with the serial stream.

language:cpp
 void loop() {
   if (Serial.available()) 
   { // If data is available to read,
     val = Serial.read(); // read it and store it in val
   }
   if (val == '1') 
   { // If 1 was received
     digitalWrite(ledPin, HIGH); // turn the LED on
   } else {
     digitalWrite(ledPin, LOW); // otherwise turn it off
   }
   delay(10); // Wait 10 milliseconds for next reading
}

This is what your code should look like when you're done:

alt text

Voila! If we load up this code onto our Arduino, and run the Processing sketch from the previous page, you should be able to turn on an LED attached to pin 13 of your Arduino, simply by clicking within the Processing canvas.