GY-271 HMC5883L模塊 電子指南針羅盤模塊 三軸磁場傳感器
#include <Wire.h>
#define Addr 0x1E // 7-bit address of HMC5883 compass
void setup() {
Serial.begin(9600);
delay(100); // Power up delay
Wire.begin();
// Set operating mode to continuous
Wire.beginTransmission(Addr);
Wire.write(0x02);
Wire.write(0x00);
Wire.endTransmission();
}
void loop() {
int x, y, z;
double radx, rady, radz;
// Initiate communications with compass
Wire.beginTransmission(Addr);
Wire.write(0x03);// Send request to X MSB register
Wire.endTransmission();
Wire.requestFrom(Addr, 6);// Request 6 bytes; 2 bytes per axis
if(Wire.available() <=6) {// If 6 bytes available
x = Wire.read() << 8 | Wire.read();
z = Wire.read() << 8 | Wire.read();
y = Wire.read() << 8 | Wire.read();
radx = x / 131.0;
rady = y / 131.0;
radz = z / 131.0;
}
// Print values
Serial.print("X=");
Serial.print(radx);
Serial.print(", Y=");
Serial.print(rady);
Serial.print(", Z=");
Serial.println(radz);
delay(20);
}