Limit servo position between 0 and 180

I have a project going to use my TV IR Remote to operate the volume of a Sound Bar. I am attempting to use a servo to operate an analog volume control. I have a sketch that I have hacked together that works but I need to limit the range of the servo between 0 and 180.

Any help appreciated

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

const byte RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);
Servo myservo; 

byte position = 0; // range 0-180
boolean newIRdata = false;
unsigned long IRinput;

decode_results results;

void setup()
{
  Serial.begin(9600);
  myservo.attach(9);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results))
  {
    IRinput = results.value;
    irrecv.resume(); // Receive the next value
    newIRdata = true;
  }
  if(newIRdata == true)
  {
   Serial.println(IRinput, HEX);
      switch(IRinput)
    {
     // rotate up 5 degree per button push 
     case(1752382022): // Vol Up button
     position += 5;
     Serial.println(position);
     break;
     
     // rotate down 5 degree per button push
     case(2209452902): // Vol Down button
     position -= 5;
     Serial.println(position);
     break;     
    }
     IRinput = 0;
     newIRdata = false;   
  }
  myservo.write(position);
  delay(500);
}

Rather than limit the value, do you think you could constrain the value?

OK Groove, newby here. How would I use the constrain? In an if statement?

Did you read the link I posted?

Yes and I have tried using constrain in several ways. I thought this would be correct:

// rotate down 5 degree per button push
case(2209452902): // Vol Down button
constrain (position -= 5, 0, 180);
Serial.println(position);
break;

But I still move the servo below 0 (per the serial monitor readout)

Hi,

You have 3 options:

  1. You simply need to use IF statements:
// The IF statements dont allow you to substract 5 to Pos when the pos is <= 0

//Vol Down case:

  if(!(Position <= 0)) {
    Position -= 5;
  }


// IMPORTANT: The "!" inverts the output, so if the Pos is >= 0, you CANT add 5



//Vol Up case:

  if(!(Position >= 180)) {
    Position += 5;
  }
  1. Constrain like this form:
// Here you can substract 5 when Pos is 0, but the constrain func takes it back to 0

// Vol Up case:
Position += 5;
Position = constrain(Position, 0, 180);


// Vol Down case:
Position -= 5;
Position = constrain(Position,0,180);
  1. IF Statements again… (This works similar to constrain)
// UP

Pos += 5;
if(Pos > 180) { 
  Pos = 180;
}


// DOWN

Pos -= 5;
if(Pos < 0){
  Pos = 0;
}

Same results but different methods…

I think that’s what you want

This code worked great, thanks TheRocketGuy and sorry for the late reply.

You could just use a 180° servo...