I have made a code that takes in inputs from the IR remote then turns the motors a certain way. All of my buttons work properly but once I press a button once. It runs that over and over again and I can't input another signal. All of the lights on my board flicker like its getting the IR signal a bunch of times. I'll post the code below. I suspect its not breaking the loop but I have no idea how to fix it. Thanks!
#include <IRremote.hpp>
#define IR_RECEIVE_PIN 11
const int PWM_M1 = 5;
const int IN1_M1 = 2;
const int IN2_M1 = 3;
const int PWM_M2 = 6;
const int IN1_M2 = 8;
const int IN2_M2 = 9;
int speed = 100;
// Function prototype
void stop();
void setup() {
Serial.begin(9600);
IrReceiver.begin(IR_RECEIVE_PIN, ENABLE_LED_FEEDBACK); // Initialize IR receiver
pinMode(PWM_M1, OUTPUT);
pinMode(PWM_M2, OUTPUT);
pinMode(IN1_M1, OUTPUT);
pinMode(IN2_M1, OUTPUT);
pinMode(IN1_M2, OUTPUT);
pinMode(IN2_M2, OUTPUT);
}
void loop() {
// Check if IR data is available
if (IrReceiver.decode()) {
// Handle the decoded IR signal
unsigned long irData = IrReceiver.decodedIRData.decodedRawData;
Serial.print("Received IR code: ");
Serial.println(irData, HEX);
// Switch based on received IR code
switch (irData) {
case 0x1BA45FF00: // power
break; // No action for this IR code
case 0x2B946FF00: // VOL+
forward();
break;
case 0x3B847FF00: // FUNC/STOP
stop();
break;
case 0x4BB44FF00: // |<<
turnLeft();
break;
case 0x5BF40FF00: // >||
stop();
break;
case 0x6BC43FF00: // >>|
turnRight();
break;
case 0x8EA15FF00: // VOL-
backward();
break;
default:
Serial.println("Unknown IR code");
break;
}
// Ready to receive the next signal
IrReceiver.resume();
}
}
void forward() {
Serial.println("Moving forward");
analogWrite(PWM_M1, 255);
analogWrite(PWM_M2, 225);
digitalWrite(IN1_M1, HIGH);
digitalWrite(IN2_M1, LOW);
digitalWrite(IN1_M2, HIGH);
digitalWrite(IN2_M2, LOW);
}
void backward() {
Serial.println("Moving backward");
analogWrite(PWM_M1, 225);
analogWrite(PWM_M2, 225);
digitalWrite(IN1_M1, LOW);
digitalWrite(IN2_M1, HIGH);
digitalWrite(IN1_M2, LOW);
digitalWrite(IN2_M2, HIGH);
}
void turnLeft() {
Serial.println("Turning left");
analogWrite(PWM_M1, 0);
analogWrite(PWM_M2, 225);
digitalWrite(IN1_M1, HIGH);
digitalWrite(IN2_M1, LOW);
digitalWrite(IN1_M2, HIGH);
digitalWrite(IN2_M2, LOW);
}
void turnRight() {
Serial.println("Turning right");
analogWrite(PWM_M1, 225);
analogWrite(PWM_M2, 0);
digitalWrite(IN1_M1, HIGH);
digitalWrite(IN2_M1, LOW);
digitalWrite(IN1_M2, HIGH);
digitalWrite(IN2_M2, LOW);
}
void stop() {
Serial.println("Stopping motors");
digitalWrite(IN1_M1, LOW);
digitalWrite(IN2_M1, LOW);
digitalWrite(IN1_M2, LOW);
digitalWrite(IN2_M2, LOW);
}
Here is a screenshot of my wiring diagram