The Spark Core is a tiny module with ARM Cortex M3 micro-controller and Wi-Fi interface. These devices will be connect with the Spark Cloud service for firmware updates and remote control. A limited amount of pins on the module can be used for analog and digital signals. The firmware of the Spark Core can be programmed, compiled and uploaded using the Spark Web IDE.
The following code is for a Spark Core installed on the Spark relay shield. All relays are controlled using a single function. Up to four functions are currently supported by Spark. The status of the four relays can be read through a single variable.
/*
Web controlled garden lights using the Spark.io relay shield
*/
int RELAY1 = D0;
int RELAY2 = D1;
int RELAY3 = D2;
int RELAY4 = D3;
int relayState = 0;
void setup() {
pinMode(A0, INPUT); // 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 functions (name max 12 characters, max 4 functions)
Spark.function("toggleRelay", relayControl);
Spark.variable("stateRelay", &relayState, INT);
}
void loop() {
}
int bitSelector(int bit) {
// Returns a 1 shifted to position bit as integer value
return (1 << (bit));
}
int relayControl(String command) {
// Parse the relay number
int relayNumber = (command.charAt(0) - '0') - 1;
// Do a sanity check
if (relayNumber < 0 || relayNumber > 3)
return -1;
// Check state of relay with registered state
if (digitalRead(relayNumber) == ((relayState & bitSelector(relayNumber)) > 0)) {
// Toggle the state of the relay
relayState = relayState ^ bitSelector(relayNumber);
}
// Write to the appropriate relay
digitalWrite(relayNumber, (relayState & bitSelector(relayNumber)));
return 1;
}
The HTML code below will show four buttons on a web page, which can be pressed to activate the corresponding relays. The device ID of the Spark Core and the access code need to be filled in, instead of the “12345” and “abcde” shown below.
Lights
Test
name value
id N/A
name N/A
connected N/A
return value N/A