#include <Timer.h>
Timer t;
#include <Wire.h>
#include <Servo.h>
Servo myservo;
#define Addr 0x1E // 7-bit address of HMC5883 compass
int x, y, z;
int lastX, avgX;
int histry[2][5];
int pos;
boolean clockDir=true;
double radx, rady, radz;
#include "U8glib.h"
U8GLIB_SSD1306_128X64 u8g(13, 11, 10, 9);
void draw(void) {
// graphic commands to redraw the complete screen should be placed here
//u8g_font_unifont:10*10
//search u8g_font in files to find other settings
u8g.setFont(u8g_font_unifont);
//u8g.setFont(u8g_font_9x18);
//u8g.setFont(u8g_font_osb21);
//u8g.drawStr(X-pos, Y-pos, content);
u8g.drawStr(1, 10, "X:");
char snum[8];
// convert 123 to string [buf]
itoa(x, snum, 10);
u8g.drawStr(20, 10, snum);
if(clockDir){
u8g.drawStr(1, 20, "true");
}else{
u8g.drawStr(1, 20, "false");
}
}
void setup(void) {
pos=0;
t.every(50, takeReading);
Serial.begin(9600);
u8g.setColorIndex(255); // white
Wire.begin();
myservo.attach(12);
// Set operating mode to continuous
Wire.beginTransmission(Addr);
Wire.write(0x02);
Wire.write(0x00);
Wire.endTransmission();
}
void takeReading(){
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();
}
}
void loop(void) {
if(x<380){
if(!myservo.attached()){
myservo.attach(12);
}
if(x<lastX){
clockDir = !clockDir;
}
lastX=x;
if(clockDir){
myservo.write(104);
}else{
myservo.write(108);
}
}else{
myservo.detach();
}
//myservo.detach();
// picture loop
takeReading();
u8g.firstPage();
do {
draw();
} while( u8g.nextPage() );
// rebuild the picture after some delay
delay(200);
}