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 毫秒发送一次数据。
我做错了什么?