splitTokens() question

Thank you for reading this.

The following is a section from a piece of code that I copied for an Internet project. It fails with an exception error on the line float hum = float(list[1]);. Some Internet searching reveals that this might be a case for splitTokens(). Is that correct and if so how I proceed?

  if (port.available() > 0)
  {
    String val = port.readString(); // read incoming string on serial port
    // First we need to separate temperature and humidity values
    String[] list = split(val, ','); // splits value separated by ','
    float temp = float(list[0]); // first value is Temperature
    float hum = float(list[1]);  // second value is Humidity

only ask for data you know they exist,

if ( list.length >= 2 ) tells you if you have actually 2 values, OR a BAD LINE


also better use 2 more checks:

  • trim()
  • if ( val != null )

see also

Thank you kll, I should have thought of this myself but I had convinced myself that split function was the problem.

1 Like

Two interesting posts that I have kept for future reference, thank you GoToLoop.

1 Like