Подключение к брокеру
Используйте PubSubClient для подключения к серверу MQTT.
«Подключение к брокеру» — бесплатный урок Arduino & IoT Academy на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Arduino & IoT Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Arduino & IoT Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
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. 🎉
Часто задаваемые вопросы
Урок «Подключение к брокеру» бесплатный?
Да — полный текст урока «Подключение к брокеру» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Arduino & IoT Academy, подпишись на CoddyKit PRO. Курс Arduino & IoT Academy содержит 4 уроков всего.
Чему я научусь в уроке «Подключение к брокеру»?
Используйте PubSubClient для подключения к серверу MQTT. Ты практикуешь Arduino & IoT Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Arduino & IoT Academy?
Предыдущий опыт не требуется. Arduino & IoT Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.
Сколько времени занимает урок «Подключение к брокеру»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Arduino & IoT Academy?
Да. Каждый урок Arduino & IoT Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Почему MQTT подходит для IoT
- Подключение к брокеру
- Публикация тем датчиков
- Подписка и выполнение команд