Spark core, first code…

As you might have noticed from a previous post, I got a Spark Core.

I haven’t done much with it yet, but what I have done is to make it able to turn pins high/low, using their web api.

TCPClient client;
byte server[]  = { xx, xx, xx, xx };

char tempStr[16];

void setup()
    //Register our Spark function here
    Spark.function("SWITCH", pinSwitch);

void loop()

int pinSwitch(String command)
   int state = 0;
   //find out the pin number and convert the ascii to integer
   int pinNumber = command.charAt(1) - '0';

   //Sanity check to see if the pin numbers are within limits
   if (pinNumber < 0 || pinNumber > 7)
       return -1;

   // find out the state of the led
   if(command.substring(3,7) == "HIGH")
       state = 1;
   else if(command.substring(3,6) == "LOW")
       state = 0;
       return -2;

   // write to the appropriate pin
   pinMode(pinNumber, OUTPUT);
   digitalWrite(pinNumber, state);
   return 1;

unsigned long lastSync = 0;
void nodeSync()
    if ((millis() - lastSync < 3600000  && lastSync != 0) && millis() >= lastSync) return; //Only check once every hour, unless we havent checked yet, or if time since overflow of millis is less than last time we checked
    lastSync = millis();


    if (client.connect(server, 80))
        RGB.color(255, 0, 0);
        String tsData = String(Spark.deviceID());

        client.println("GET /nodeSync.php?spark=" + tsData + " HTTP/1.1");
        client.println("Connection: close");

        while (client.available()) //Read what is returned from the server
            char c =;
            if (millis() - lastSync > 500) break; //Read for maximum 500ms, then stop reading



This code actually does a bit more than just changing the pins… I made a file for the different nodes to synchronize with. Calling this file with the id of the node makes the server do the appropriate calls to the node again, making the pins go high/low according to the database. This happens both on initial start of the node and then again every 60 minutes (or every 3600000 millisecond).


To use this code for something else you will have to fill in the server ip and change “Host:” to be the same as yours too.

Leave a Comment