#include <IRremote.h> // Library to receive IR signals from the remote
#include <ESP32Servo.h> // Import ESP32Servo library to control the servo motor
Servo servo;
#define PIN_RECEIVER 15 // Define the pin where the IR sensor is connected
IRrecv receiver(PIN_RECEIVER); // Create a receiver object to receive signals from the IR remote
decode_results results;
int pos = 0; // Variable to store the servo position
void setup() {
Serial.begin(115200); // Start serial communication with a baud rate of 115200
receiver.enableIRIn(); // Start receiving IR signals
servo.attach(18); // Attach the servo to pin 18
}
void loop() {
if (receiver.decode()) { // If an IR signal is received
int key_value = translateIR(); // Translate the IR signal into a number or button code
receiver.resume(); // Clear the IR receiver buffer to receive new signals
// Debugging: print key_value to see if the button codes are correct
Serial.println("Key value: " + String(key_value));
if (key_value == 99) { // If the translated IR button is 2 "+" (button to increase)
pos++; // Increase the servo position
if (pos >= 180) // The maximum angle limit for the servo is 180 degrees
pos = 180;
}
if (key_value == 88) { // If the translated IR button is 152 "-" (button to decrease)
pos--; // Decrease the servo position
if (pos <= 0) // The minimum angle limit for the servo is 0 degrees
pos = 0;
}
// Move the servo to the 'pos' position based on the value
servo.write(pos);
// Display the servo position on the serial monitor
Serial.println("Servo angle: " + String(pos));
}
}
// Translate the received IR code into a number or command
int translateIR() {
switch (receiver.decodedIRData.command) {
case 2: return 99; // Code 2 from the remote is translated into the command "+"
case 152: return 88; // Code 152 from the remote is translated into the command "-"
default: return -1; // If the button is not recognized, return -1
}
}