Processing(ldrValues)上的空指针异常

问题描述 投票:1回答:1

我的代码涉及Processing和Arduino。 5种不同的光电池可以触发5种不同的声音。仅当ldrvalue高于阈值时,我的声音文件才会播放。

此行上突出显示Null Pointer Exception

for (int i = 0; i < ldrValues.length; i++) {

我不确定应该更改我的代码的哪一部分,以便我可以运行它。

import processing.serial.*;
import processing.sound.*;

SoundFile[] soundFiles = new SoundFile[5];
Serial myPort;  // Create object from Serial class

int[] ldrValues;
int[] thresholds = {440, 490, 330, 260, 450};
int i = 0;
boolean[] states = {false, false, false, false, false};

void setup() {
  size(200, 200);


  println((Object[])Serial.list());

  String portName = Serial.list()[3];
  myPort = new Serial(this, portName, 9600);


  soundFiles[0] = new SoundFile(this, "1.mp3");
  soundFiles[1] = new SoundFile(this, "2.mp3");
  soundFiles[2] = new SoundFile(this, "3.mp3");
  soundFiles[3] = new SoundFile(this, "4.mp3");
  soundFiles[4] = new SoundFile(this, "5.mp3");
}

void draw()
{
  background(255);             

  //serial loop
  while (myPort.available() > 0) {
    String myString = myPort.readStringUntil(10);
    if (myString != null) {
      //println(myString);
      ldrValues = int(split(myString.trim(), ','));
      //println(ldrValues);
    }
  }

  for (int i = 0; i < ldrValues.length; i++) {
    println(states[i]);
    println(ldrValues[i]);
    if (ldrValues[i] > thresholds[i] && !states[i]) {
      println("sensor " + i + " is activated");
      soundFiles[i].play();
      states[i] = true;
    }
    if (ldrValues[i] < thresholds[i]) {
      println("sensor " + i + " is NOT activated");
      soundFiles[i].stop();
      states[i] = false;
    }
  }
}
nullpointerexception arduino processing
1个回答
0
投票

你接近我们应该乐观吗? :)

它总是假设有一条来自Serial的消息,总是以正确的方式格式化,因此可以解析它,并且缓冲数据绝对有0个问题(不完整的字符串等))

您可以做的最简单的事情是检查解析是否成功,否则ldrValues数组仍然为null:

void draw()
{
  background(255);             

  //serial loop
  while (myPort.available() > 0) {
    String myString = myPort.readStringUntil(10);
    if (myString != null) {
      //println(myString);
      ldrValues = int(split(myString.trim(), ','));
      //println(ldrValues);
    }
  }
  // double check parsing int values from the string was successfully as well, not just buffering the string  
  if(ldrValues != null){
    for (int i = 0; i < ldrValues.length; i++) {
      println(states[i]);
      println(ldrValues[i]);
      if (ldrValues[i] > thresholds[i] && !states[i]) {
        println("sensor " + i + " is activated");
        soundFiles[i].play();
        states[i] = true;
      }
      if (ldrValues[i] < thresholds[i]) {
        println("sensor " + i + " is NOT activated");
        soundFiles[i].stop();
        states[i] = false;
      }
    }
  }else{
    // print a helpful debugging message otherwise
    println("error parsing ldrValues from string: " + myString);
  }


}

(不知道你可以用int[]解析int():太棒了!)

© www.soinside.com 2019 - 2024. All rights reserved.