【问题标题】:Arduino to Processing Long datatype over serial OutofBoundsExceptionArduino 通过串行 OutofBoundsException 处理 Long 数据类型
【发布时间】: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


    【解决方案1】:

    Arduino 中的long 是 32 位无符号或有符号的。 0x00000000000000FF 的值是 64 位数字,在 Arduino 架构中无法理解。当您可以简单地执行此操作时,该功能似乎没有任何用途::

    value = inBuffer[0] | 
            inBuffer[1] << 8 | 
            inBuffer[2] << 16| 
            inBuffer[3] << 24;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多