I'm trying to move a servo motor according to an audio stream. But I noticed that as soon as servo gets connected, there is noise in the analog read value. I removed everything and only connected A0 to GND, the servo to 5V, GND and Pin 9, uploaded the below code and watched the serial monitor. I got noise in analog input with average value of 30 and a max of 40. If I remove the servo, I get a flat 0 reading, as expected. Is this behavior expected from a servo and how to prevent it from polluting analog inputs? I tried adding 0.1uF and 10uF caps to servo power pins but was of no use.
-Antzy
#include <Servo.h>
Servo myservo; // create servo object to control a servo
int pos = 0; // variable to store the servo position
int sensorValue;
void setup()
{
Serial.begin(9600);
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop()
{
for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
Serial.print("{");
Serial.print("input");
Serial.print(",T,");
Serial.print(getMaxVal());
Serial.println("}");
}
for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
// print out the value you read:
Serial.print("{");
Serial.print("input");
Serial.print(",T,");
Serial.print(getMaxVal());
Serial.println("}");
}
}
int getMaxVal()
{
int maxVal = 0;
for(int i=0;i<100;i++)
{
sensorValue = analogRead(A0);
if(sensorValue > maxVal)
maxVal = sensorValue;
}
return maxVal;
}