0
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 个字节转到 <<8 位,然后我加上另一个字节,这给了我从 -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 毫秒发送一次数据。

我做错了什么?

4

2 回答 2

1

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

于 2012-09-13T10:18:57.643 回答
0

这将从两个 8 位值中重建一个 16 位值。虽然 16 位会给你超过 [-255,255]。根据您的结尾,您将不得不交换ub1ub2( gyro_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] -> gyro_out_x
  • outByte[2] 和 outByte[3] -> gyro_out_y
  • ETC?
于 2012-09-13T10:22:12.740 回答