Alarm.timerRepeat not working

Hello guys,

I am using Arduino Uno to control two Hitec 31311S HS-311 Servos and I wanted them to sweep back and forth once every 10 seconds using the TimeAlarm library and here’s my code:

#include <Servo.h> 
#include <Time.h>
#include <TimeAlarms.h>
Servo myservo;
Servo myservo1;
int pos = 0;   

 
void setup() 
{ 
  myservo.attach(5);
  myservo1.attach(6);
  Alarm.timerRepeat(10, Repeats);
} 

void loop(){
  Alarm.delay(500);
}

void Repeats()
{ 
  for(pos = 0; pos < 180; pos += 1)  
  {                                  
    myservo.write(pos);
myservo1.write(pos);    
    delay(50);                      
  } 
  delay(1000);
  for(pos = 180; pos>=1; pos-=1)     
  {                                
    myservo.write(pos);
myservo1.write(pos);    
    delay(50);                        
  } 
}

They start sweeping back and forth after 10 seconds but the problem is they don’t stop and they keep on sweeping infinitely and I want them to stop after sweeping once and wait for another 10 seconds to sweep again but I can’t achieve that.

Any ideas?

The problem is that your back and forth sweep takes longer than 10 seconds so that by the time it has happened it is time for it to start again. I suggest that you do not use TimeAlarms for such a trivial timing task and use millis() timing instead.

#include <Servo.h>
Servo myservo;
Servo myservo1;
int pos = 0;
unsigned long startTime = 0;
unsigned long interval = 10000;

void setup()
{
  myservo.attach(5);
  myservo1.attach(6);
}

void loop()
{
  if (millis() - startTime >= interval)
  {
    Repeats();
    startTime = millis();
  }
}

A better version would use millis() for all timing and avoid the use of delay()

If you feel that you must use TimeAlarms then one way would be to increase the alarm period to allow for the time taken by the sweep. ie make the alarm period 28 seconds.

You need to replace EVERY delay() in your code with Alarm.delay(), so that the Alarm library knows that time is passing. As it is, you only tell the Alarm class that time has passed for about 2.5% of the time. Maybe if you wait long enough, the alarm will actually repeat.

Actually I think that the problem is that the alarm does exactly what it is told to and repeats every 10 seconds. The trouble is that the function called by the alarm being triggered takes longer than 10 seconds so that by the time it is finished it is past time for it to be triggered again so it starts again immediately. Changing all the delays to Alarm.delay makes no difference.