Convert String to float for drawing graph

edited September 2017 in Arduino

Hay everyone I'm new here and I hope someone can help me with my little issue. On my arduino is a sensor attached, that works fine. Also the transmission from the Arduino to the Processing program. The information comes as a String variable "val". To draw the graph I need to convert the variable into a float typ. I tried it with "Float.parseFloat(val)" but that didn't worked.

import processing.serial.*;
Serial myPort;
Table table;

int numReadings = 100; //8640000 = One day
int readingCounter = 0;

String val;

float y = 0;
float t = 20;


void setup() {
  String portName = Serial.list()[0];

  myPort = new Serial(this, Serial.list()[0], 9600);
  table = new Table();

  table.addColumn("id");
  table.addColumn("month");
  table.addColumn("day");
  table.addColumn("hour");
  table.addColumn("minute");
  table.addColumn("second");

  table.addColumn("sensor1");

  size(1000, 1000);
  frameRate(10);
}

void draw() {

  if ( val != null) {
    y = Float.parseFloat(val);

  } else {
    y = 0;
  }
  rect(t, y, 5, 5);
  t = t + 5;
}

void serialEvent(Serial myPort) {

  try {
    String val = myPort.readStringUntil('\n');
    if (val!= null) {
      val = trim(val);
      println(val, y);  //Control
      float sensorValue[] = float(split(val, ','));

      TableRow newRow = table.addRow();
      newRow.setInt("id", table.lastRowIndex());

      newRow.setInt("month", month());
      newRow.setInt("day", day());
      newRow.setInt("hour", hour());
      newRow.setInt("minute", minute());
      newRow.setInt("second", second());

      newRow.setFloat("sensor1", sensorValue[0]); 
      println(table.lastRowIndex());

      readingCounter++;

      if (readingCounter == numReadings) {
        saveTable(table, "data/new.csv");
      }
    }
  }
  catch(RuntimeException e) {
    e.printStackTrace();
  }
}

In the console comes the following:

    177 0.0
    java.lang.NullPointerException
        at Processing_uebertragung.serialEvent(Processing_uebertragung.java:73)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at processing.serial.Serial.serialEvent(Unknown Source)
        at jssc.SerialPort$EventThread.run(SerialPort.java:1112)
    179 0.0
    0
    181 0.0
    1
    183 0.0
    2
    185 0.0
    3
    186 0.0
    4
    188 0.0
    5
    190 0.0

sorry for my bad english. 8-|

Answers

Sign In or Register to comment.