ArrayIndexOutOfBoundsException

So a friend of mine gave me a test code that sent over pwn values to the arduino. For some reason, it keeps on giving me an error message saying "ArrayIndexOutOfBoundsException: 1" here is the code:

import processing.serial.*;

PFont font;
int pwmValue;
Serial mySerial;
int serialIndex = 1;

void setup() {
  font  = createFont("Arial", 32);
  size(300, 301);
  mySerial = new Serial(this, Serial.list()[serialIndex], 9600); //This one has been giving me the error
}

void draw() {
  background(200);
  if (mouseY > 44) {
    line(0, mouseY, 300, mouseY);
    pwmValue = int(constrain(-2.1*(mouseY - 172), -255, 255));
    fill(0);
  }
  else {
    pwmValue = 0;
    fill(70);
  }
  rect(0, 0, 300, 44);
  textAlign(LEFT, TOP);
  textFont(font, 16);
  fill(255);
  text("Current Speed: " + str(pwmValue), 9, 9);
  fill(255, 0, 0);
  text("Rollover to Reset", 160, 9);

  mySerial.write(str(pwmValue)); 
  mySerial.write("#");
  mySerial.write(str(pwmValue)); 
  mySerial.write(10);
}

Any ideas? Please respond if you do

Thanks

Tagged:

Answers

  • Answer ✓

    I have corrected your code formatting. The error you are receiving is very simple: the array returned by Serial.list() contains only one element, so index 1 is out of bounds. To specify the first element, you must use index 0.

    Change line 6 to:

    int serialIndex = 0;
    
  • It works thank you :)

Sign In or Register to comment.