Step 6: Final Step

We combined both the servo code and accelerometer code. From the values we found earlier , we added it to the code to make the motors turn at the correct value.

The values are not very accurate. We found it difficult to pinpoint an exact value,it still isn't a perfect set of  "ears" as it doesn't turn everytime we turn our heads. 

Final code:
===================================================
#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); 
}
  }

   
 
}
===================================================

It's done!
 
Remove these adsRemove these ads by Signing Up
Pro

Get More Out of Instructables

Already have an Account?

close

PDF Downloads
As a Pro member, you will gain access to download any Instructable in the PDF format. You also have the ability to customize your PDF download.

Upgrade to Pro today!