import processing.serial.*;
import java.io.FileWriter;
import java.io.*;
import java.util.*;

Serial myPort;
String val = "0.0";

int speeds_show=5;
float[] speeds=new float[speeds_show];
int speeds_index=0; //points to next array index

float speedfloat=0;

Date d=new Date();

PrintWriter pw;

int unitdisplay=0;
int unitdisplay_count=2; //how much different units available

void setup() {
  size(1500, 1000);
  frameRate(30);
  //String portName = "COM3";
  String portName = "/dev/ttyUSB0";
  myPort = new Serial(this, portName, 115200);
  
  pw=createWriter("speeds.txt");
  
  background(0);
}


// speed wird sein "20.08" oder

void draw() {
  if ( myPort.available() > 0) {
    val = myPort.readString();
    print("val = " + val);
    val = val.substring(0,val.length()-1);
    
    speedfloat=float(val);
    
    speeds[speeds_index]=speedfloat;
    speeds_index++;
    speeds_index%=speeds_show;
    
    
    println(d.getTime()+";"+speedfloat);
    pw.println(d.getTime()+";"+speedfloat);
    pw.flush();
    
    unitdisplay=int(random(0,unitdisplay_count));
    unitdisplay=1;
    println("unitdisplay: "+unitdisplay);
    
  }
  
  background(0);
  fill(255);
  
  textSize(150);
  
  switch(unitdisplay){
    case 0:
      text(nf(speedfloat,1,2) + " km/h" , 100, 200);
      break;
    case 1:
      text(nf(speedfloat*0.000809848,1,6) + " Mach" , 100, 200);
      break;
  }
  
  
  
  textSize(80);
  //println();
  int ipos=1;
  for (int i=speeds_show;i>0;i--){
    ipos++;
    text(  nf(speeds[(speeds_show+speeds_index-1+i)%speeds_show], 1,2) ,  100, 250+(ipos)*80);
    
    //print(speeds[i]);
    //print(",");
  }
  
  
  
}