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);
}
// 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;
}
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);
IF Statements again… (This works similar to constrain)