//code to record data from near-simultaneous measurement of a magnetometer and potentiometer
//and save the data to a file
//by Daniel Soltis

import processing.serial.*;
Serial port;

int x;
int y;
int z;
int pot;
long time1;
long time2;
//this string will fill with the variables being recorded.
//if the ouse is pressed, the entire string will be saved to a file
String allData;
float heading;
int index;

void setup(){
  size(900,400);
  port = new Serial(this, Serial.list()[0], 9600);
  port.write(65); 
  println("OK let's go!");
  allData = "";
  noStroke();
  background(0);
}

void draw(){
  //this shows a running graph of the pot and magnetometer values
  fill(255,127,0);
  ellipse(index, height/2-(heading*height)/(4*PI),2,2);
  fill(0,0,255);
  ellipse(index, height-(pot*height)/1024,2,2);
  index = (index+1)%width;
}

void serialEvent(Serial port) {
  String input = port.readStringUntil(13);
  if (input != null){
    String[] parts = input.split(",");

    x= int(parts[0]);
    y= int(parts[1]);
    z =int(parts[2]);
    pot = int(parts[3]);
    time1 = int(parts[4]);
    time2 = int(parts[5]);

    heading = 0;
    if (x == 0 && y < 0){
      heading = PI/2;
    }
    else if (x == 0 && y > 0){
      heading = 3*PI/2; 
    }
    else if (x < 0){
      heading = PI - atan(float(y)/float(x));
    }
    else if (x > 0 && y < 0){
      heading = -atan(float(y)/float(x)); 
    }

    else if (x > 0 && y > 0) {
      heading = 2*PI - atan(float(y)/float(x));
    }
    //add a new line to the data string
    allData = allData + time1 + "\t" + time2 + "\t" + pot + "\t" + heading + "\n";
    port.write(65); 
  }

}

void mousePressed(){
  String[] lines = allData.split("\n");
  saveStrings("data" + millis() + ".txt", lines);
}