Switch lamp through webpage, Arduino error

Alright,

So basically I’ve been trying to get this working, got the web page side done, now the problem is that I get 2 errors while reaching the last step; https://api.spark.io/v1/devices/53ff6b066667574853492467/switchLamp?access_token=MY ACCES TOKEN

{
“ok”: false,
“error”: “Variable not found”
}

Any help would be appreciated, I’m using the code below for my Spark API:

//This code will switch on, or off pin D2, which at my home activates a lamp. It will switch when the “switchLamp” command is received from the spark cloud.

.

bool debug = FALSE;

int lampPin = D2;
int lampStatus = HIGH;
String lampStatusString = "on";




void setup() {
    //start Serial communication for debugging
    if (debug){
        Serial.begin(9600);
    }

 

    
    //set lamp
    pinMode(lampPin,OUTPUT);
    digitalWrite(lampPin,lampStatus);
    
    //define communication with cloud
    Spark.function("switchLamp",switchLampFunc);
    Spark.variable("lampStatus",&lampStatusString, STRING);
    
    
    
}

void loop() {
    digitalWrite(lampPin,lampStatus);
    delay(10);
    //do nothing
}

int switchLampFunc(String command){
   
    
    if (lampStatus == HIGH)
    {
        digitalWrite(D2,lampStatus);
        
    }
    else if (lampStatus == LOW)
    {
        digitalWrite(D2,lampStatus);
        
    }
    else
    {
        return -1;
    }
    
    //set the lamp
    digitalWrite(lampPin,lampStatus);
    
    }

Thanks in advance,

Kind regards,

Kai Nijssen

Heya @Wyverncrypt!

You seem to send in your request as a GET request, which makes the API assume you’re trying to request a variable. To trigger a function, send the same as a POST request and the function will be smoothly executed!
A look at the definitions and curl examples in the API docs will help you further.

Though you might want to change the state handlers in your switchLampFunc, currently you don’t change the lampStatus variable’s state at all :wink:

Good luck! :sunflower:

Thanks for clearing that :wink:

I am basically a noob in Arduino or coding in general, could you pass me some hints on how to do this?
I have taken a look in the API docs and tried to figure out some things, but didn’t get much further.
Also, I thought this might help to understand the situation;

<?php

  //This php scirpt first switches the lamp by doing an API call to spark.io and than adds the name of the user to a MySQL database

  //The spark core part first:

  // Set your access token here. Make sure this token is never stored client side, ie. in Javascript files for example.
  define('ACCESS_TOKEN', 'MY ACCES TOKEN');

// All responses should be JSON
header('Content-type: application/json');


// Build the URL.  Since it's possible to accidentally have an
// extra / or two in $_SERVER['QUERY_STRING], replace "//" with "/"
// using str_replace().  This also appends the access token to the URL.
$url = 'https://'.str_replace('//', '/', 'api.spark.io/v1/devices/'.$_SERVER['QUERY_STRING'].'?access_token='.ACCESS_TOKEN);


// HTTP GET requests are easy!
if(strtoupper($_SERVER['REQUEST_METHOD'])=='GET')
        echo file_get_contents($url);
// HTTP POST requires the use of cURL
elseif (strtoupper($_SERVER['REQUEST_METHOD'])=='POST') {

  $c = curl_init();
  
  curl_setopt_array($c, array(
  // Set the URL to access
                CURLOPT_URL => $url,
                // Tell cURL it's an HTTP POST request
                CURLOPT_POST => TRUE,
                // Include the POST data
                // $HTTP_RAW_POST_DATA may work on some servers, but it's deprecated in favor of php://input
                CURLOPT_POSTFIELDS => file_get_contents('php://input'),
                // Return the output to a variable instead of automagically echoing it (probably a little redundant)
                CURLOPT_RETURNTRANSFER => TRUE
  ));


  // Make the cURL call and echo the response
  echo curl_exec($c);

  // Close the cURL resource
  curl_close($c);
  

}


?>

Thanks in advance,

Kai Nijssen

Its already all in the code :blush: Just remove following to always POST the request to the API:

// HTTP GET requests are easy!
if(strtoupper($_SERVER['REQUEST_METHOD'])=='GET')
        echo file_get_contents($url);
// HTTP POST requires the use of cURL
elseif (strtoupper($_SERVER['REQUEST_METHOD'])=='POST') {

and the trailing

}

Pleasure! :slight_smile: :rainbow:

I would recommend you reading through some Spark/Arduino examples and tutorials to get started though, as learning and understanding what happens in an existing code is a very important base to built upon! Good luck!

For the remote side of your quedtion, I’d agree with @rastapasta, and to extend his hint about your firmware, there are more than one things a bit odd.

  • I’d not use a String object to base a Spark.variable on. Rather go for a char[] (see here)
  • The next possible problem is that you don’t return an int if lampStatus is HIGH or LOW, but you have to return something.
  • The if ... else if ... construct is slightly obscure, since you just do exactly the same thing in both cases and as in the last statement in this function (???).
  • I guess you’d want to interpret the Spark.function() command rather than the current lampStatus in your if ... else ....
  • You have declared lampPin = D2, so you should stick to using lampPin and avoid D2.
  • Just for nit picking :wink: LOW is defined as 0 and digitalWrite() considers everything but 0 as HIGH, so there won’t be any need for the final else.
  • No need to permanently digitalWrite() in loop() - the GPIOs usually don’t forget their current state.
  • And - as @rastapasta pointed out already - lampStatus will always be HIGH, and lampStatusString never changes too - but this may well be due to work in progress :wink:
1 Like

So I should also remove the request post method?

I’ve tried removing the request get method and the request post method, also tried only removing the request get method…
I’m just sitting here quite frustrated because my browser now comes up with some error:

Uncaught ReferenceError: $ is not defined

In line 9 of lampScriptGit.php which would be;

 $.post('http://127.0.0.1/proxyGit.php?'+deviceID+'/' + setFunc, {params: sendName},function(response) {console.log(response);});