30 August, 2015

Arduino: manage 8-channel relay module via infrared remote control

Arduino allows us to do simple things in a simple way.

Pretty obvious desire - to control home electronics using the remote control: manage lighting, doors remotely by pressing the buttons. It is really easy. You just need these components:

Connect all together:

Arduino, 8-channel relay, IR remote control

Upload the source code to the Arduino board:

#include <IRremote.h>

const int IR_PIN = 2;

const int RELAY_PINS[8] = {12, 11, 10, 9, 8, 7, 6, 5};
int RELAY_STATES[8] = {LOW};

IRrecv irrecv(IR_PIN);

decode_results results;

void setup() {
  irrecv.enableIRIn();

  for (int i = 0; i < 8; i++) {
    pinMode(RELAY_PINS[i], OUTPUT);
  }
}

/**
 * Decode IR code to numeric button 0-9
 * Return pressed button number or -1
 */
int samsungDecode(unsigned long irValue) {
  switch (irValue) {
    case 0xE0E020DF:
      return 1;
    case 0xE0E0A05F:
      return 2;
    case 0xE0E0609F:
      return 3;
    case 0xE0E010EF:
      return 4;
    case 0xE0E0906F:
      return 5;
    case 0xE0E050AF:
      return 6;
    case 0xE0E030CF:
      return 7;
    case 0xE0E0B04F:
      return 8;
    case 0xE0E0708F:
      return 9;
    case 0xE0E08877:
      return 0;
  }
  return -1;
}

/**
 * Toggle single relay or switch ON/OFF all relays
 */
void action(int button) {
  if (button > 0 && button < 9) {
    //toggle single relay
    int i = button - 1;
    if (RELAY_STATES[i] == LOW) {
      digitalWrite(RELAY_PINS[i], HIGH);
      RELAY_STATES[i] = HIGH;
    } else {
      digitalWrite(RELAY_PINS[i], LOW);
      RELAY_STATES[i] = LOW;
    }
  } else if (button == 9) {
    //switch ON all relays
    for (int i = 0; i < 8; i++) {
      digitalWrite(RELAY_PINS[i], HIGH);
      RELAY_STATES[i] = HIGH;
    }
  } else if (button == 0) {
    //switch OFF all relays
    for (int i = 0; i < 8; i++) {
      digitalWrite(RELAY_PINS[i], LOW);
      RELAY_STATES[i] = LOW;
    }
  }
}

int lastPressedButton = -1;

void loop() {
  if (irrecv.decode(&results)) {
    int button = samsungDecode(results.value);
    if (button != lastPressedButton) {
      lastPressedButton = button;
      action(button);
    }
    irrecv.resume();
  } else {
    lastPressedButton = -1;
  }
  delay(250);
}

And enjoy by pressing buttons:

Buttons 1-8 manage relays 1-8, button 9 switch on all relays, and button 0 switch all off.

The previous day I wrote the article Arduino: scan codes from a remote control. I have scanned codes for my Samsung remote control. So if you have another remote control, just scan your codes.