Report get website

Good evening everyone.
I’m trying to read the status of a led on a web page. It is programmed to turn on and off every 4 seconds. In particle console I get the values ​​"1" and “0” respectively. But I can’t collect this data on a web page.

int ledPin = D7;
int statusPin;

void setup() {
    pinMode(ledPin,OUTPUT);
    Spark.variable("statusPin", &statusPin, INT);
}
void loop() {
  digitalWrite(ledPin,LOW);
  statusPin = digitalRead(ledPin);
  Particle.publish("Status", String(statusPin) , PRIVATE);
  delay(4000);
  digitalWrite(ledPin,HIGH);
  statusPin = digitalRead(ledPin);
  Particle.publish("Status", String(statusPin) , PRIVATE);
  delay(4000);
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="raphael.2.1.0.min.js"></script>
<script src="justgage.1.0.1.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
var accessToken = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
var deviceID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
var url = "https://api.spark.io/v1/devices/" + deviceID + "/statusPin";

function callback(status){
	if(status == "sucess"){
		if(statusPin == '0')
		alert("on");
		else{
		alert("off");	
		}
		g.refresh(statusPin);
		setTimeout(getReading,1000);
		}
}
function getReading(){
   	$.get(url, {access_token: accessToken}, callback);
}
</script>
</head>	
<body>
</body>
</html>

This application note may help, AN032 Calling the Particle API from a web page.

Just some notes about your code

  • You should not use the Spark moniker anymore but rather Particle
  • The three-parameter version of Particle.variable() is outdated and shouldn’t be used anymore
  • Try to adopt a non-blocking coding paradigm as early as possible to prevent future headache - e.g. your loop() could look like this
void loop() {
  static uint32_t msLastExec = 0;
  if (millis() - msLastExec < 4000) return; // bail out when nothing to do
  msLastExec = millis();
 
  statusPin = !statusPin;                   // toggle the value
  digitalWrite(ledPin, statusPin);
  Particle.publish("Status", String(statusPin));
}
1 Like

First thanks for the tip. I didn’t understand the “The three-parameter version of Particle.variable() is out of date and should no longer be used” part. Where do I become aware of updates?

This would be the place
https://docs.particle.io/reference/device-os/firmware/#particle-variable-

Or you could use a faily new version to expose a calculated Particle.variable() (even using lambdas)

Particle.variable("statusPin", []() -> bool { return digitalRead(ledPin); });
3 Likes