IR receiving AND servo control...

I’m trying to use a remote control with a servo. I have the IR part already working well for quite some time.

#include <avr/interrupt.h>
#include <avr/io.h>

#include "myIRlib.h"
#include <Servo.h> 

Servo myservo; 
int IRpin = 2;
boolean changed = false;


void setup() {
  Serial.begin(9600);
  Serial.println("IR Remote");
  
  IrRxFunctions.initPfIr(IRpin);
  
  myservo.attach(6); // if I enable this line, no IR messages anymore!

  
}

void loop()
{
  digitalWrite(statusLed, LOW);
  if (IrRxFunctions.crunchIRData(IRpin) == 1) {
    // do something with the message...
    // ... bunch of lines here...
  }
  
  delay(50);
}

I don’t know why, but as soon as I put myservo.attach in the code, my IR stops working… The IR functions currently don’t use interrupts and that also may be the cause of the problem, but it should not be a problem should it?!

I have no idea what your magic IR-libraries is doing and to be honest, I don't really care either. About your problem I'm pretty sure that your IR-Libary or the rest of your program uses Timer1 in some way. So does the Servo library. Calling Servo.attach will set up Timer1 the way the Servo library likes it and all other uses of that timer won't work any more.

It's time for you now to figure out what uses Timer1 is and to resolve the conflict.

Korman

It is indeed the timer, stupid of me to overlook that!

Thanks a lot, I'll try another timer than for the IR stuff I suppose :)

To save you some grief, try Timer2 and not Timer0. Timer0 is busy updating the millis() and micros() for you.

If the resolution of 4µs (on a 16MHz CPU) is good enough, you might also forget completely about the timer and work with micros() or millis() instead. Just make sure that you do you delay calculation correctly so that the roll-over of the micros or millis doesn't create a problem.

Korman

I'll take that into account. I know enough of the basics of the timers. Changing the whole IR code to external interrupts would best, but that is a next step I guess.

That's easier than doing it with timers. Just read micros() in the interrupt function and save the pulse length when necessary. Always assuming, that 4µs is good enough as a resolution.

Korman

Well I think 4µs is. So I agree that that would be the best way. I have some good experiences with external interrupts, so let's try that then!!! Thanks a lot.

for the time being I solved the problem using a different servo library that uses timer2 instead of timer0.

I might change the libary later.