C ++与Big endian的小端无符号短文用Java签名

时间:2013-06-18 00:18:36

标签: java c++ casting arduino processing

刚才,我碰巧有过于复杂的类型转换(我仍然不完全理解它们的类型) 我通过串行链接将0到1024个值从Arduino传输到4个字节(int)。很快我就意识到我也可以发短路(2个字节)来快速通信2倍(而且我需要它非常快)。
所以这就是我在arduino上的C ++中所拥有的:

  // variable to store the value coming from the sensor
  unsigned short sensorValue = 0;  
  //Time when I last sent the buffer (serial link seems to need some rest)
  unsigned long last_time_sent = millis();
  //Buffer to save data I've collected
  byte buffer[256];
  //Position in buffer
  byte buffer_pos = 0;

  while(1) {
    //Get 0 - 1024
    sensorValue = analogRead(sensorPin);
    //(Try to) convert Short to two bytes. I don't even which is first and which is last
    for(byte i=0; i<2; i++) {
       //Some veird bit-shifting, all saved in buffer with an offset
       buffer[i+buffer_pos] = (byte)(sensorValue >> ((2-i) * 8));
    }
    //Iterate buffer position
    buffer_pos+=2;
    //Currently, I send the data allways
    if(true||millis()-last_time_sent>30||buffer_pos+2>=255)
      Serial.write(buffer, buffer_pos);
    //Temporary delay for serial link to rest
    delay(50);
  }

现在,在Processing中,java代码如下所示:

void serialEvent(Serial uselessParameter) {
  while (myPort.available() >= 2) {
    //java doesn't allow unsigned variables
    short number = 0;
    for(byte i=0; i<2; i++) {
      byte received = (byte)myPort.read();
      println("Byte received: "+Integer.toString((int)received));
      number |= myPort.read() << (2-i)*8;
    }
    //Save data for further rendering
    graph.add(number);  //Array of integers, java doesn't let me make array of short
  }
  //Clean old data
  while(graph.size()>MAX_GRAPH_SIZE)
    graph.remove(0);

}

我认为我在arduino方面有问题,因为我在输出中看到了这一点:

  

接收字节:0
  字节收到:-1
  产生的2字节数:-256

Arduino值应该发送大约681.(我有一个1位数的显示来检查大约的值。)

1 个答案:

答案 0 :(得分:0)

  • 在C ++方面,使用htons()s horts从h ost endianness to n etwork endianness(htons:举办网络短片)。
  • 在Java端,从套接字读取,写入ByteArrayOutputStream;获得所有数据后,将此ByteArrayOutputStream的基础字节数组包装到ByteBuffer
  • 使用ByteBuffer的{​​{1}}。
  • 阅读短片