My version allows you to control all 4 relays in one request using the following parameters -
params=R1,HIGH,R2,LOW
This can be abbreviated to -
params=R1,1,R2,0
or even -
params=1,1,2,0
int RELAY1 = D0;
int RELAY2 = D1;
int RELAY3 = D2;
int RELAY4 = D3;
void setup()
{
//Initilize the relay control pins as output
pinMode(RELAY1, OUTPUT);
pinMode(RELAY2, OUTPUT);
pinMode(RELAY3, OUTPUT);
pinMode(RELAY4, OUTPUT);
// Initialize all relays to an OFF state
digitalWrite(RELAY1, LOW);
digitalWrite(RELAY2, LOW);
digitalWrite(RELAY3, LOW);
digitalWrite(RELAY4, LOW);
//register the Spark function
Spark.function("relay", relayControl);
}
void loop()
{
// This loops for ever
}
int tokenise(char * command, char * tokens[], int max_tokens) {
int n = 0;
char * p = command;
while (n<max_tokens) {
tokens[n]=p;
while (*p != '\0' && *p != ',') { p++; };
if (*p == '\0') return(n+1);
*p++ = '\0';
n++;
}
return(n);
}
// command format r1,HIGH
int relayControl(String command)
{
char char_command[64];
char * tokens[20];
int token_count;
int relayNumber;
int relayState;
int n = 0;
command.toCharArray(char_command, 64);
token_count = tokenise(char_command, tokens, 20);
if (token_count >=20 || token_count == 0) return(-1);
while (n<token_count) {
if (tokens[n][0] == 'R' || tokens[n][0] == 'r') relayNumber = tokens[n][1] - '0';
else relayNumber = tokens[n][0] - '0';
n++;
relayState=-1;
if (strncmp(tokens[n],"HIGH", 4) == 0 || strncmp(tokens[n], "1", 1) ==0 ) relayState = 1;
else if (strncmp(tokens[n],"LOW",3) == 0 || strncmp(tokens[n], "0", 1) ==0 ) relayState = 0;
n++;
// do a sanity check
if (relayNumber < 1 || relayNumber > 4 || relayState==-1) continue;
digitalWrite(relayNumber-1, relayState);
}
return 1;
}