#include <Servo.h>
int i;
const int xPin = 0;
const int yPin = 1;
const int zPin = 2;
int minVal = 265;
int maxVal = 402;
double x;
double y;
double z;
Servo myservoLeft;
// the setup routine runs once when you press reset:
void setup() {
Serial.begin(9600);
myservoLeft.attach(9);
}
// the loop routine runs over and over again forever:
void loop() {
int xRead = analogRead(xPin);
int yRead = analogRead(yPin);
int zRead = analogRead(zPin);
//convert read values to degrees -90 to 90 - Needed for atan2
int xAng = map(xRead, minVal, maxVal, -90, 90);
int yAng = map(yRead, minVal, maxVal, -90, 90);
int zAng = map(zRead, minVal, maxVal, -90, 90);
//Caculate 360deg values like so: atan2(-yAng, -zAng)
//atan2 outputs the value of -π to π (radians)
//We are then converting the radians to degrees
x = RAD_TO_DEG * (atan2(-yAng, -zAng) + PI);
y = RAD_TO_DEG * (atan2(-xAng, -zAng) + PI);
z = RAD_TO_DEG * (atan2(-yAng, -xAng) + PI);
Serial.print("x: ");
Serial.print(x);
Serial.print(" | y: ");
Serial.print(y);
Serial.print(" | z: ");
Serial.println(z);
delay(100);
if (z >=76){ //right
delay(100);
for ( i = 0 ; i < 90 ; i+=10)
{
myservoLeft.write(i);
delay(100);
}
for ( i = 90 ; i > 0 ; i-=10)
{
myservoLeft.write(i);
delay(100);
}
}
if ( (z >= 50 )&&(z <= 75)){ //middle
myservoLeft.write(60);
delay(100);
}
if ( z <= 49){ //left
delay(100);
for ( i = 90 ; i < 180 ; i+=10)
{
myservoLeft.write(i);
delay(100);
}
for ( i = 180 ; i > 90 ; i-=10)
{
myservoLeft.write(i);
delay(100);
}
}
}
What is the model of the accelerometer?
Also, would you please out the values directly read from the accelerometer, as soon as it’s read.
Something Ike:
Serial.print("xRead = “);
Serial.print(xRead);
Serial.print(”, yRead = “);
Serial.print(yRead);
Serial.print(”, zRead = ");
Serial.println(zRead);
I can’t think of anything to ask other than to check that this is actually an analog output sensor rather than an I2C sensor.
All of my IMUs are serial devices of some kind (I2c or SPI).
I hope this helps.