HMC5883L + OLED128*64IIC
HMC5883L 應平放,IC面朝上(Z軸為垂直)
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// 7-bit address of HMC5883 compass
#define Addr 0x1E
#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);
#define NUMFLAKES 10
#define XPOS 0
#define YPOS 1
#define DELTAY 2
#define LOGO16_GLCD_HEIGHT 16
#define LOGO16_GLCD_WIDTH 16
#if (SSD1306_LCDHEIGHT != 64)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif
void setup() {
Serial.begin(9600);
delay(100); // Power up delay
Wire.begin();
// Set operating mode to continuous
Wire.beginTransmission(Addr);
//label self 0x02
Wire.write(0x02);
Wire.write(0x00);
Wire.endTransmission();
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
}
double radx, rady, radz;
void loop() {
int x, y, z;
// 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;
}
showMsg();
delay(20);
}
void showMsg(){
display.clearDisplay();
display.setTextColor(WHITE);
display.setCursor(1,0);
display.setTextSize(2);
display.print("X:");
display.println(radx);
display.print("Y:");
display.println(rady);
display.print("Z:");
display.println(radz);
display.display();
}