Controlling the Spark Core pins with webpage buttons

Ok, so now you need to go back and look at the Spark Variable and Function on One Web Page and make some minor edits. You don’t want the slider, but you do want four buttons (you could do it with two, I just did four).

Add your device id and access token to this HTML and save it as a local file. Open it in a web browser with the file:///path/to/file/filename.html URL and click away! Remember to keep your access_token private since that identifies you.

<!DOCTYPE HTML>
<html>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<body>

    <br><br>
    <button id="led1onbutton"  onclick="switchLED(1,1)">LED 1 On</button>
    <button id="led1offbutton"  onclick="switchLED(1,0)">LED 1 Off</button>
    <br><br>
    <button id="led2onbutton"  onclick="switchLED(2,1)">LED 2 On</button>
    <button id="led2offbutton"  onclick="switchLED(2,0)">LED 2 Off</button>
    <br><br>
    <script type="text/javascript">
      var deviceID    = "<<device id>>";
      var accessToken = "<<access token>>";
      var setFunc = "led";

      function switchLED(ledn,newValue) {
        var paramStr = "l" + ledn.toString();
        if (newValue==1) { 
           paramStr = paramStr + ",HIGH";
        } else {
          paramStr = paramStr + ",LOW";
        }
	var requestURL = "https://api.spark.io/v1/devices/" +deviceID + "/" + setFunc + "/";
        $.post( requestURL, { params: paramStr, access_token: accessToken });
      }
    </script>
</body>
</html>

[EDIT] if you do want to put this on the net on a public server, you should use a PHP proxy or other service to keep your access token private.

See here for an example:

7 Likes