I am using the Arduino ServoTimer2 library (because I need to also use the VirtualWire library in the same sketch. I don't know if this problem also exists in the regular Servo library, but I thought it was worth mentioning.
Any time I call servo.attach(pin)
, the servo moves from whatever its current position is to the exact middle of its range (1500 microseconds). This is a problem because my Arduino needs to attach and detach the servo regularly and resetting back to the center defeats the purpose of my project.
I read that calling servo.write(xxxx)
immediately before servo.attach(pin)
would cause it to default to xxxx rather than 1500, but that doesn't seem to work for me (nor do I even understand how that would work if the pin isn't attached...). Any ideas?
*
Edit: My Solution
Thanks to djUniversal's answer, I got it working so that the servo doesn't move when attached. In case anyone else is looking to do the same, all I did was go into ServoTimer2.cpp
and comment out the first 3 lines of the initISR
method. It now looks like this:
static void initISR()
{
// for(uint8_t i=1; i <= NBR_CHANNELS; i++) { // channels start from 1
// writeChan(i, DEFAULT_PULSE_WIDTH); // store default values
// }
servos[FRAME_SYNC_INDEX].counter = FRAME_SYNC_DELAY; // store the frame sync period
Channel = 0; // clear the channel index
ISRCount = 0; // clear the value of the ISR counter;
/* setup for timer 2 */
TIMSK2 = 0; // disable interrupts
TCCR2A = 0; // normal counting mode
TCCR2B = _BV(CS21); // set prescaler of 8
TCNT2 = 0; // clear the timer2 count
TIFR2 = _BV(TOV2); // clear pending interrupts;
TIMSK2 = _BV(TOIE2) ; // enable the overflow interrupt
isStarted = true; // flag to indicate this initialisation code has been executed
}
As soon as I did that and recompiled, the servo stopped moving immediately when it was attached and now moves only when it is written to.