Processing to Arduino Serial Library Example

I modified the existing “SimpleWrite” example to:

  • save and check for the state of mouseOverRect()
  • print state to console
  • only writes serial data once
  • a delay() to wait for Arduino to reset once connected to it; in my case, it is an Arduino Mega 2560 R3.

I kept the spirit of the original example intact and left it as a “Simple Write” program.

My edit of “SimpleWrite” example so it only sends data once:

/**
 * Simple Write. 
 * 
 * Check if the mouse is over a rectangle and writes the status to the serial port. 
 * This example works with the Wiring / Arduino program that follows below.
 */


import processing.serial.*;

Serial myPort;  // Create object from Serial class
int val;        // Data received from the serial port

int state = 'L'; //GLV added

void setup() 
{
  size(200, 200);
  // I know that the first port in the serial list on my mac
  // is always my  FTDI adaptor, so I open Serial.list()[0].
  // On Windows machines, this generally opens COM1.
  // Open whatever port is the one you're using.
  String portName = Serial.list()[0];
  myPort = new Serial(this, portName, 9600);
  delay(1000); //GLV added Wait for Arduino to reset
}

void draw() {
  background(255);
  //if (mouseOverRect() == true  ) {  // If mouse is over square,
  if (mouseOverRect() == true && state != 'H' ) {  // If mouse is over square, //GLV modified
    fill(204);                    // change color and
    myPort.write('H');              // send an H to indicate mouse is over square
  println('H');  //GLV added
  state = 'H'; //GLV added
  } 
//  else {                        // If mouse is not over square,
  if (mouseOverRect() == false && state != 'L' ) {  // If mouse is over square, //GLV modified

    fill(0);                      // change color and
    myPort.write('L');              // send an L otherwise
    println('L');   //GLV added
    state = 'L';  //GLV added
  }
  rect(50, 50, 100, 100);         // Draw a square
}

boolean mouseOverRect() { // Test if mouse is over square
  return ((mouseX >= 50) && (mouseX <= 150) && (mouseY >= 50) && (mouseY <= 150));
}

:slight_smile:

3 Likes