我正在通过处理将数据从Leap-Motion传输到Arduino。但是,它总是返回错误“ java.lang.ArrayIndexOutOfBoundsException:1”

这是生成错误的代码,但我不知道是什么引起了该问题。

import processing.serial.*;
Serial myPort;
import com.onformative.leap.LeapMotionP5;
import com.leapmotion.leap.Hand;

LeapMotionP5 leap;
float xhand;
float yhand;
float zhand;

void setup(){
  frameRate(20);
  size(500, 500, P2D);

  myPort = new Serial(this, "COM7", 57600);
  myPort.bufferUntil ('\n');
  leap = new LeapMotionP5(this);
}

void draw(){
background(23,23,200);
ellipse(getHandX()+30, getHandZ()+320, 55, 55);

line( 200, 500, 200, 0);
line( 300, 500, 300, 0);
line( 0, 200, 500, 200);
line( 0, 300, 500, 300);

int handCt = 0;

 for (Hand hand : leap.getHandList()) {
     if (handCt == 0) {
      PVector handPos = leap.getPosition(hand);
      setHandPos( handPos.x, handPos.y, handPos.z );
     }
     handCt++;

    int throttle = (int)map(getHandY(), height-100, -100, 0, 85);
    throttle = constrain(throttle, 0, 85);
    int pitch = (int)map(getHandZ(), -500, 1000, 171, 250);
    pitch = constrain(pitch, 171, 250);
    int yaw= (int)map(getHandX(), width-130, -width, 86, 170);
    yaw = constrain(yaw, 86, 170);
    myPort.write(yaw);
    myPort.write(pitch);
    myPort.write(throttle);
    println(pitch);
  }
}

最佳答案

当您尝试引用不存在的数组元素时,抛出ArrayIndexOutOfBoundsException。这意味着指定的索引大于或等于数组的长度,因为数组中的第一个元素的索引为0(而不是1)。

我希望它发生在此行中:

String portName = Serial.list()[1];


必须是它尝试访问的数组只有一个元素,该元素位于索引0处。

07-24 09:48
查看更多