Servo library and interrupts

Can I use servo.write() inside an interrupt function callback like in the example below?

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

Servo myservo; 
Timer t;

volatile int step = 0;

setup()
{
 t.every(10, rotate);
	myservo.attach(9); 
   step = 0;
}

loop()
{
	t.update();
}

rotate()
{
  myservo.write(step); 
  step++; 
}

I don't see why not, but the 20ms update cycle of a servo is not exactly the sort of territory where an interrupt is necessary or appropriate.

BTW. sp. "void loop () {", "void setup () {" etc

1 Like

Make sure that the timer and servo libraries use different timers. Such conflicts are common.

1 Like

I was worried that myservo.write() use some interrupts.
Then what should I do if I want to update it every 20ms, but I don't want to use delays?

Cooperative multitasking, aka " blink without delay"

Study this excellent tutorial: https://www.baldengineer.com/blink-without-delay-explained.html

I was worried that myservo.write() use some interrupts.

To answer questions like that (and also learn if there are timer conflicts), examine the library source code: https://github.com/arduino-libraries/Servo/tree/master/src

1 Like

You can disable timers in conflict in this way:

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.