I have built an Arduino Nano based robot controlled by an Adafruit IR remote. As my code shows below, is is designed to start the functions controlling the motors and to wait for code 28 to be received in order to stop the motors using the appropriate command. However when I press a button on the remote, the motors move but do not stop when I press the button on the remote. They only stop when I reset the Arduino. Is there any way to improve the code?
Thanks
#include <Adafruit_NECremote.h>
#define IR 2
#define ENA 11
#define IN1 7
#define IN2 6
#define IN3 5
#define IN4 4
#define ENB 3
Adafruit_NECremote remote(IR);
void forwd(){
digitalWrite(IN1, HIGH);
digitalWrite(IN3, HIGH);
digitalWrite(IN4, LOW);
digitalWrite(IN2, LOW);
}
void reverse(){
digitalWrite(IN1, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
digitalWrite(IN2, HIGH);
}
void left(){
digitalWrite(IN1, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, LOW);
digitalWrite(IN2, HIGH);
}
void right(){
digitalWrite(IN1, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
digitalWrite(IN2, LOW);
}
void stopall(){
digitalWrite(IN1, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, LOW);
digitalWrite(IN2, LOW);
}
void setup() {
pinMode(ENA, OUTPUT);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
pinMode(ENB, OUTPUT);
analogWrite(ENA, 200);
analogWrite(ENB, 200);
}
int lastcode = -1;
int checkCode(){
int c = remote.listen();
int code = 0;
if (c >= 0){
code = c;
lastcode = c;
}else if (c == -2) {
code = lastcode;
}return code;
}
void loop() {
while (checkCode() == 24){
if (checkCode() == 28){
stopall();
break;
}forwd();
}while (checkCode() == 82){
if (checkCode() == 28){
stopall();
break;
}reverse();
}while (checkCode() == 8){
if (checkCode() == 28){
stopall();
break;
}left();
}while (checkCode() == 90){
if (checkCode() == 28){
stopall();
break;
}right();
}
}