🛠 Commander une LED à distance avec Particle.function
Objectives
Expose a firmware function to the Particle Cloud using Particle.function, then call it from the Internet via a simple HTTP request: the cloud calls your registered C++ function, which returns an integer.
Hardware
- 1 Particle Photon connected to the cloud (tutorial: photon-wifi-publish)
- 1 external LED (with resistor) or the onboard LED D7
- A Particle account and a token:
particle token createor the OAuth2 flowPOST https://api.particle.io/oauth/token
Complete Code
// photon-fonction-distance.ino — fonction appelée depuis le cloud
void setup {
pinMode(D7, OUTPUT);
Particle.function("led", ledCmd); // enregistrement auprès du cloud
}
void loop { }
// Appelee par le cloud : POST /v1/devices/<id>/led?args=on
int ledCmd(String args) {
if (args == "on") { digitalWrite(D7, HIGH); return 1; }
if (args == "off") { digitalWrite(D7, LOW); return 0; }
return -1; // argument invalide
}
Expected Verification
From a terminal: curl -H "Authorization: Bearer $TOKEN" -d args=on https://api.particle.io/v1/devices/<Photon_ID>/led turns on LED D7; args=off turns it off; an unknown argument returns -1. The list of your devices (and the 24-character hexadecimal ID) is obtained with curl -H "Authorization: Bearer $TOKEN" https://api.particle.io/v1/devices.
Common Errors
- Function name too long or non-alphanumeric: keep a short name like "led".
- Forgetting the Authorization Bearer header: the API responds with an authentication error (TLS 1.2+ required).
- Expecting a String return value: the function returns an int, visible on the API side in the return field.
- Performing long processing within the function: it runs in the system context, keep it brief and queue the actual work.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-evenement.inoArduinofonction-distance.inoArduinocapteur-dht.inoArduinoruban-neopixel.inoArduinopwm-respiration.inoArduino