ArrayIndexOutOfBoundsException: 2 - Going out of bounds of array?

Viewed 128

I am sending 3 sensor values from Arduino to Processing and splitting the String into three elements in the array. Sometimes when I run the program, I get the ArrayIndexOutOfBoundsException: 2 error and as far as I understand, it means that I am trying to access an element in the array that isn't there. What am I doing wrong?

My code from Processing and Arduino is below:

PROCESSING:

import processing.serial.*;

Serial port;
float background;
float r1;
int a;
int b;
int c;
PrintWriter output;
Databox Data1 = new Databox(20, 20);
Databox Data2 = new Databox(20, 190);
Databox Data3 = new Databox(20, 360);

void setup() {
  size (690, 530);
  port = new Serial(this, "COM3", 9600);
  output = createWriter(hour() + "." + minute() + "." + second() + ".txt");
}

void draw() {
  background(60, 40);
  Data1.drawDataboxHumi();
  Data2.drawDataboxTemp();
  Data3.drawDataboxMoist();

  if (port.available() > 0) {
    String inString = port.readStringUntil('\n');
    if (inString != null) {
      inString = trim(inString);
      String[] data = split(inString, '#');

      a = int(data[0]);
      b = int(data[1]);
      c = int(data[2]);

      output.println("Tidspunkt:" + " " + hour() + ":" + minute() + ":" + second() + " - " 
        + "Luftfugtighed:" + a +"%" + " "+ "Temperatur:" + b + " " + "Jordfugtighed:" + " " + c);
      output.flush();
    }
  }
}

ARDUINO:

#include <dht.h>

dht DHT;

#define DHT11_PIN 7

void setup() {
  Serial.begin(9600);
  pinMode(A0, INPUT);
}

void loop() {
  int SensorValue = analogRead(A0); 
                                      

  int chk = DHT.read11(DHT11_PIN);

  Serial.print(DHT.humidity);
  Serial.print("#");
  Serial.print(DHT.temperature);
  Serial.print("#");
  Serial.print(SensorValue);
  Serial.println("#");
  delay(1500);
}
1 Answers

Try checking (by printing) what port.readStringUntil('\n') returns exactly every time, and in the same way check what is left of it after the trim().

It could be readStringUntil() times out sometimes, and then returns 0 only, which is a string without any #s, which would split into a 1-element array. It could also be reading spurious data left in the buffer somehow, with the same effect.

The only way of finding out is checking the inString as said above.

You could prevent the run-time error by doing a check on the number of elements in String[] data before addressing the individual array elements, but that doesn't solve the onderlying problem. It could well be good enough for your purpose, though.

Remark:

You don't need to send the last (third) # from the Arduino; you only need two for splitting an Arduino String into three parts, and having three #s may lead to split yielding four parts. It will need a \n at the end, though.

Related