The code works but the servo is a little jittery anyone have any ideas?
I'm already using a smoothing code to get an average value.
Using the duemilanove and adxl335 and currently not using any capacitors to set bandwidth
Code: Select all
#include <Servo.h>
// Define the number of samples to keep track of. The higher the number,
// the more the readings will be smoothed, but the slower the output will
// respond to the input. Using a constant rather than a normal variable lets
// use this value to determine the size of the readings array.
const int numReadings = 10;
int readings[numReadings]; // the readings from the analog input
int index = 0; // the index of the current reading
int total = 0; // the running total
int average = 0; // the average
const int numReadings2 = 10;
int readings2[numReadings2]; // the readings from the analog input
int index2 = 0; // the index of the current reading
int total2 = 0; // the running total
int average2 = 0; // the average
Servo servox; // create servo object to control a servo
Servo servoy; // create servo object to control a servo
int accelx = 3; // x-axis of accelerometer
int accely = 5; // y-axis of accelerometer
void setup()
{
Serial.begin(9600); //initialize serial communicatoin with computer
servox.attach(9); // attaches the servo on pin 9 to the servo object
servoy.attach(10); // attaches the servo on pin 10 to the servo object
// initialize all the readings to 0:
for (int thisReading = 0; thisReading < numReadings; thisReading++)
readings[thisReading] = 0;
// initialize all the readings to 0:
for (int thisReading2 = 0; thisReading2 < numReadings2; thisReading2++)
readings[thisReading2] = 0;
}
void loop()
{
// subtract the last reading:
total= total - readings[index];
// read from the sensor:
readings[index] = analogRead(accelx);
// add the reading to the total:
total= total + readings[index];
// advance to the next position in the array:
index = index + 1;
// if we're at the end of the array...
if (index >= numReadings)
// ...wrap around to the beginning:
index = 0;
// calculate the average:
average = total / numReadings;
// send it to the computer (as ASCII digits)
Serial.println(average);
// subtract the last reading:
total2= total2 - readings2[index2];
// read from the sensor:
readings2[index2] = analogRead(accely);
// add the reading to the total:
total2= total2 + readings2[index2];
// advance to the next position in the array:
index2 = index2 + 1;
// if we're at the end of the array...
if (index2 >= numReadings2)
// ...wrap around to the beginning:
index2 = 0;
// calculate the average:
average2 = total2 / numReadings2;
// send it to the computer (as ASCII digits)
Serial.print("\t");
Serial.println(average2);
average = map(average, 300, 372, 0, 179); // scale it to use it with the servo (value between 0 and 180)
average2 = map(average2, 300, 368, 0, 179); // scale it to use it with the servo (value between 0 and 180)
servox.write(average);
servoy.write(average2);
delay(50);
}