Problems with converting a String to a float

Hello,

Take a look at this:

Arduino
void setup(void)
  {
  Serial.begin(9600);
  Serial.println("DS18B20 Library version: ");
  }

void loop(void)
  {
  Serial.print("sen1");
  Serial.print(",");
  Serial.println(float (millis()));
  delay(1000);
  }
Processing
import processing.serial.*;

Serial myPort;
int lf = 10;
float temp =0.1;
String s = null;

void setup() 
  {
  // List all the available serial ports:
  printArray(Serial.list()); 
  
  myPort = new Serial(this, "COM6", 9600);
  //myPort.clear();
  s = myPort.readStringUntil(lf);
  //println("s0:", s);
  }

void draw() 
  {
  while (myPort.available() > 0) 
    {
    s = myPort.readStringUntil(lf);
    //println("s1:", s);

    if (s != null) 
      {
      println("s2:", s);
      String[] list = trim(split(s, ","));
      //String[] list = split(s, ",");
      //String sen1 = list[0];
      //println("sen1: ", sen1);
      //printArray(list);
      
      if(list.length == 2)
        {
        printArray(list);
        float temp = float(list[1]);
        println("temp: ", temp);
        }
      //delay(600);
      }
    }
  }

I wrote some test code on Arduino that I know the behavior of from the Arduino serial monitor.

I added some println() statements and other code to the Processing side to monitor incoming data.

trim() will removed the “linefeed” from the string; this may not be necessary if the float conversion can remove it. I still remove it in all code I write.

You can comment and uncomment as you desire to see what is going on when testing your code.

I also checked for an expected and valid array length before trying to read data from it.

My first pass at this with some tweaks to your code:

Also, I just worked through your code… there are other ways to do this.

I prefer to use:
serialEvent() \ Language (API) \ Processing 3+

Please format your first post in this topic; it is messy.

:)

1 Like