Connecting Arduino to Processing

Pages
Contributors: b_e_n
Favorited Favorite 29

From Processing...

So we’ve sent data from Arduino to Processing, but what if we want to send data the other way - from Processing to Arduino? Piece of cake!

Let’s start with the Processing side of things. It starts out much like our last sketch: we import the Serial library and declare a global Serial object variable for our port up top, and in our setup() method we find our port and initialize Serial communication on that port with our Serial variable at 9600 baud. We’re also going to use the size() command, to give us a little window to click in, which will trigger our sketch to send something over the Serial port to Arduino.

language:java
import processing.serial.*;

Serial myPort;  // Create object from Serial class

void setup() 
{
  size(200,200); //make our canvas 200 x 200 pixels big
  String portName = Serial.list()[0]; //change the 0 to a 1 or 2 etc. to match your port
  myPort = new Serial(this, portName, 9600);
}

In our draw() loop, we send whatever we want over the serial port by using the write method from the Processing Serial library. For this sketch, we will send a ‘1’ whenever we click our mouse in the Processing window. We’ll also print it out on the console, just to see that we’re actually sending something. If we aren’t clicking we’ll send a ‘0’ instead.

language:java
void draw() {
  if (mousePressed == true) 
  {                           //if we clicked in the window
   myPort.write('1');         //send a 1
   println("1");   
  } else 
  {                           //otherwise
  myPort.write('0');          //send a 0
  }   
}

This is what your code should look like at this point:

alt text

If you run this code, you should see a bunch of 1’s appear in the console area whenever you click your mouse in the window. Neat! But how do we look for these 1’s from Arduino? And what can we do with them?