Arduino Interrupts, Servo, & IR

I am trying to implement interrupts to run my servo for 1 minute after the button on the controller is pressed. But with my current sketch, the servo only moves if the button is continuously held down. I am not sure where I am going wrong.

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

#define interruptNumber 0 
#define RECV_PIN 2      
#define button1 0xFF30CF 
#define servoPin 10 

Servo myservo;  
IRrecv irrecv(RECV_PIN);
decode_results results;
volatile byte IREventFlag;

// Interval is how long we wait
// add const if this should never change
int interval=60000;
// Tracks the time since last event fired
unsigned long previousMillis=0;


void setup()
{
  pinMode(RECV_PIN, INPUT);//define the interrupt pin as an input
  Serial.begin(9600);
  attachInterrupt(0,InterruptServiceRoutine,CHANGE);
}
 
void loop(){

  
  // Get snapshot of time
   unsigned long currentMillis = millis();
   
  if (IREventFlag==1){
    servo_move();
    // How much time has passed, accounting for rollover with subtraction!
    if ((unsigned long)(currentMillis - previousMillis) >= interval) {
      IREventFlag=0;//reset the flag for the next interrupt
      previousMillis = currentMillis;// Use the snapshot to set track time until next event
    }
  }
}

void InterruptServiceRoutine(){
  if(digitalRead(RECV_PIN)==HIGH){
    digitalWrite(servoPin, HIGH);
    IREventFlag=1;            
  }
  if(digitalRead(RECV_PIN)==LOW){
    digitalWrite(servoPin, LOW);
  }
}

//runs between 0 and 20 deg in increments of 1
void servo_move(){ 
    for (int i = 0; i<20; i++){
        myservo.write(i);
        //delay(10);
        }
    for(int i = 20; i>0; i--){
      myservo.write(i);
      //delay(10);
      }
}

Use the state change detection method to sense when the pin transitions for one state to the other. Detect the change instead of the level.

Would I not be able to solve this with the interrupts?

That does not work as you expect it to work if you're using an AVR based board; 60000 does not fit in an variable of type int and will become a negative value.

Neither am I. I have no experience with servos but it does not sound right that you control the servo pin from your ISR if you have a library that also controls that pin. Maybe this would be better

void InterruptServiceRoutine(){
  if(digitalRead(RECV_PIN)==HIGH){
    IREventFlag=1;            
  }
}

You probably can but it makes life complicated.

And a question: why are you including the IRremote library if you don't use it.

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