我正在尝试通过串行将长值从Arduino传输到处理中,并具有以下代码。
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 中的long
是 32 位无符号或有符号。 值0x00000000000000FF
是一个 64 位数字,在 Arduino 架构中无法理解。当您可以简单地执行以下操作时,该函数似乎没有任何用途:
value = inBuffer[0] |
inBuffer[1] << 8 |
inBuffer[2] << 16|
inBuffer[3] << 24;