Java字节/位麻烦

时间:2012-09-13 10:05:52

标签: java serial-port arduino

import jssc.SerialPort;
import jssc.SerialPortException;
import org.jfree.ui.RefineryUtilities;

public class Main {

  public static int gyro_out_X, gyro_out_Y, gyro_out_Z, acc_out_X, acc_out_Y, acc_out_Z, adc_pressure, HMC_xo, HMC_yo, HMC_zo;

  public static void main(String[] args) {
    //In the constructor pass the name of the port with which we work
    SerialPort serialPort = new SerialPort("COM4");
    try {

        //Open port
        serialPort.openPort();
        //We expose the settings. You can also use this line - serialPort.setParams(9600, 8, 1, 0);
        serialPort.setParams(SerialPort.BAUDRATE_115200,
                SerialPort.DATABITS_8,
                SerialPort.STOPBITS_1,
                SerialPort.PARITY_NONE);
        while (1 == 1) {

            byte[] sensor_buffer = serialPort.readBytes(21);
            gyro_out_X = ((sensor_buffer[1] << 8) + sensor_buffer[2]);
            gyro_out_Y = ((sensor_buffer[3] << 8) + sensor_buffer[4]);
            gyro_out_Z = ((sensor_buffer[5] << 8) + sensor_buffer[6]);
            acc_out_X = ((sensor_buffer[7] << 8) + sensor_buffer[8]);
            acc_out_Y = ((sensor_buffer[9] << 8) + sensor_buffer[10]);
            acc_out_Z = ((sensor_buffer[11] << 8) + sensor_buffer[12]);
            HMC_xo = ((sensor_buffer[13] << 8) + sensor_buffer[14]);
            HMC_yo = ((sensor_buffer[15] << 8) + sensor_buffer[16]);
            HMC_zo = ((sensor_buffer[17] << 8) + sensor_buffer[18]);

            System.out.println("gyro_out_X: " + gyro_out_X );

            //Closing the port
            //  serialPort.closePort();
        }
    } catch (SerialPortException ex) {
        System.out.println(ex);
    }
  }
}

好的,在这个结构中,我读取了21个字节的代码,1个字节转到&lt;&lt;&lt;&lt;&lt;&lt;&gt;,然后我加上另一个字节,这给了我从-255到255的值。

但在输出中我看到:

 gyro_out_X: 14556
 gyro_out_X: 23857
 gyro_out_X: -15234
 gyro_out_X: -255
 gyro_out_X: 23295
 gyro_out_X: -13346
 gyro_out_X: -255
 gyro_out_X: 30813
 gyro_out_X: 12506
 gyro_out_X: -255
 gyro_out_X: 5104
 gyro_out_X: -10220
 gyro_out_X: 23807
 gyro_out_X: 5246
 gyro_out_X: -463
 gyro_out_X: -27536
 gyro_out_X: -511
 gyro_out_X: -8640
 gyro_out_X: 4306
 gyro_out_X: 16448
 gyro_out_X: 21075
 gyro_out_X: 16450
 gyro_out_X: 220
 gyro_out_X: 16448

每10毫秒发送一次数据。

我做错了什么?

2 个答案:

答案 0 :(得分:1)

您正在获取两个字节(8位)值,并创建一个“短”(16位)值。 16位有符号值可以是-32768到32767.唯一可以得到介于-255和255之间的值的方法是发送数据发送正确位的任何程序。

答案 1 :(得分:0)

这将从两个8位值重建16位值。虽然16bit会给你超过[-255,255]。根据您的终结,您必须交换ub1ub2gyro_out_x = (ub1 << 8) + ub1;)。

int ub1 = outByte[1] & 0xFF;
int ub2 = outByte[2] & 0xFF;
gyro_out_x = (ub2 << 8) + ub1;

另外,你确定你的值是从outByte [1]开始的吗?不是这样的:

  • outByte [0]和outByte [1] - &gt; gyro_out_x
  • outByte [2]和outByte [3] - &gt; gyro_out_y
  • 等?