#include <IRremote.h>
int input_pin = 2; // IR port
IRrecv irrecv(input_pin); //IR port
decode_results results;
unsigned long currentButtonCode;
unsigned long lastButtonCode;
void setup()
{
Serial.begin(9600);
irrecv.enableIRIn(); // turn on IR
pinMode(6, OUTPUT); //motor PWM signal
pinMode(7, OUTPUT); //motor output
pinMode(8, OUTPUT); //motor output
timerinit();
}
void timerinit() {
TCCR1A = 0x00; //Normal port operation
TIMSK1 |= (1 << TOIE1); //enable overflow interrupts
sei(); //enable global interrupts
}
void start() {
TCNT1 = 20535; //65535-40000 from calculator
TCCR1B = 0x0000011; //64 prescaler
}
void stop() {
TCCR1B = 0x00; // (timer stopped)
}
ISR(TIMER1_OVF_vect) { turn off motor
analogWrite(6, 0); //
digitalWrite(7, LOW);
digitalWrite(8, LOW);
stop();
}
void loop() {
if (irrecv.decode(&results)) {
currentButtonCode = results.value; //ignoring reapeat 0xFFFFFF
if (currentButtonCode == 0xFFFFFFFF) { //ignoring reapeat 0xFFFFFF
currentButtonCode = lastButtonCode; //ignoring reapeat 0xFFFFFF
} else {
lastButtonCode = currentButtonCode; ///ignoring reapeat 0xFFFFFF
}
Serial.print(F("result = 0x")); //received code
Serial.println(currentButtonCode, HEX); // conversion to HEX
irrecv.blink13(true); // blink LEDs when code is received
if (results.value == 0xFF18E7 ) { //go up
start();
analogWrite(6, 255); //high speed
digitalWrite(7, HIGH); //move up
digitalWrite(8, LOW);
delay(10);
}
if (results.value == 0xFF4AB5) { //move down
start();
analogWrite(6, 255); //high speed
digitalWrite(7, LOW); //move down
digitalWrite(8, HIGH);
delay(10);
}
if (results.value == 0xFF38C7) { //optional stop button
analogWrite(6, 0);
digitalWrite(7, LOW);
digitalWrite(8, LOW);
delay(10);
}
irrecv.resume();
}
}
I want to control DC motor with IR remote - motor should keep rotating as long as i hold a button on remote.
I've got a problem with my timer and interrupts. My idea was to start timer everytime when the code is received from remote. Remote sends codes as long as i hold a button, so timer should keep reseting as long as i hold a button. When i release button, timer should be overflow (after few ms), so interrupt should turn off my motor.
Code works only for the first "iteration". Motor keep rotating when i hold button, but when i release button and hold it again - motor start moving and turn off immediately.
What is wrong with my idea and code? Is there any easier way to solve my problem?