This is a simple Arduino sketch for an ESP32 that connects to a WiFi network and an MQTT broker. It periodically publishes a "Hello" message to a specified topic.
- Connects to a WiFi network.
- Connects to a specified MQTT broker.
- Publishes a message to
test/topic
every 10 seconds. - Includes automatic reconnection logic for the MQTT connection.
- An ESP32 development board.
- PubSubClient: You can install this library through the Arduino IDE Library Manager. Search for
PubSubClient
by Nick O'Leary.
To keep your sensitive information (like WiFi and MQTT credentials) separate from the main code, we use a secrets.h
file. This file is not included in the repository for security reasons.
You must create it yourself by following these steps:
- Create a copy of the
secrets.h.example
file. - Rename the copied file to
secrets.h
. - Open the new
secrets.h
file and fill in your credentials.
Example content of secrets.h
:
#define WIFI_SSID "YOUR_WIFI_SSID"
#define WIFI_PASSWORD "YOUR_WIFI_PASSWORD"
#define MQTT_SERVER "your_mqtt_broker_address"
#define MQTT_PORT 1883
#define MQTT_USER "your_mqtt_username"
#define MQTT_PASSWORD "your_mqtt_password"
- Install the required libraries.
- Configure your credentials in
secrets.h
as described above. - Upload the sketch to your ESP32.
- Open the Serial Monitor at a baud rate of 115200 to see the connection status and messages.
- اتصال به شبکه وایفای.
- اتصال به بروکر MQTT مشخص شده.
- ارسال پیام به تاپیک
test/topic
هر ۱۰ ثانیه یکبار. - دارای منطق اتصال مجدد خودکار در صورت قطع ارتباط با بروکر MQTT.
- یک برد توسعه ESP32.
- PubSubClient: این کتابخانه را میتوانید از طریق Library Manager در نرمافزار آردوینو نصب کنید. عبارت
PubSubClient
نوشته Nick O'Leary را جستجو کنید.
برای جدا نگه داشتن اطلاعات حساس شما (مانند نام و رمز عبور وایفای و MQTT) از کد اصلی، از فایلی به نام secrets.h
استفاده شده است. این فایل به دلایل امنیتی در مخزن کد قرار داده نمیشود.
شما باید خودتان این فایل را با طی کردن مراحل زیر ایجاد کنید:
۱. یک کپی از فایل secrets.h.example
بسازید.
۲. فایل کپی شده را به secrets.h
تغییر نام دهید.
۳. فایل جدید secrets.h
را باز کرده و اطلاعات شخصی خود را در آن وارد کنید.
محتوای نمونه فایل secrets.h
باید به این شکل باشد:
#define WIFI_SSID "YOUR_WIFI_SSID"
#define WIFI_PASSWORD "YOUR_WIFI_PASSWORD"
#define MQTT_SERVER "your_mqtt_broker_address"
#define MQTT_PORT 1883
#define MQTT_USER "your_mqtt_username"
#define MQTT_PASSWORD "your_mqtt_password"
۱. کتابخانههای مورد نیاز را نصب کنید.
۲. فایل secrets.h
را مطابق توضیحات بالا با اطلاعات خودتان تکمیل کنید.
۳. کد را روی برد ESP32 خود آپلود کنید.
۴. سریال مانیتور را با باد ریت 115200 باز کنید تا وضعیت اتصال و پیامها را مشاهده کنید.