#include "GY521.h" //Import the GY521 library
GY521 sensor(0x68); //define a GY521 device "sensor" at 0x68
struct Vector3{
float x;
float y;
float z;
}; //define a data structure called vector 3 that holds floats x y and z
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Wire.begin();
if (sensor.wakeup()) {
Serial.println("Sensor initialized successfully.");
} else {
Serial.println("Failed to initialize the sensor.");
while (1); // Halt the program if initialization fails.
}
sensor.setAccelSensitivity(2); // 8g
sensor.setGyroSensitivity(1); // 500 degrees/s
sensor.setThrottle();
sensor.axe = 0;
sensor.aye = 0;
sensor.aze = 0;
sensor.gxe = 0;
sensor.gye = 0;
sensor.gze = 0;
//Initialize the sensor and the serial monitor
delay (1000);
}
void loop() {
OutputSensorData(); //Read Sensor Data and print it to serial monitor
delay(200); //do this 5 times every second
}
Vector3 ReadSensorAngle() {
sensor.read();
return Vector3{sensor.getAngleX(),sensor.getAngleY(),sensor.getAngleZ()};
} //return the sensor's rotational speeds in the x,y, and z directions
Vector3 ReadSensorAccel() {
sensor.read();
return Vector3{sensor.getAccelX(),sensor.getAccelY(),sensor.getAccelZ()};
} //return the sensor's acceleration in the x,y, and z directions
void OutputSensorData() {
Serial.print("Sensor Angle is: (");
Serial.print(ReadSensorAngle().x);
Serial.print(" ");
Serial.print(ReadSensorAngle().y);
Serial.print(" ");
Serial.print(ReadSensorAngle().z);
Serial.print(") ");
//print "Sensor Angle is: (x,y,z)"
Serial.print("Sensor Acceleration is: (");
Serial.print(ReadSensorAccel().x);
Serial.print(" ");
Serial.print(ReadSensorAccel().y);
Serial.print(" ");
Serial.print(ReadSensorAccel().z);
Serial.print(") ");
//print "Sensor Acceleration is: (x,y,z)"
Serial.print("Current Temp is: ");
Serial.print(sensor.getTemperature());
Serial.println("°C");
//print sensor temperature in degrees celcius
Serial.println(""); //print a fresh line
}