Page 150 - Programming the Photon Getting Started With the Internet of Things
P. 150
// write to the appropriate relay
digitalWrite(relayNumber+2, relayState);
return 1;
}
The code for this experiment is actually pretty straightforward. We first set up each of
the relays and assign the Photon pin number to the relay:
int RELAY1 = D3;
int RELAY2 = D4;
int RELAY3 = D5;
int RELAY4 = D6;
We then set the digital pins on the Photon to outputs, as when we switch the pin to
HIGH or LOW; this will also switch the relay ON or OFF:
pinMode(RELAY1, OUTPUT);
pinMode(RELAY2, OUTPUT);
pinMode(RELAY3, OUTPUT);
pinMode(RELAY4, OUTPUT);
When we first run the program, it is best practice to make sure all the relays are
switched off before we do anything:
digitalWrite(RELAY1, LOW);
digitalWrite(RELAY2, LOW);
digitalWrite(RELAY3, LOW);
digitalWrite(RELAY4, LOW);
If we want to control all the relays over the Internet using a Web browser, then we
need to register a Spark function:
Spark.function("relay", relayControl);
In the actual function we do a number of checks, such as determine which relay button
was pressed and whether or not the relay is HIGH or LOW to determine the next state of
the relay. Once the program has done that, we can write to the digital pin:
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;