import processing.serial.*;

Serial myPort;
String currentPort = "COM10";  // Set this to match your board
int[] sensorValues = {0, 0, 0, 0};
float[] displayedValues = {0, 0, 0, 0};
String[] labels = {"N", "E", "S", "W"};

void setup() {
  size(600, 600);
  surface.setTitle("Phototransistor Spider Chart");

  println("Available ports:");
  println(Serial.list());  // Optional: shows all available ports

  // Open the correct port and assign it to myPort
  myPort = new Serial(this, currentPort, 9600);
  myPort.clear();  // Clear buffer in case of junk data
  myPort.bufferUntil('\n');  // Trigger serialEvent on newline
}

void draw() {
  background(255);
  translate(width / 2, height / 2);

  float maxRadius = 200;

// Draw spider web with 10 concentric divisions
stroke(200);
noFill();
for (int i = 1; i <= 10; i++) {
  float r = map(i, 1, 10, 0, maxRadius);
  ellipse(0, 0, r * 2, r * 2);
}

  // Draw axes and direction labels
  stroke(180);
  fill(0);
  textAlign(CENTER, CENTER);
  textSize(16);
  for (int i = 0; i < 4; i++) {
    float angle = TWO_PI / 4 * i - HALF_PI;
    float x = cos(angle) * maxRadius;
    float y = sin(angle) * maxRadius;
    line(0, 0, x, y);
    text(labels[i], x * 1.3, y * 1.3);
  }

  // Draw polygon for sensor values
  stroke(0);
  strokeWeight(3);
  fill(100, 150, 255, 100);
  beginShape();
  for (int i = 0; i < 4; i++) {
    float angle = TWO_PI / 4 * i - HALF_PI;
    float val = map(displayedValues[i], 0, 1024, 0, maxRadius);
    float x = cos(angle) * val;
    float y = sin(angle) * val;
    vertex(x, y);
  }
  endShape(CLOSE);

  // Display numeric values
  fill(0);
  for (int i = 0; i < 4; i++) {
    float angle = TWO_PI / 4 * i - HALF_PI;
    float val = map(displayedValues[i], 0, 1024, 0, maxRadius);
    float x = cos(angle) * val;
    float y = sin(angle) * val;
    text(int(displayedValues[i]), x * 1.2, y * 1.2);
  }
}

void serialEvent(Serial port) {
  String input = port.readStringUntil('\n');
  if (input != null) {
    input = trim(input);
    String[] tokens = split(input, ",");
    if (tokens.length == 4) {
      displayedValues[0] = constrain(int(tokens[0]), 0, 1024); // North
      displayedValues[1] = constrain(int(tokens[1]), 0, 1024); // East
      displayedValues[2] = constrain(int(tokens[3]), 0, 1024); // South
      displayedValues[3] = constrain(int(tokens[2]), 0, 1024); // West
      println("Received: " + input);  // Log to console for debugging
    }
  }
}
