How to use Servo library with IRremote library?

When using the Servo library with the IRremote library, the servomotor that's connected to the Arduino twitches. The only thing I could think of is using the detach() method right after write(), but trying this leads to the servomotor disconnecting before finishing the write() command (it stops before reaching the desired angle). I can do a workaround by making a variable to store the last desired angle and implementing an if statement inside the loop() function to check if the current angle has reached the desired angle. This works, but when the servo is detached you can move it by hand which is not something that I'd want. I also tried changing pins.
Does anyone know a working solution to this problem? Is it about ISRs/timers? The servomotor I'm experiencing this issue with is the SG-90... As far as I know, other servos do have the same issue with the same library.

You forgot to tell us which Arduino you have.

This is probably due to a timer conflict, with Timer1. The ServoTimer2 library might solve it.

Do not attempt to power servos or motors from the Arduino 5V output.

Hello again, thanks for your time. I'm using Arduino UNO.
To use this library, do I just call the library header? Or do I need to do other things?

Also, the IRremote library uses timer 2. So wouldn't using timer 2 for the Servo library make this worse?

On an Arduino Uno by default in the servo-library timer1 is used. IRRemote uses timer2 by default. So this should work.

The "documentation" of the servo-library is not worth this name in regard to easy understand which timer is used on which board.

The IRRemote-repo

defines

// ATmega328 and ATmega88
#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega328PB__) || defined(__AVR_ATmega168__) || defined(__AVR_ATmega88P__) || defined(__AVR_ATmega88PB__)
#  if !defined(IR_USE_AVR_TIMER1) && !defined(IR_USE_AVR_TIMER2)
//#define IR_USE_AVR_TIMER1   // send pin = pin 9
#define IR_USE_AVR_TIMER2     // send pin = pin 3
#  endif

default on #define IR_USE_AVR_TIMER2 // send pin = pin 3

the servo-library has

#else  // everything else
#define _useTimer1
typedef enum { _timer1, _Nbr_16timers } timer16_Sequence_t;

So the twitching might be caused by something different.
Anyway it is a good idea to post your complete sketch using this method
You can post code by using this method that adds the code-tags
There is an automatic function for doing this in the Arduino-IDE
just three steps

  1. press Ctrl-T for autoformatting your code
  2. do a rightclick with the mouse and choose "copy for forum"
  3. paste clipboard into write-window of a posting

best regards Stefan

Post your code, using code tags, and a wiring diagram.

Servo twitching is usually due to an inadequate power supply, like trying to use the Arduino 5V output. A 4xAA battery pack will power one or two small servos.

I tried starting from scratch just to make sure that my code/my old wiring isn't the problem.

I started by defining the Servo object, then I wrote one single write() command in setup(). The servomotor worked with no issues at all.

Then I went on and called the IRremote library, still no issues.

After that I put IrReceiver.begin(), and that's when the twitching started.

I also tried connecting the Servomotor directly to the 5V pin, still twitching. So I connected the motor to different batteries, ranging from 4V to 8V. But this didn't fix it either.

I'll go ahead and post this simple test circuit, and the code that reproduces this issue.

#include <Servo.h>
#include <IRremote.h>

constexpr byte servo = 9;
constexpr byte ir = 7;
Servo s;

void setup() {
  
  s.attach(servo);
  s.write(90);
  delay(5000); // no twitching
  
  IrReceiver.begin(ir);
  s.write(120);
  delay(5000); // twitching
  
  IrReceiver.stop();
  s.write(180);
  delay(5000); // no twitching
}

void loop() {}

Do you guys want me to also post my original project as well? This example should be enough to demonstrate what's going on but much simpler.

So I connected the motor to different batteries, ranging from 4V to 8V.

I see that you don't take advice very well.

The servo is rated for 4.5V to 6V maximum, so you may have damaged it by connecting it to 8V. And you may have damaged the Arduino by connecting the servo to the 5V output.

At first, the servo was connected to just 5V with an external battery though. Even with that I noticed the twitching, that was why I even went ahead and tried different batteries/Arduino 5V pin etc... So in other words the twitching was present way before I tried 6V-8V.
I think this servomotor was already damaged when I got it, that'd explain a lot of things.

You should make a test with a demo-code that does nothing more than controlling a single servo to set the servo-horn to different angles with pausing inbetween to see if the twitching occurs or not

How do I make a "test" then? I thought this would be the best way to do it because it's so simple and straightforward with nothing else like other libraries/functions and logic interfering.

servo sweeping slowly
zero IR-remote things = pure test: is hardware of the servo OK?

/* Sweep
  by BARRAGAN <http://barraganstudio.com>
  This example code is in the public domain.

  modified 28 May 2015
  by Michael C. Miller
  modified 8 Nov 2013
  by Scott Fitzgerald

  http://arduino.cc/en/Tutorial/Sweep
*/

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards


void setup() {
  myservo.attach(2);  // attaches the servo on GIO2 to the servo object
}

void loop() {
  int pos;

  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'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

Additionally set servo to a position but not the extreme of 0 or 180
wait 3 seconds then set the second position.


#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards


// easy to use helper-function for non-blocking timing
boolean TimePeriodIsOver (unsigned long &startOfPeriod, unsigned long TimePeriod) {
  unsigned long currentMillis  = millis();
  if ( currentMillis - startOfPeriod >= TimePeriod ) {
    // more time than TimePeriod has elapsed since last time if-condition was true
    startOfPeriod = currentMillis; // a new period starts right here so set new starttime
    return true;
  }
  else return false;            // actual TimePeriod is NOT yet over
}

byte pos = 10;
unsigned long MyTestTimer = 0;                   // Timer-variables MUST be of type unsigned long



void setup() {
  myservo.attach(2);  // attaches the servo on GIO2 to the servo object
  MyTestTimer = millis();
}

void loop() {

  if ( TimePeriodIsOver(MyTestTimer, 3000) ) {
    // if 2000 milliseconds have passed by 
    myservo.write(pos); // tell servo to go to position in variable 'pos'

    if (pos == 160) { // change value of pos
      pos = 10;
    }
    else {
      pos = 160;
    }
  }
}

Try GitHub - ArminJo/LightweightServo: Lightweight Servo library for Arduino for 2 Servos at Pin 9 and 10. Needs only timer1, no interrupts or other resources.. This avoids the twitching.