We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi all, I've been trying for hours to get a serial connection to my decibel meter to work in processing. It works with my old Basic Stamp setup but now I want to use it in Processing and I'm trying to translate the script. I do get some sensible data but after a while the I get an index out of bounds error. Here's the script: import processing.serial.*;
Serial myPort; // Create object from Serial class
int baudrate = 9600;
int delayTime = 3000;
byte regel1[] = new byte[8];
byte regel2[] = new byte[8];
byte regel3[] = new byte[8];
int db = 0;
int maxRange = 1300;
int minRange = 300;
//int oldMillis = 0;
void setup(){
size(200, 200);
String portName = Serial.list()[1];
println(Serial.list());
myPort = new Serial(this, portName, baudrate,'N',8,1);
}
void draw(){
regel1[0] = byte(2);
regel1[1] = byte('K');
regel1[2] = byte(0);
regel1[3] = byte(0);
regel1[4] = byte(0);
regel1[5] = byte(0);
regel1[6] = byte(0);
regel1[7] = byte(3);
regel2[0] = byte(2);
regel2[1] = byte('a');
regel2[2] = byte('0');
regel2[3] = byte('0');
regel2[4] = byte('0');
regel2[5] = byte('0');
regel2[6] = byte('0');
regel2[7] = byte(3);
regel3[0] = byte(2);
regel3[1] = byte('X');
regel3[2] = byte('0');
regel3[3] = byte('0');
regel3[4] = byte('0');
regel3[5] = byte('0');
regel3[6] = byte('0');
regel3[7] = byte(3);
myPort.write(regel1);
myDelay(50);
while (myPort.available() > 0) {
println("available");
byte[] smallBuffer = new byte[4];
smallBuffer = myPort.readBytes();
myPort.write(regel2);
myDelay(50);
myPort.write(regel3);
myDelay(50);
byte[] inBuffer = new byte[15]; //15
for(int i = 0; i < inBuffer.length; i++){
inBuffer[i] = 0;
}
inBuffer = myPort.readBytes();
if (inBuffer != null && inBuffer[3] != 0 && inBuffer[4] != 0){
db = inBuffer[3]*256 + inBuffer[4];
if(db > minRange && db < maxRange){
println("db: "+db);
//print(" t: ");
//println(millis()-oldMillis);
//oldMillis = millis();
}
}
myDelay(2850);
}
}
void myDelay(int ms)
{
try
{
Thread.sleep(ms);
}
catch(Exception e){}
}
As you can see I've filled the buffer with zero's to make sure there's something inside. I then check for index 3 and 4 (because I'm doing calculations on it). But I still get an index out of bounds on this line: if (inBuffer != null && inBuffer[3] != 0 && inBuffer[4] != 0) As the reported decibel level is sometimes incorrect I suspect the buffer to not have cleared of filled completely. I hope someone can point me in the right direction here.
Thanks very much in advance for your help, danielle.