Sharing timer 1 with Servo.h and my own code

Hello!

I have an RFID controlled cat flap, which consists of a few IR sensors, RFID decoding hardware and a flap actuated by a servo.

I need to use timer 1 for reading biphase encoded signals from RFID hardware, but I also need to use a servo. I currently use SoftwareSerial, but it's not great. I don't need the biphase decoder code and associated timer to run while the servo code runs, so I so I stop timer 1 and run servo.attach(N). Unfortunately it seems this doesn't work; Servo.h breaks when I use the same timer for anything else even when using detach() and attach(); the servo motor doesn't move at all.

Looking through the Servo library code, it appears to re-setup the timers whenever servo.attach(N) is called, so it should work, since my code isn't "overlapping" in its use of timer 1. My code is several large-ish files, so I've snipped out the relevant bits and attached here.

If anyone has any idea what's going on, I would appreciate your help! Thanks!

rfidControl.cpp

void rfidControl::setupRfidTimers(){
    PRR &= ~(1 << PRTIM1);          // Make sure Timer1 is enabled (Power Reduction Register)
    TCCR1A = 0 ;                    // Normal counting mode
    TCCR1B = B011 ;         // Set clock bits
    TCCR1B |= _BV(ICES1);           // Edge Select: Trigger on rising edge
    
    TIMSK1 |= _BV(ICIE1) | _BV(TOIE1);   // enable input capture interrupt and overflow interrupt for timer 1

    TCNT1=0;

}

void rfidControl::stop(){
    rfid_state=STOP;
    
    //stop RFID timers, all register bits are zero by default
    TCCR1A = 0;
    TCCR1B = 0;
    TIMSK1 = 0;
}

bool rfidControl::checkAuth(){
//returns true if cat allowed through, false if not
}

ISR(TIMER1_CAPT_vect) {
//biphase decoder
}

catflap.ino

#include <Servo.h>

Servo flapServo;


setup(){
}

loop(){

if (rfidControl.checkAuth()){

     rfidControl.stop();
     openFlap();
     rfidControl.setupRfidTimers();

}


openFlap(){
     flapServo.attach(2);
     delay(10);
     flapServo.write(15);
     delay(2000);
     flapServo.write(118);
     delay(1000);
     flapServo.detach();
}

IIRC, SoftwareSerial also wants Timer 1. There is another servo library that uses timer 2.

Thanks for your reply! Apparently it does exist but timer2 is only 8 bit, so the resolution is poor: about 13° per step.