|
CLASS DOCUMENTS
REPORTS & ASSIGNMENTS
CLASS CONTENT
USING THIS SITE
registered authors login here You are: (logout) For more on PMWiki, see pmwiki.org |
Micro Mag Processing
//processing code for reading data from a magnetometer
//and calculating 2-dimensional orientation
//by Daniel Soltis
import processing.serial.*;
Serial port;
boolean firstContact = false;
int x;
int y;
int z;
void setup() {
size(640, 480);
port = new Serial(this, Serial.list()[0], 9600);
port.write(65);
println("OK let's go!");
}
void draw(){
background(0);
//if you can't get the serial port to respond, try again
if (firstContact == false) {
delay(300);
port.write(65);
}
//translate the x and y data from the magnetometer
//into a single orientation reading
float heading = 0;
if (x == 0 && y < 0){
heading = PI/2;
}
if (x == 0 && y > 0){
heading = 3*PI/2;
}
if (x < 0){
heading = PI - atan(float(y)/float(x));
}
if (x > 0 && y < 0){
heading = -atan(float(y)/float(x));
}
if (x > 0 && y > 0) {
heading = 2*PI - atan(float(y)/float(x));
}
//this shows a line in the middle that shows the orientation of the magnetometer
strokeWeight(4);
stroke(255);
line(width/2, height/2, width/2 + 100*cos(heading), height/2 + 100*sin(heading));
}
//get data from the magnetometer
void serialEvent(Serial port) {
if (firstContact == false) {
firstContact = true;
}
//read the data as a string, split it into parts, ad turn them into numbers
String input = port.readStringUntil(13);
if (input != null){
String[] parts = input.split(",");
x= int(parts[0]);
y= int(parts[1]);
z =int(parts[2]);
}
port.write(65);
}
|