Tuesday, February 16, 2016

playing with Gyro sensor GY-291 and Arduino



1. connection.





2. The Script

/* Include the standard wire library */
#include

/* Alternate I2C address of the module */
#define I2C_Add 0x53

/* ADXL345 register addresses */
#define POWER_CTL 0x2D
#define DATA_FORMAT 0x31
#define X_Axis 0x32
#define Y_Axis 0x34
#define Z_Axis 0x36

/* Accelerometer range modes */
#define RANGE_2g 0
#define RANGE_4g 1
#define RANGE_8g 2
#define RANGE_16g 3

void setup()
{
  /* Initialise the I2C bus */
  Wire.begin();  
  
  /* Initialise the serial interface */
  Serial.begin(9600);
  
  /* Initialise the ADXL345 */  
  Init_ADXL345(RANGE_2g);
}

/* Main program */
void loop()
{
  /* Continually read and output all 3 axis to the serial port */
  Serial.print("X: ");
  Serial.print(Read_Axis(X_Axis));
  
  Serial.print(" Y: ");
  Serial.print(Read_Axis(Y_Axis));
  
  Serial.print(" Z: ");
  Serial.println(Read_Axis(Z_Axis));
}

/* Read one of the 3 axis via the I2C interface */
int Read_Axis(byte axis)
{
  int Data;
   
  Wire.beginTransmission(I2C_Add); 
  Wire.write(axis); 
  Wire.endTransmission(); 
  
  Wire.beginTransmission(I2C_Add);
  Wire.requestFrom(I2C_Add, 2);
  
  /* If data is available then read it (2 bytes) */
  if(Wire.available())     
  { 
    Data = (int)Wire.read();
    Data = Data  | (Wire.read() << 8);
  }else
  {
    Data = 0;
  }
    
  Wire.endTransmission();  
  return Data;
}


/* Initialise the ADXL345 */
void Init_ADXL345(byte range)
{
  Wire.beginTransmission(I2C_Add);
  
  /* Set the sensitivity of the module */
  Wire.write(DATA_FORMAT); 
  Wire.write(range); 
  Wire.endTransmission(); 
  
  /* Put the module into measurement mode to start taking measurements */
  Wire.beginTransmission(I2C_Add);
  Wire.write(POWER_CTL); 
  Wire.write(0x08); 
  
  Wire.endTransmission(); 
}


No comments: