IR Remote Help!

I'm new to Arduino coding and I'm trying to program an IR receiver to move a servo when I click a button on the remote, I have the serial monitor display when an IR hex code is received and it works a couple of times moving the servo where I want it. but then after 2-8 times of getting it to work the serial monitor displays a whole bunch of random codes and the remote stops working. if anyone can check out the Arduino code too see if I have any errors I would greatly appreciate it. Thank you
CODE:
#include <IRremote.h>
#include <Servo.h>
int RECV_PIN = 11;

Servo myservo;

IRrecv irrecv(RECV_PIN);

decode_results results;

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

void loop() {
if (irrecv.decode(&results)) {
Serial.println(results.value, HEX);
irrecv.resume(); // Receive the next value
if(results.value==0xFFA25D){
myservo.attach(9);
myservo.write(11);
delay(500);
myservo.detach();
}
else if(results.value==0xFF629D){
myservo.attach(9);
myservo.write(58);
delay(500);
myservo.detach();
}
}
delay(100);
}

Well, for one thing you need to auto format the code with ctrl-T in the IDE, and then use code tags when posting it in the forum. This is all explained in the introductory threads at the top of the forum.

By the way, you should not attach the servo every time through loop(). Do it once in setup(), and there is normally no need to detach it. So maybe fix that and repost (properly) if it still doesn't work...

It sounds like a hardware problem, What is your power supply for the servo. You could also have noisey or lose connections, I would double check all the connections and connect a volt meter and see what happens to the processor voltage as you click the button(s). I am assuming the code is ok as it works a few times then crashes. From what I am reading this is repeatable.

Duplicate topics merged

Why did you post the second one ?

attaching the servo-pin should be done only one time in the setup-function.

detaching should only be done if you use the IO-pin for something else.
(very rare case which would require some special mode "you can disconnect servo now")

continuosly attaching and detaching can cause current-spikes. If you supply the servo from a 5V-pin of the arduino this
can overload the voltage-regulator of the Arduino which makes the Arduino reset.

best regards Stefan

Also, for trouble shooting, you can attempt to isolate the problem by commenting out all the servo related statements and seeing if the results in the serial monitor are then stable. Also add some Serial.print() statements within the 'if' statement.

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