//-------------------
// Processing code:
//-------------------
// analog_Ellipse_Motion
// -Reads analog data from the serial port
// and uses data to change 2D graphic image.

import processing.serial.*;
Serial myPort;        // Create object from Serial class
String serialString;  // variable for serial ASCII date
float val;            // val for data from serial port

float yLoc = 100.0;     // location on Y axis
float speed = 5.0;    // pixels per movement
int radius = 45;      // size of ellipse
int direction = 1;    // 1 goes down, 0 goes up

void setup() {
   size(600, 600);
   smooth();
   noStroke();
   ellipseMode(RADIUS);

   // Open connection to USB (COM port) at 9600 bps
    myPort = new Serial(this, Serial.list()[2], 9600);
}

void draw() {
    radius = 10 + int(val)/3;   // scale analog reading
    fill(0,12);                    // black, transluscent (alpha=12)
    rect(0, 0, width, height);     // rectangle covers screen 
    fill(255,255,225);             // mix RGB color for ellipse
    ellipse(2 * val, yLoc, radius, radius);
    yLoc += (speed * direction);
    if ((yLoc > height-radius) || (yLoc < radius)) {
      direction = -direction;
    }
  }


//---- The SerialEvent function runs continuously in the background and
//---- stores new values whenever new data comes in on the serial port (USB)

void serialEvent(Serial myPort) {
   serialString = myPort.readStringUntil(10); // Read until end of line character
   if (serialString != null) {
     serialString = trim(serialString); 
     val = int(serialString);
     println(val);
   }                               // end if
}