Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /********* Pleasedontcode.com **********
- Pleasedontcode thanks you for automatic code generation! Enjoy your code!
- - Terms and Conditions:
- You have a non-exclusive, revocable, worldwide, royalty-free license
- for personal and commercial use. Attribution is optional; modifications
- are allowed, but you're responsible for code maintenance. We're not
- liable for any loss or damage. For full terms,
- please visit pleasedontcode.com/termsandconditions.
- - Project: **WiFi MQTT**
- - Source Code NOT compiled for: ESP32 DevKit V1
- - Source Code created on: 2025-01-27 15:11:27
- ********* Pleasedontcode.com **********/
- /****** SYSTEM REQUIREMENTS *****/
- /****** SYSTEM REQUIREMENT 1 *****/
- /* The project aims to develop a responsive Arduino */
- /* application utilizing connected components for */
- /* real-time data processing and user interaction. It */
- /* should support modular library integration for */
- /* enhanced functionality. */
- /****** END SYSTEM REQUIREMENTS *****/
- /* START CODE */
- /****** DEFINITION OF LIBRARIES *****/
- #include <WiFi.h>
- #include <HTTPClient.h>
- #include <ArduinoJson.h>
- #include <PubSubClient.h>
- /****** FUNCTION PROTOTYPES *****/
- void setup(void);
- void loop(void);
- // WiFi credentials
- const char* ssid = "your_SSID"; // Replace with your network SSID
- const char* password = "your_PASSWORD"; // Replace with your network password
- // MQTT broker details
- const char* mqtt_server = "broker.hivemq.com"; // Replace with your MQTT broker address
- WiFiClient espClient;
- PubSubClient client(espClient);
- /****** FUNCTION IMPLEMENTATIONS *****/
- void setup(void)
- {
- // Initialize Serial Monitor
- Serial.begin(115200);
- // Connect to WiFi
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.print(".");
- }
- Serial.println("Connected to WiFi");
- // Setup MQTT client
- client.setServer(mqtt_server, 1883);
- }
- void loop(void)
- {
- // Ensure the MQTT client is connected
- if (!client.connected()) {
- // Attempt to reconnect
- if (client.connect("ESP32Client")) {
- Serial.println("Connected to MQTT broker");
- } else {
- Serial.print("Failed to connect to MQTT broker, state: ");
- Serial.println(client.state());
- delay(2000);
- }
- }
- // Handle MQTT client loop
- client.loop();
- // Example: Publish a message
- StaticJsonDocument<200> doc;
- doc["message"] = "Hello from ESP32!";
- char jsonBuffer[512];
- serializeJson(doc, jsonBuffer);
- client.publish("test/topic", jsonBuffer);
- delay(5000); // Publish every 5 seconds
- }
- /* END CODE */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement