Hi,
I'm just starting out with the Arduino - and loving it too. I'm trying to control a servo. I've got it wired onto pin 9. I have a simple sketch (not using the servo library - thought I'd do it by hand to help learn...) which allows me to type <> or . to move the servo left, right or centre it. By and large it works, but if I enter a string like '<<<<.>>>>....>' sometimes the servo just dies - offers no resistance to manual rotation and doesn't obey any inputs. All debugging gives expected results.
Here's the sketch:
const int servoPin = 9;
const int fullLeft = 900;
const int centre = 1500;
const int fullRight = 2100;
const int turnRate = 100;
const int refreshPeriod = 20; //20ms
int lastRefresh = 0;
void setup()
{
Serial.begin(9600);
Serial.println("Enter '<' to turn left, '>' to turn right or '.' to centre");
pinMode(servoPin,OUTPUT);
}
void loop()
{
int ch;
int pulseWidth = centre;
for(;;){
if (Serial.available()) {
ch = Serial.read();
if (ch=='<') {
Serial.print("Sub ");
Serial.print(turnRate,DEC);
Serial.print(" from pulseWidth to give ");
pulseWidth -= turnRate;
Serial.println(pulseWidth,DEC);
}
if (ch=='>') {
Serial.print("Add ");
Serial.print(turnRate,DEC);
Serial.print(" from pulseWidth to give ");
pulseWidth += turnRate;
Serial.println(pulseWidth,DEC);
}
if (ch=='.') {
pulseWidth = centre;
}
// Prevent over ranging
pulseWidth = pulseWidth>fullRight?fullRight:pulseWidth;
pulseWidth = pulseWidth<fullLeft?fullLeft:pulseWidth;
Serial.print("New pulseWidth is ");
Serial.println(pulseWidth,DEC);
}
if (millis()>lastRefresh+refreshPeriod) {
digitalWrite(servoPin,HIGH);
delayMicroseconds(pulseWidth);
digitalWrite(servoPin,LOW);
lastRefresh = millis();
}
}
}
Any ideas as to what's going wrong here would be appreciated.
Thanks, Mark