Week 14

Arduino to Processing Communication

The Arduino can communicate with processing over USB. The DigitalReadSerial lesson on the Arduino learning page, show how to set up a simple circuit to read a digital input pen and send a “1” or “0” over the serial connection to a computer. In the Arduino IDE you can monitor those incomming messages with the serial monitor. You can also create a processing sketch to read and react to those messages.

Below is a sample Processing sketch that listens to the incoming messages and responds by changing the background color of the window.

import processing.serial.*;
Serial arduinoSerial;
boolean arduinoButtonPressed = false;

void setup() {
  size(400, 400);
  arduinoSerial = new Serial(this, Serial.list()[0], 9600);
  arduinoSerial.bufferUntil('\n');
}

void draw() {
  if (arduinoButtonPressed) {
    background(100, 250, 100);
  } 
  else {
    background(100, 50, 50);
  }
}

void serialEvent(Serial myPort) { 
  // read a line from the arduino
  String inString = arduinoSerial.readStringUntil('\n');
  //trim whitespace
  inString = trim(inString);
  //check value, set flag
  if (inString.equals("1")) {
    arduinoButtonPressed = true;
  }
  else {
    arduinoButtonPressed = false;
  }
}