🛠 Commander la Boron à distance avec Particle.function
Objectives
Particle.function exposes a function from your firmware to the cloud: any client (CLI, curl, Python, web app) can call it via the REST API, and Device OS handles TLS authentication and device identity. Each device is a REST resource on https://api.particle.io — you POST a function call just as you would send a request to a micro-server. You will control an output (turning a load on/off via a relay) from the terminal, then understand the constraints: maximum 63-character argument, short function name, integer return value.
Hardware
- 1× Particle Boron connected to the cloud (previous tutorial validated)
- 1× 3.3 V relay module or an LED + transistor depending on the load
- Particle CLI connected (
particle whoami)
Complete Code
// Boron — commande cloud via Particle.function
const uint16_t RELAIS_PIN = D5; // broche sortie — verifier le pinout
bool chargeActive = false;
void setup {
pinMode(RELAIS_PIN, OUTPUT);
digitalWrite(RELAIS_PIN, LOW);
Particle.function("setCharge", setChargeHandler);
}
int setChargeHandler(String args) {
// args vient du champ POST "arg" (63 caracteres max)
if (args == "on") {
digitalWrite(RELAIS_PIN, HIGH);
chargeActive = true;
return 1;
}
if (args == "off") {
digitalWrite(RELAIS_PIN, LOW);
chargeActive = false;
return 0;
}
return -1; // argument inconnu
}
void loop {
delay(1000);
}
Client-side calls: particle call <device> setCharge on then particle call <device> setCharge off. In curl:
curl https://api.particle.io/v1/devices/<device_id>/setCharge \
-d arg="on" -H "Authorization: Bearer $TOKEN"
# -> {"id":"...","return_value":1,"connected":true}
Expected Verification
Each CLI or REST call returns JSON with return_value equal to the value returned by your handler (1, 0, or -1), and the physical output toggles at the same time (milliseconds if the device is connected). Also test an invalid argument: you should receive -1, proving that the handler is executing correctly.
Common Errors
- Function name too long or not registered before the call: the cloud returns "Function not found"; the device must be online.
- Argument longer than 63 characters: it is truncated or rejected — keep business logic in the firmware, not in the payload.
- Blocking operations in the handler (delays, long I/O): the cloud call times out; delegate long tasks to
loopvia a flag. - Forgetting the
arg=field in curl: the function receives an empty string and returns -1. - Confusing function (action, returns int) and variable (state reading): to read a state, use
Particle.variable(next tutorial).
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-evenement.inoArduinofonction-distance.inoArduinocapteur-dht.inoArduinoruban-neopixel.inoArduinopwm-respiration.inoArduino