Conectarse a un broker
Use PubSubClient para conectarse a un servidor MQTT.
Conectarse a un broker es una lección gratuita de Arduino & IoT Academy en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Arduino & IoT Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Arduino & IoT Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
You Need a Broker First
Before any messages flow, your device must reach a broker. It is the server that accepts connections and routes every message.
Public or Private Brokers
You can use a free public broker like test.mosquitto.org for learning, or run your own private one for real projects.
The PubSubClient Library
On ESP boards the popular choice is the PubSubClient library. Install it once, then include it at the top of your sketch.
#include <PubSubClient.h>It Rides on a WiFi Client
PubSubClient needs a network client to ride on. You hand it a WiFiClient that has already joined your network.
WiFiClient espClient;
PubSubClient client(espClient);Point It at the Broker
Tell the client where the broker lives with its address and port. Plain MQTT uses port 1883 by default.
client.setServer("test.mosquitto.org", 1883);Give Each Device a Client ID
Every connection needs a unique client ID. If two devices share one, the broker kicks the older connection off.
Make the Connection
Call connect with your client ID to log in. It returns true when the broker accepts you and false if something is wrong.
client.connect("esp32-sensor-01");Reconnect When It Drops
Connections die on real networks. Wrap your connect in a loop so the device keeps retrying until it is back online.
Keep the Link Alive
You must call client.loop() often inside loop(). It handles keepalive pings and incoming messages behind the scenes.
void loop() {
client.loop();
}Authenticate When Needed
Private brokers usually want a username and password. Pass them to connect so only trusted devices get in.
client.connect("id", "user", "pass");Watch the Connection State
Print the result of connect or check client.state() to debug. Clear logs save you from guessing why nothing arrives.
Quick Check
Your ESP32 sketch compiles but never receives messages, even though it connected once. What is the likely cause?
Recap
You connected to a broker with PubSubClient: set the server and port, used a unique client ID, and kept the link alive. 🎉
Preguntas frecuentes
¿La lección «Conectarse a un broker» es gratis?
Sí — el texto completo de «Conectarse a un broker» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Arduino & IoT Academy, actualiza a CoddyKit PRO. El curso de Arduino & IoT Academy incluye 4 lecciones en total.
¿Qué aprenderé en «Conectarse a un broker»?
Use PubSubClient para conectarse a un servidor MQTT. Practicas Arduino & IoT Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Arduino & IoT Academy?
No se requiere experiencia previa. Arduino & IoT Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.
¿Cuánto tiempo toma la lección «Conectarse a un broker»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Arduino & IoT Academy?
Sí. Cada lección de Arduino & IoT Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Por qué MQTT encaja con IoT
- Conectarse a un broker
- Publicar temas de sensores
- Suscribirse y actuar ante comandos