60 lines
1.5 KiB
C++
Executable File
60 lines
1.5 KiB
C++
Executable File
#include <Wire.h>
|
|
|
|
#define Addr 0x1E // 7-bit address of HMC5883 compass
|
|
|
|
|
|
// Assign LED Output PWM Pins
|
|
int Red = 11;
|
|
int Green = 10;
|
|
int Blue = 9;
|
|
|
|
|
|
void setup() {
|
|
// LED
|
|
pinMode(Red, OUTPUT);
|
|
pinMode(Green, OUTPUT);
|
|
pinMode(Blue, OUTPUT);
|
|
Serial.begin(9600);
|
|
delay(100); // Power up delay
|
|
Wire.begin();
|
|
|
|
// Set operating mode to continuous
|
|
Wire.beginTransmission(Addr);
|
|
Wire.write(byte(0x02));
|
|
Wire.write(byte(0x00));
|
|
Wire.endTransmission();
|
|
}
|
|
|
|
void loop() {
|
|
int x, y, z;
|
|
|
|
// Initiate communications with compass
|
|
Wire.beginTransmission(Addr);
|
|
Wire.write(byte(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();
|
|
}
|
|
|
|
// Print raw values
|
|
Serial.print("X="); Serial.print(x);
|
|
//Serial.print(min(255, 255.0 * (512 + x) / 1024.0));
|
|
Serial.print(", Y="); Serial.print(y);
|
|
//Serial.print(min(255, 255.0 * (512 + y) / 1024.0));
|
|
Serial.print(", Z="); Serial.println(z);
|
|
//Serial.println(min(255, 255.0 * (512 + z) / 1024.0));
|
|
|
|
|
|
analogWrite(Red, min(255, 255.0 * (512 + x) / 1024.0));
|
|
analogWrite(Green, min(255, 255.0 * (512 + y) / 1024.0));
|
|
analogWrite(Blue, min(255, 255.0 * (512 + z) / 1024.0));
|
|
delay(100);
|
|
|
|
//delay(500);
|
|
}
|
|
|