Relay code not working

Hi Everybody,

I recently got my spark core and have been loving it so far, but have hit a stumbling block with my latest project. Here goes…

I have an eight channel relay that I am trying to control with the Spark, so far it works fine from the tinker app. However, my ultimate goal is controlling it from a website, so I used the available relay shield code, see below:

int RELAY1 = A0;
int RELAY2 = A1;
int RELAY3 = A2;
int RELAY4 = A3;

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, HIGH);
   digitalWrite(RELAY2, HIGH);
   digitalWrite(RELAY3, HIGH);
   digitalWrite(RELAY4, HIGH);

   //register the Spark function
   Spark.function("relay", relayControl);
}

void loop()
{
   // This loops for ever
}

// command format r1,HIGH
int relayControl(String command)
{
  int relayState = 0;
  // parse the relay number
  int relayNumber = command.charAt(1) - '0';
  // do a sanity check
  if (relayNumber < 1 || relayNumber > 4) return -1;

  // find out the state of the relay
  if (command.substring(3,7) == "HIGH") relayState = 1;
  else if (command.substring(3,6) == "LOW") relayState = 0;
  else return -1;

  // write to the appropriate relay
  digitalWrite(relayNumber-1, relayState);
  return 1;
}

But it doesn’t work, I have tried using curl in the terminal and Spark Helper both give me success messages but nothing happens on the Spark. Here is an example of a curl command and return:

curl https://api.spark.io/v1/devices/{MY-ID}/relay -d access_token={MY TOKEN} -d args=r1,LOW

{
  "id": "MY-ID",
  "name": "core-1",
  "last_app": null,
  "connected": true,
  "return_value": 1
}

Same arguments in Spark Helper, I get a success message, but no cigar on the Spark.

Anybody have any ideas?

Hi @obrien28

How do you know that your code is not working? Maybe you could get a better idea by putting LEDs from the A0-A3 outputs with a current limiting resistor and see if you can control the LEDs.

From the code, it looks like HIGH means relay off, so LOW must be mean relay on. Maybe your could share more details of the relay board and how you have it hooked up?

Since you are using analog pins, their PIN numbers are 10 higher than the digital ones.

Try this :wink:

digitalWrite(relayNumber-1+10, relayState);

3 Likes
digitalWrite(relayNumber-1+A0, relayState);

This one will be more immune to possible firmware changes (10 not hardcoded).

@BDub and @cyberluke thanks for the suggestion it worked like a charm, I had wondered about that line of code but wasn’t sure how to fix it, clearly I need to learn more about ascii, it always seems to trip me up one way or another

I think you mean:

digitalWrite(relayNumber-1+A0, relayState);

Currently
D0 = 0
A0 = 10

Ahh, sorry…was copy’n’pasting code from other browser tab :smiley: