I am working on reading data from a gyroscope and I am getting the data back just fine but the values are not as expected. I am thinking this is due to an error in my coding after searching around for a solution I came up with a post HERE that states:
Make sure you are reading the output registers correctly, the data is a 16-bit value in 2's complement (i.e the MSB is the sign bit, then 15 bits for the value)
This is very confusing to me and I am unsure if my coding is reading the value as its supposed to. I am using the wiringPi
I2C library to convert existing code for the Arduino to run on the Raspberry Pi. I have my code below I am hoping someone can tell me if they see the proper attempt to read the 16 bit value in 2's compliment. Inside the getGyroValues
function is the only place I could see this happening. Is my code reading the values correctly?
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#include <wiringPi.h>
#include <wiringPiI2C.h>
#define CTRL_REG1 0x20
#define CTRL_REG2 0x21
#define CTRL_REG3 0x22
#define CTRL_REG4 0x23
int fd;
int x = 0;
int y = 0;
int z = 0;
int main (){
fd = wiringPiI2CSetup(0x69); // I2C address of gyro
wiringPiI2CWriteReg8(fd, CTRL_REG1, 0x1F); //Turn on all axes, disable power down
wiringPiI2CWriteReg8(fd, CTRL_REG3, 0x08); //Enable control ready signal
wiringPiI2CWriteReg8(fd, CTRL_REG4, 0x80); // Set scale (500 deg/sec)
delay(100); // Wait to synchronize
void getGyroValues (){
int MSB, LSB;
LSB = wiringPiI2CReadReg16(fd, 0x28);
MSB = wiringPiI2CReadReg16(fd, 0x29);
x = ((MSB << 8) | LSB);
MSB = wiringPiI2CReadReg16(fd, 0x2B);
LSB = wiringPiI2CReadReg16(fd, 0x2A);
y = ((MSB << 8) | LSB);
MSB = wiringPiI2CReadReg16(fd, 0x2D);
LSB = wiringPiI2CReadReg16(fd, 0x2C);
z = ((MSB << 8) | LSB);
}
for (int i=0;i<10;i++){
getGyroValues();
// In following Divinding by 114 reduces noise
printf("Value of X is: %d\n", x / 114);
printf("Value of Y is: %d\n", y / 114);
printf("Value of Z is: %d\n", z / 114);
int t = wiringPiI2CReadReg8(fd, 0x26);
t = (t*1.8)+32;//convert Celcius to Fareinheit
int a = wiringPiI2CReadReg16(fd,0x2B);
int b = wiringPiI2CReadReg16(fd,0x2A);
printf("Y_L equals: %d\n", a);
printf("Y_H equals: %d\n", b);
int c = wiringPiI2CReadReg16(fd,0x28);
int d = wiringPiI2CReadReg16(fd,0x29);
printf("X_L equals: %d\n", c);
printf("X_H equals: %d\n", d);
int e = wiringPiI2CReadReg16(fd,0x2C);
int f = wiringPiI2CReadReg16(fd,0x2D);
printf("Z_L equals: %d\n", e);
printf("Z_H equals: %d\n", f);
printf("The temperature is: %d\n\n\n", t);
delay(500);
}
};