Converting 2 8 bit integers into a 16 bit?

조회 수: 26 (최근 30일)
Mustafa Abu-Mallouh
Mustafa Abu-Mallouh . 2018년 12월 23일
댓글: Mike Faulkner . 2023년 6월 1일
I am pulling data from an MPU6050 accelerometer using an Arduino uno and the outputs from the device are 2 8 bit integers. Here is my code for pulling the data from the accelerometer (example for the X-acceleration):
sensitivity = 16384;
g_level = 2;
% Read X Accel
x1 = readRegister(mpu,59,'uint8'); % Reads bits 15:8 from register 59
x2 = readRegister(mpu,60,'uint8'); % Reads bits 7:0 from register 60
X = swapbytes( [x2 x1] );
X_accel(i) = double( typecast(X,'uint16') ) / sensitivity - g_level;
The variable x1 contains bits 15 to 8 and x2 contains bits 7:0. The conversion I am using puts the code on the proper ±2 g scale I was expecting to receive but the actual values make no sense.
Attached is a plot of the acceleration values I am getting; the y-axes of the subplots should be in units of G and the accelerometer was fixed (except for the pulse at around index 65-70) and oriented with the positive z-axis set vertical (gravity in the negative z direction).
Am I converting the 8 bit integers into the 16 bit integer correctly?
Thank you!
  댓글 수: 2
Samuel Louise
Samuel Louise 2018년 12월 30일
Hi Mustapha,
I am working on a very similar project as you but with an MPU9250 and arduino Mega 2560. I was wondering whether we could share knowledge and help each other get to the appropriate level of confidence. If this would interest you, please get in touch.
Mike Faulkner
Mike Faulkner 2023년 6월 1일
Try this: Take the Byte with the MSBs shift it to the left by 8 bit places (x by 256) and then add the Byte with the LSBs
X= X1*256 + X2 (if bits 15:8 are the MSBs)
This worked for me ... good luck

댓글을 달려면 로그인하십시오.

채택된 답변

Guillaume 2018년 12월 23일
swapbytes on an array of uint8 is never going to swap anything. If you want to change the order of the two bytes, then simply concatenate them the other way round:
X = [x1, x2]; %instead of [x2, x1]
Your conversion from X to 16-bit integer is correct, so the above is the only thing I can see going wrong. If x1 is indeed bit 15:8 then it should be [x1, x2].

추가 답변 (0개)


Help CenterFile Exchange에서 MATLAB Support Package for Arduino Hardware에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by