Referencing functions in Javascript and setup

Hey, I need to reference some functions on the core by using javascript, and don’t know how to do so. I have been able do it through regular html, however i believe it is different. My code for the setup of the functions is below, as well as an example of the actual function. Could someone make an example of what the code should look like in javascript?

Function setup:

void setup() {
    Spark.function("motor1drive", motor1);
    Spark.function("motor1stop", motor1);
    pinMode(motor1, OUTPUT);
    
    Spark.function("motor2drive", motor2);
    Spark.function("motor2stop", motor2);
    pinMode(motor2, OUTPUT);
}

Function example

int motor2(String command) {
    if(command==motor2drive)
        loop() {
            analogWrite(motor,255); 
            delay(ms);
            analogWrite(motor,0);
            delay(ms);
        }
    }
    else if(command==motor2stop) {
        loop() {
            analogWrite(motor,0);  
            delay(ms);
            analogWrite(motor,0);
            delay(ms);
        }
    }
}

Also, how would you setup javascript in order to reference the core in general? thanks.

I think you can interact with them via a javascript ajax request to https://api.particle.io/v1/devices/{deviceID}/{function-name} with POST variables for the accessToken and any arguments for the function.
See https://docs.particle.io/reference/api/#call-a-function for calling a function over the cloud.

On the HTML page, you’d want something like this…

<div id='myDiv'> Response of the function will go here </div>
<script>
    var accessToken = 1234;
    var deviceID = 5678;
    var baseURL = "https://api.particle.io/v1/devices/"+ deviceID + "/";
    function callSpark(fName, args) {
            var xmlhttp;
            if (window.XMLHttpRequest) {
                 xmlhttp=new XMLHttpRequest();
            } else {
                  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function() {
                      if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                               document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
                      }
          }
          var fullURL = baseURL + fName;
          xmlhttp.open("POST", fullURL ,true);
          xmlhttp.send("access_token="+ accessToken + "&args=" + args);
    }
</script>

And then you would just call something like: callSpark(“motor1drive”, “command”) in javascript.
Please excuse any errors (this is handwritten, and mostly theory)

But since your access code is in there, I wouldn’t recommend making that page public.
I think @bko wrote a tutorial about using javascript to call a function on your spark…

Check this out:

I've written an example over here, using the JavaScript SDK, just right-click to check the source: http://jordymoors.nl/particle/demos/function_button.html

1 Like