Spark Core for IoT device development in SmartThings

In this example I will show you how to turn on and off the Spark Core blue, on board, LED connected to D7 from your SmartThings App.

First you will have to flash this code to your Spark Core

/* A Spark function to parse the commands */
int ledControl(String command);

// We name pin D7 as led
int led = D7; 

// This routine runs only once upon reset
void setup() 
{
  //Register Spark function
  Spark.function("ledstate", ledControl);    
  // Initialize D0 pin as an output
  pinMode(led, OUTPUT);
}

// This routine loops forever 
void loop()
{
  // Nothing to do here
}

int ledControl(String command)
{
  if (command == "1") {   
    digitalWrite(led, HIGH);   // Turn ON the LED
    return 1;
  } else {               
    digitalWrite(led, LOW);    // Turn OFF the LED
    return 0;
  }
}

Then, on SmartThings IDE:

  • Log in to SmartThings IDE
  • Go to “My Device Type” and click on “+New SmartDevice”
  • Create the Device type with the following values:
  • Name: Spark Core
  • Author: juano23@gmail.com
  • Click Create
  • Paste the following code
/**
 *  Spark Core
 *
 *  Author: juano23@gmail.com
 *  Date: 2014-01-23
 */
 
 preferences {
    input("deviceId", "text", title: "Device ID")
    input("token", "text", title: "Access Token")
}
 
 // for the UI
metadata {
    // Automatically generated. Make future change here.
	definition (name: "Spark Core", author: "juano23@gmail.com") {
    	capability "Switch"
	}

    // tile definitions
	tiles {
		standardTile("switch", "device.switch", width: 2, height: 2, canChangeIcon: true) {
			state "on", label: '${name}', action: "switch.off", icon: "st.switches.switch.on", backgroundColor: "#79b821"
			state "off", label: '${name}', action: "switch.on", icon: "st.switches.switch.off", backgroundColor: "#ffffff"
		}

		main "switch"
		details "switch"
	}
}

def parse(String description) {
	log.error "This device does not support incoming events"
	return null
}

def on() {
	put '1'
}

def off() {
	put '0'
}

private put(led) {
    //Spark Core API Call
	httpPost(
		uri: "https://api.spark.io/v1/devices/${deviceId}/ledstate",
        body: [access_token: token, command: led],  
	) {response -> log.debug (response.data)}
}

  • Go to “My Devices” and click on “+New Device”
  • Create the Device type with the following values
  • Name: Spark Core
  • Device Network Id: 2323
  • Type: Spark Core
  • Click Create
  • Restart the App and you should be able to see the new device
  • In the device Preferences you will be able enter your Device ID and your Access Token
  • All set :)