Hi, I have recently been trying to hook up my servo to my light switch in my room and have it be controlled by both a momentary push button and an IR remote.
My goal is to have the servo be able to be in 2 positions, each either turning the light on or off. I tried to make it so the button and the IR codes would be able to tell the current position of the servo and change to be in the opposite position when either the button is pressed or the IR receiver receives the proper code from the remote.
The code I currently have is my best attempt to mash up the two separate codes. One for the button and one for the IR. The momentary button is doing it's job properly when I uploaded the code to my Arduino but when ever I press the IR remote once the servo will continue move back and forth between the two positions without stopping and without me pressing any buttons.
This is my first time posting and I did my best to look for any solutions already out there. Any help to improve the code and solve my problem would be much appreciated. Thank you.
Here is the code
#include <Servo.h>
#include <IRremote.h>
int inPin = 2; // the number of the momentary input pin
int reading; // the current reading from the input pin
int previous = LOW; // the previous reading from the input pin
int IRpin = 11; // pin for the IR sensor
IRrecv irrecv(IRpin);
decode_results results;
Servo myservo;
boolean SRVOstate = false; // Initialize the state of servo as off/down
long time = 0; // the last time the output pin was toggled
long debounce = 200; // the debounce time, increase if the output flickers
void setup()
{
pinMode(inPin, INPUT);
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
myservo.attach(9);
}
void loop()
{
reading = digitalRead(inPin);
if (reading == HIGH && previous == LOW && millis() - time > debounce) //if momenatary is pressed
{
if (SRVOstate == true) //current state of servo
{
SRVOstate = false; //set the new state
myservo.write(80); //servo down posistion
}
else
{
SRVOstate = true; //set the new state
myservo.write(170); //servo up posistion
}
time = millis();
}
previous = reading;
if (irrecv.decode(&results))
{
irrecv.resume(); // Receive the next value
}
if (results.value == 2189279550) //if IR remote value is recieved
{
if (SRVOstate == false) //current state of servo
{
SRVOstate = true; //set the new state
myservo.write(170); //servo up posistion
delay(1000); // keeps the transistion smooth
}
else
{
SRVOstate = false; //set the new state
myservo.write(80); //servo down posistion
delay(1000);
}
}
}