【发布时间】:2017-08-10 13:23:18
【问题描述】:
我正在尝试通过串行方式将长值从 Arduino 传输到处理,并具有以下代码。
阿杜诺:
void setup() {
Serial.begin(9600);
}
void loop() {
long int randomno = random(0, 1520);
unsigned char buf[sizeof(long int)];
memcpy(buf,&randomno,sizeof(long int));
Serial.write(buf,sizeof(buf));
delay(50);
}
及处理:
import processing.serial.*;
Serial myPort;
void setup() {
size(1920, 1080);
myPort = new Serial(this, "COM3", 9600);
}
void draw(){
background(0,0,0);
long value;
byte[] inBuffer = new byte[4];
if (myPort.available() > 0) {
try{
inBuffer = myPort.readBytes();
if (inBuffer != null) {
value = byteAsULong(inBuffer[0]) << 0 |
(byteAsULong(inBuffer[1])) << 8 |
(byteAsULong(inBuffer[2])) << 16|
(byteAsULong(inBuffer[3])) << 24;
println(value);
}
} catch(RuntimeException e) {
e.printStackTrace();
}
}
}
public static long byteAsULong(byte b) {
return ((long)b) & 0x00000000000000FFL;
}
当我运行它时,我得到了一些值,但随后不断收到向我抛出的 ArrayIndexOutofBounds 异常。现在我已经通过使用 printstacktrace 捕获来克服它,但我想找出问题所在。
【问题讨论】:
标签: arduino serial-port processing indexoutofboundsexception long-integer