🛠 Variables cloud et intégration HTTP
Objectives
Expose Photon data to the cloud using Particle.variable: a read-only integer (a sensor value) and a String writable from the cloud, then query and modify them from an HTTP script — the basis of an integration hook to any backend.
Hardware
- 1 Particle Photon with a sensor on A0 (tutorial photon-capteur-adc)
- API token (
particle token create) and the device ID - Python 3 with the requests library, or curl
Complete code
// photon-variables-hook.ino — variables cloud
int sensor = 0;
String status = "idle"; // les String sont inscriptibles depuis le cloud
unsigned long derniere = 0;
void setup {
Particle.variable("sensor", sensor); // lecture: GET .../sensor
Particle.variable("status", status); // ecriture: POST .../status
}
void loop {
if (millis - derniere > 2000) {
derniere = millis;
sensor = analogRead(A0); // 12 bits, 0..4095
}
}
Expected verification
Read: curl -H "Authorization: Bearer $TOKEN" https://api.particle.io/v1/devices/<ID>/sensor returns the value. Write: curl -H "Authorization: Bearer $TOKEN" -d value=mode_nuit https://api.particle.io/v1/devices/<ID>/status modifies the String on the firmware side. In Python, requests.get followed by r.json does the same job.
Common errors
- Passing a local variable:
Particle.variablemust point to a global variable that lives for the entire duration of the program. - Changing a variable's type between two firmwares without re-claiming: the cloud may reject the new schema.
- Polling too aggressively from your HTTP hook: be mindful of the API and Wi-Fi, keep an interval of several seconds.
- Forgetting that the endpoint is api.particle.io: the old api.spark.io has been permanently closed.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-evenement.inoArduinofonction-distance.inoArduinocapteur-dht.inoArduinoruban-neopixel.inoArduinopwm-respiration.inoArduino