我正在尝试通过串行从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 Exceptions。现在我已经通过使用printstacktrace catch来克服它,但我想知道问题是什么。
答案 0 :(得分:0)
Arduino中的long
是32位无符号或有符号。值0x00000000000000FF
是64位数,在Arduino体系结构中无法理解。当你可以简单地执行::
value = inBuffer[0] |
inBuffer[1] << 8 |
inBuffer[2] << 16|
inBuffer[3] << 24;