-
Notifications
You must be signed in to change notification settings - Fork 0
/
magnetometer_sensor.ino
73 lines (62 loc) · 2.5 KB
/
magnetometer_sensor.ino
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>
#include <Adafruit_Sensor.h>
#include <Adafruit_LSM303_U.h>
/* Assign a unique ID to this sensor at the same time */
Adafruit_LSM303_Mag_Unified mag = Adafruit_LSM303_Mag_Unified(12345);
#define SERIAL_BAUD 115200
void displaySensorDetails(void)
{
sensor_t sensor;
mag.getSensor(&sensor);
Serial.println("------------------------------------");
Serial.print ("Sensor: "); Serial.println(sensor.name);
Serial.print ("Driver Ver: "); Serial.println(sensor.version);
Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id);
Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println(" uT");
Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println(" uT");
Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println(" uT");
Serial.println("------------------------------------");
Serial.println("");
delay(500);
}
void setup(void)
{
#ifndef ESP8266
while (!Serial); // will pause Zero, Leonardo, etc until serial console opens
#endif
Serial.begin(SERIAL_BAUD);
Serial.println("Magnetometer Test"); Serial.println("");
/* Enable auto-gain */
mag.enableAutoRange(true);
/* Initialise the sensor */
if(!mag.begin())
{
/* There was a problem detecting the LSM303 ... check your connections */
Serial.println("Ooops, no LSM303 detected ... Check your wiring!");
while(1);
}
/* Display some basic information on this sensor */
displaySensorDetails();
}
void loop(void)
{
/* Get a new sensor event */
sensors_event_t event;
mag.getEvent(&event);
/* Display the results (magnetic vector values are in micro-Tesla (uT)) */
Serial.print("X: "); Serial.print(event.magnetic.x); Serial.print(" ");
Serial.print("Y: "); Serial.print(event.magnetic.y); Serial.print(" ");
Serial.print("Z: "); Serial.print(event.magnetic.z); Serial.print(" ");Serial.println("uT");
/* Note: You can also get the raw (non unified values) for */
/* the last data sample as follows. The .getEvent call populates */
/* the raw values used below. */
Serial.print("X Raw: "); Serial.print(mag.raw.x); Serial.print(" ");
Serial.print("Y Raw: "); Serial.print(mag.raw.y); Serial.print(" ");
Serial.print("Z Raw: "); Serial.print(mag.raw.z); Serial.println("");
float heading = atan2(event.magnetic.y,event.magnetic.x)*180/3.14159;
if(heading < 0)
heading +=360;
Serial.print("Magnetic North: "); Serial.println(heading);
/* Delay before the next sample */
delay(500);
}