This is my first post here and my forum browsing has been far from exhaustive so bear with me...
I am attempting to control 2 servos with a 3-axis accelerometer.
The servos operate smoothly when controlled by analogue potentiometers.
The serial out from the accelerometer is smooth when servos are not connected.
Attaching one servo disturbs the accelerometer output (all three values) at regular intervals.
Attaching the other makes the whole thing go haywire.
I have considered using a lowpass filter, but really I want to remove the cause of the problem.
Any help appreciated. Code is below.
/* Using a MMA7361 (MMA7260) accelerometer to control 2 servos
Semi working. Chris Killer 25/11/11
Assume accelerometer readings for x and y are proportional to
pitch and roll respectively
Accelerometer calibrated & working well, but gets noisy when
servos are connected. Voltage to servo is smooth when disconnected.
*/
#include <Servo.h>
Servo myservo0; // create servo object to control a servo
Servo myservo1;
int x0; // set up the x,y,z axis
int y0;
int z0;
int xcal;
int ycal;
int zcal;
int slp_pin = 5;
int pitch;
int roll;
int vertangle;
int servo0; // inputs to servos
int servo1;
//const int cal = 7; // calibration button hooked into digital pin 7
//
//int calState = 0;
void setup(){
Serial.begin(9600); // open the Serial port and run it at 9600 baud
// pinMode(cal, INPUT); // set the pinMode of the calibration button to INPUT
myservo0.attach(8); // attaches the servo on pin 2 to the servo object
myservo1.attach(9);
digitalWrite(slp_pin, HIGH); // wake up!
delay(500); // because pressing the button can accelerate it
zcal = analogRead(5); // inaccurate for some reason
delay(500); // for some reason it needs these delays to calibrate properly
xcal = analogRead(3);
delay(500);
ycal = analogRead(4);
}
void loop(){
x0 = analogRead(3);
y0 = analogRead(4);
z0 = analogRead(5);
pitch = x0 - xcal; // approximate
pitch = map(pitch, 0, 255, 0, 90);
Serial.print(pitch);
// delay(5);
Serial.print(" : ");
// delay(5);
roll = y0 - ycal;
roll = map(roll, 0, 255, 0, 90);
Serial.print(roll);
// delay(5);
Serial.print(" : ");
// delay(5);
vertangle = z0 - zcal;
vertangle = map(vertangle, 0, 255, 0, 90);
Serial.println(vertangle);
// delay(50);
servo0 = 30 + pitch + roll;
myservo0.write(servo0);
delay(15);
servo1 = 30 + pitch - roll;
myservo1.write(servo1);
delay(15);
}