import processing.serial.*;

Serial myPort;
float temp = 0;
float[] history; // Para guardar los puntos de la gráfica

void setup() {
  size(800, 400);
  history = new float[width];
  
  // Listar puertos
  printArray(Serial.list());
  // Asegúrate de seleccionar el índice correcto de tu Xiao
  myPort = new Serial(this, Serial.list()[0], 115200);
  myPort.bufferUntil('\n');
}

void draw() {
  background(20);
  drawGrid();
  
  // Dibujar la línea de temperatura
  stroke(0, 255, 200);
  strokeWeight(2);
  noFill();
  beginShape();
  for (int i = 0; i < history.length; i++) {
    // Mapeamos 0°C - 50°C al alto de la pantalla
    float y = map(history[i], 0, 50, height, 0);
    vertex(i, y);
  }
  endShape();
  
  // Mostrar texto
  fill(255);
  textSize(32);
  text(nf(temp, 0, 1) + " °C", 20, 50);
}

void serialEvent(Serial p) {
  String inString = p.readStringUntil('\n');
  if (inString != null) {
    temp = float(trim(inString));
    
    // Desplazar historial a la izquierda
    for (int i = 0; i < history.length - 1; i++) {
      history[i] = history[i+1];
    }
    history[history.length - 1] = temp;
  }
}

void drawGrid() {
  stroke(50);
  for (int i = 0; i < height; i += 50) {
    line(0, i, width, i);
  }
}
