Christian
Published © GPL3+

Control Relays Using a Keypad

Need to control your relays using a Keypad? Then you need the IO Expander with Relay Expanders!

BeginnerFull instructions provided1 hour723

Things used in this project

Hardware components

Arduino UNO
Arduino UNO
×1
IO Expander
×1
Relay Expander
×1
FCB Maker (FCB Electronics)
×1

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Schematics

Control Relays Using a Keypad

Use the IO Expander with Relay Expanders

Code

Control Relays Using a Keypad

C/C++
Use the IO Expander with Relay Expanders
/* IO Expander
 *  
 * Relay Keypad
 *
 */

#include <SoftwareSerial.h>
#include "IOExpander.h"
#include <avr/wdt.h>

//#define SERIAL_DEBUG
#define MAX_RELAYS    64

#ifdef SERIAL_DEBUG
SoftwareSerial swSerial(8,7);
#endif

char cmd[16];
char key[16] = {};

#define KEYPAD_4x3
//#define KEYPAD_4x4

#ifdef KEYPAD_4x3
#define MAX_KEYS    12

int thresholds[MAX_KEYS] = {18,329,598,1000,1183,1346,1603,1723,1833,2009,2093,2172};
char keypad[MAX_KEYS] = {'1','2','3','4','5','6','7','8','9','*','0','#'};
#endif

#ifdef KEYPAD_4x4
#define MAX_KEYS    16

int thresholds[MAX_KEYS] = {105,394,617,847,1049,1220,1357,1502,1634,1748,1840,1939,2031,2110,2177,2249};
char keypad[MAX_KEYS[ = {'1','2','3','A','4','5','6','B','7','8','9','C','*','0','#','D'};
#endif

void setup()
{
  int i;
 
  Serial.begin(115200);

#ifdef SERIAL_DEBUG
  swSerial.begin(115200);
  swSerialEcho = &swSerial;
  swSerial.println("DEBUG");
#endif  
  wdt_enable(WDTO_8S);

  delay(100);                           // Wait 100 ms for IO Expander Title
  while (Serial.available()) Serial.read(); // Flush RX buffer
 
  sprintf(cmd, "eb%d", MAX_RELAYS / 16);
  SerialCmdDone(cmd);

  // Configure keypad
  SerialCmdDone("s2t1d;sc0,0");
  Serial.print("sc");
  for (i = 0; i < MAX_KEYS; i++)
  {
    if (i) Serial.print(",");
    Serial.print(thresholds[i]);
    Serial.print(",\"");
    Serial.print(keypad[i]);
    Serial.print("\"");
  }
  SerialCmdDone(";sd100");                 // Keypad debounce 100ms
}

void loop()
{
  int i,relay;
  char ch;
 
  SerialCmd("s2r");
  int len = strlen(key);
  SerialReadString(key+len, sizeof(key)-len); // Concatinate keypad characters
  SerialReadUntilDone();

  for (i = 0; i < strlen(key); i++) {
    ch = key[i];
    if (!isdigit(ch)) {
      key[i] = NULL;
      if (ch == '*' || ch == '#') {
        relay = atoi(key);
        if (relay > 0 && relay <= MAX_RELAYS) {
          Serial.print("e");
          Serial.print(relay);
          if (ch == '#') Serial.println("o"); // Turn on relay
          else Serial.println('f');           // Turn off relay
          SerialReadUntilDone();              // Wait for the '>' prompt
        }
      }
      strcpy(key, key+i+1);
      break;
    }
  }
 
  wdt_reset();
  delay(100);
}

Credits

Christian

Christian

24 projects • 134 followers
Senior Embedded Engineer

Comments