#include <Arduino.h>
#include <Stepper.h>
#define DECODE_NEC  // Only decode the protocol used by the supplied kit remote.
#include <IRremote.hpp>  // IRremote 4.x implementation; use its global IrReceiver object.
const uint8_t RECEIVER_PIN = 12;
const int ROTOR_STEPS = 32;  // These are internal rotor steps, not output-shaft steps.
Stepper motor(ROTOR_STEPS, 8, 10, 9, 11);
uint32_t previousCode = 0;
bool havePreviousCode = false;
void releaseMotor() {
  for (uint8_t pin = 8; pin <= 11; ++pin) digitalWrite(pin, LOW);
}
void setup() { IrReceiver.begin(RECEIVER_PIN, DISABLE_LED_FEEDBACK); }
void loop() {
  if (!IrReceiver.decode()) return;
  uint32_t code = IrReceiver.decodedIRData.decodedRawData;
  // Test only the repeat bit. Other flags do not mean "repeat the last button".
  if (IrReceiver.decodedIRData.flags & IRDATA_FLAGS_IS_REPEAT) {
    if (!havePreviousCode) { IrReceiver.resume(); return; }
    code = previousCode;
  } else { previousCode = code; havePreviousCode = true; }
  motor.setSpeed(500);  // 32-step rotor RPM: about 7.8 nominal geared-output RPM, not 500.
  switch (code) {
    case 0xB946FF00: motor.step(-2048); delay(2000); break;  // VOL+
    case 0xEA15FF00: motor.step(2048); delay(2000); break;   // VOL-
  }
  // Preserve blocking moves and the two-second hold; new IR frames wait until this finishes.
  IrReceiver.resume();
  releaseMotor();  // Stop coil current after the accepted frame is processed.
}
