NodeMCU recibe el comando como byte* payload y atoi me devuelve 0
Traducido del English por IA ·
Hola, todavía estoy aprendiendo. Tengo un NodeMCU (ESP8266) con PubSubClient que controla una tira de LED a través de un MOSFET. En mi placa Hermetry hay un deslizador que envía un comando llamado light.set. Puedo ver cómo llega el mensaje en el monitor serie:
topic: v1/rpc/req/17
payload: {"method":"light.set","params":{"level":42}}
Pero en mi callback no consigo extraer el 42. Probé esto:
void callback(char* topic, byte* payload, unsigned int length) {
int level = atoi((char*)payload);
analogWrite(D5, level);
}
level siempre es 0, a veces un número grande aleatorio. La tira no cambia. También creo que el deslizador muestra «Sent; waiting for the device» para siempre. ¿Qué estoy haciendo mal?
Hello, still learning. I have a NodeMCU (ESP8266) with PubSubClient controlling a LED strip through a MOSFET. On my Hermetry board there’s a slider that sends a command called light.set. I can see the message arrive in the serial monitor:
topic: v1/rpc/req/17
payload: {"method":"light.set","params":{"level":42}}
But in my callback I can’t get the 42 out. I tried:
void callback(char* topic, byte* payload, unsigned int length) {
int level = atoi((char*)payload);
analogWrite(D5, level);
}
level is always 0, sometimes a random big number. The strip doesn’t change. I also think the slider shows «Sent; waiting for the device» forever. What am I doing wrong?
Traducido del English por IA ·
¿Quizás deberías hacer primero un cast a String? String s = (char*)payload;
Maybe cast it to a String first? String s = (char*)payload;
Traducido del English por IA ·
El payload no termina en nulo, así que leerlo como cadena C se sale del final. Ese es el número aleatorio.
The payload isn’t null-terminated, so reading it as a C string runs past the end. That’s the random number.
Traducido del English por IA ·
Incluso con un null al final, atoi sobre {«method»:… devuelve 0 porque el primer carácter es una llave. Necesitas parsear el JSON.
Even with a null at the end, atoi on {«method»:… gives 0 because the first character is a brace. You need to parse the JSON.
Traducido del English por IA ·
Kevin A y Maria tienen razón en ambos puntos. Hice casi el mismo controlador de luz para nuestra oficina el año pasado. Analiza el JSON con ArduinoJson (recibe el buffer y la longitud, así que no hace falta null), toma el id de la petición del final del topic y responde en v1/rpc/res/ con ese id. El «waiting for the device» se mantiene porque la placa nunca recibe respuesta.
#include <ArduinoJson.h>
void callback(char* topic, byte* payload, unsigned int length) {
String t(topic);
String id = t.substring(t.lastIndexOf('/') + 1); // "17"
StaticJsonDocument<256> doc;
if (deserializeJson(doc, payload, length)) return;
if (doc["method"] == "light.set") {
int level = doc["params"]["level"] | -1; // -1 if missing
if (level >= 0 && level <= 100) {
analogWrite(D5, map(level, 0, 100, 0, 1023));
client.publish(("v1/rpc/res/" + id).c_str(), "{"ok":true}");
return;
}
}
client.publish(("v1/rpc/res/" + id).c_str(), "{"ok":false}");
}
El analogWrite del ESP8266 va de 0 a 1023 por defecto, de ahí el map. Y suscríbete a v1/rpc/req/+ después de cada reconexión, no solo en setup, o los comandos dejan de llegar tras la primera caída del Wi-Fi.
La lista de topics está en MQTT topics and payload reference.
Kevin A and Maria have both bits. I did nearly the same light controller for our office last year. Parse the JSON with ArduinoJson (it takes the buffer and length, so no null needed), pull the request id off the end of the topic, and answer on v1/rpc/res/ with that id. The «waiting for the device» stays because the board never gets an answer.
#include <ArduinoJson.h>
void callback(char* topic, byte* payload, unsigned int length) {
String t(topic);
String id = t.substring(t.lastIndexOf('/') + 1); // "17"
StaticJsonDocument<256> doc;
if (deserializeJson(doc, payload, length)) return;
if (doc["method"] == "light.set") {
int level = doc["params"]["level"] | -1; // -1 if missing
if (level >= 0 && level <= 100) {
analogWrite(D5, map(level, 0, 100, 0, 1023));
client.publish(("v1/rpc/res/" + id).c_str(), "{"ok":true}");
return;
}
}
client.publish(("v1/rpc/res/" + id).c_str(), "{"ok":false}");
}
ESP8266 analogWrite is 0-1023 by default, hence the map. And subscribe to v1/rpc/req/+ after every reconnect, not only in setup, or commands stop after the first Wi-Fi drop.
The topic list is on MQTT topics and payload reference.
Traducido del English por IA ·
¡¡Funciona!! La tira ahora se atenúa con el deslizador y la placa muestra Done. Además, estaba respondiendo en v1/rpc/req/17 en lugar de res, así que aunque obtuviera bien el número, no llegaba nada de vuelta. Gracias Emily.
It works!! The strip dims with the slider now and the board says Done. I had also been answering on v1/rpc/req/17 instead of res, so even when I got the number right nothing came back. Thank you Emily.
- Debes estar registrado para responder a este debate.
Únete a la conversación
Inicia sesión para preguntar y responder, dar me gusta a las publicaciones útiles y marcar la respuesta que resolvió tu problema. Cada aportación suma puntos y niveles.

