The code I found on the Arduino site gave me a series of numbers however I had no idea what those numbers meant. I found some code on a blog that helped me visually see the range of numbers that my sensor was giving me. The blog is in Portuguese but I found out that Processing and Arduino are universal languages. I didn't understand the comments but i was still able to configure the code to work with my particular sensor. The code only uses the x and y axis. The code allows your sensor to flip and rotate the shape on screen
Arduino code
void setup() {
Serial.begin(9600);
}
void loop() {
int xValue = analogRead(A0);
int yValue = analogRead(A1);
int zValue = analogRead(A2);
Serial.print(xValue);
Serial.print(",");
Serial.print(yValue);
Serial.print(",");
Serial.print(zValue);
Serial.println(",");
}
Processing Code
import processing.serial.*;
Serial myPort;
float xMag, yMag = 0;
int xMin = 200;
int yMin = 200;
int zMin = 200;
int xMax = 0;
int yMax = 0;
int zMax = 0;
void setup()
{
size(640, 360, P3D);
noStroke();
colorMode(RGB, 1);
println(Serial.list());
myPort = new Serial(this, Serial.list()[0], 9600);
myPort.bufferUntil('\n');
}
void draw()
{
background(0.5);
pushMatrix();
translate(width/2, height/2, -30);
rotateX(-xMag);
rotateZ(yMag);
scale(90);
beginShape(QUADS);
fill(1, 0, 0); vertex(-1, 0.5, 1);
fill(1, 0, 0); vertex( 1, 0.5, 1);
fill(1, 0, 0); vertex( 1, -0.5, 1);
fill(1, 0, 0); vertex(-1, -0.5, 1);
fill(0, 1, 0); vertex( 1, 0.5, 1);
fill(0, 1, 0); vertex( 1, 0.5, -1);
fill(0, 1, 0); vertex( 1, -0.5, -1);
fill(0, 1, 0); vertex( 1, -0.5, 1);
fill(1, 0, 0); vertex( 1, 0.5, -1);
fill(1, 0, 0); vertex(-1, 0.5, -1);
fill(1, 0, 0); vertex(-1, -0.5, -1);
fill(1, 0, 0); vertex( 1, -0.5, -1);
fill(0, 1, 0); vertex(-1, 0.5, -1);
fill(0, 1, 0); vertex(-1, 0.5, 1);
fill(0, 1, 0); vertex(-1, -0.5, 1);
fill(0, 1, 0); vertex(-1, -0.5, -1);
fill(0, 0, 1); vertex(-1, 0.5, -1);
fill(0, 0, 1); vertex( 1, 0.5, -1);
fill(0, 0, 1); vertex( 1, 0.5, 1);
fill(0, 0, 1); vertex(-1, 0.5, 1);
fill(0, 0, 1); vertex(-1, -0.5, -1);
fill(0, 0, 1); vertex( 1, -0.5, -1);
fill(0, 0, 1); vertex( 1, -0.5, 1);
fill(0, 0, 1); vertex(-1, -0.5, 1);
endShape();
popMatrix();
}
void serialEvent (Serial myPort) {
int xValue;
int yValue;
String inString = myPort.readStringUntil('\n');
if (inString != null) {
String[] tokens = inString.split(",");
if(tokens.length == 4) {
xValue = int(tokens[0]);
if (xValue > xMax) xMax = xValue;
if (xValue < xMin) xMin = xValue;
xValue = int(map(xValue,xMin,xMax,-90,90));
if (abs(xValue) > 6) { // pour éviter le tremblement du au bruit
xMag = xValue * PI / 180.0;
}
yValue = int(tokens[1]);
if (yValue > yMax) yMax = yValue;
if (yValue < yMin) yMin = yValue;
yValue = int(map(yValue,xMin,xMax,-90,90));
if (abs(yValue) > 6) { // pour éviter le tremblement du au bruit
yMag = yValue * PI / 180.0;
}
}
}
}
No comments:
Post a Comment