-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode
More file actions
73 lines (53 loc) · 1.37 KB
/
code
File metadata and controls
73 lines (53 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <Wire.h>
const int MPU_ADDR = 0x68;
int16_t gyroX, gyroY, gyroZ;
float gyroXcal, gyroYcal, gyroZcal;
float yaw = 0.0;
unsigned long previousTime, currentTime;
float elapsedTime;
void setup() {
Wire.begin();
Serial.begin(9600);
Wire.beginTransmission(MPU_ADDR);
Wire.write(0x6B);
Wire.write(0);
Wire.endTransmission(true);
Wire.beginTransmission(MPU_ADDR);
Wire.write(0x1B);
Wire.write(0x00);
Wire.endTransmission(true);
calibrateGyro();
previousTime = millis();
void loop() {
readGyro();
currentTime = millis();
elapsedTime = (currentTime - previousTime) / 1000.0;
previousTime = currentTime;
yaw += (gyroZ - gyroZcal) * elapsedTime;
Serial.print("Yaw: ");
Serial.println(yaw);
delay(10);
}
void readGyro() {
Wire.beginTransmission(MPU_ADDR);
Wire.write(0x43);
Wire.endTransmission(false);
Wire.requestFrom(MPU_ADDR, 6, true);
gyroX = (Wire.read() << 8) | Wire.read();
gyroY = (Wire.read() << 8) | Wire.read();
gyroZ = (Wire.read() << 8) | Wire.read();
}
void calibrateGyro() {
int numReadings = 2000;
long gyroXsum = 0, gyroYsum = 0, gyroZsum = 0;
for (int i = 0; i < numReadings; i++) {
readGyro();
gyroXsum += gyroX;
gyroYsum += gyroY;
gyroZsum += gyroZ;
delay(3);
}
gyroXcal = gyroXsum / numReadings;
gyroYcal = gyroYsum / numReadings;
gyroZcal = gyroZsum / numReadings;
}