Hello,
I'm new to arduino, but not necessarily to programming so I'm guessing the code is written okay, just the idea might be wrong.
I am now facing a problem with my ADXL335 accelerometer, which is supposed to control a servo.
I wrote code which averages 10 values and maps that average value to the servo. Also puts the servo value out on the serial monitor.
Now the strange problem is:
Serial monitor shows perfectly averaged, non jumpy, values, even when accelerometer is moved quickly. But as soon as I plug the servo to the Arduino Uno and Digital 9 (PWM), the accelerometer values become jumpy on the serial monitor and you can see that in erratic servo movement.
Can anyone help with this issue? I have seen the ADXL335 work nicely on videos, but can't get it to work.
If you have time on your hand, you could look at my code.
Thank you!
-Phil
#include <Servo.h>
Servo myservo;
const int xPin = 0;
int val;
int xRead[10];
int i =0;
int total=0;
void setup(){
myservo.attach(9);
Serial.begin(9600);
}
void loop(){
//set total to zero when restarting loop:
total=0;
//loop to get 10 values and average them
for(i=0;i<10;i++){
xRead[i] = analogRead(xPin);
//throw out bad values:
//if bad value bigger than last value+20
if(i>0){
if(xRead[i]>xRead[i-1]+20){
xRead[i]=xRead[i-1];
}
}
//if bad value smaller than last value-20
if(i>0){
if(xRead[i]<xRead[i-1]-20){
xRead[i]=xRead[i-1];
}
}
total= total + xRead[i];
}
//calculate average:
val=total/10;
val= map(val,269,404,0,179);
//limit servo:
if(val>179){
val=179;
}
if(val<0){
val=0;
}
Serial.println(val);
myservo.write(val);
delay(30);
}