Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <WiFi.h>
- #include <PubSubClient.h>
- #define pin_Pot 36
- // WiFi
- const char *ssid = "RobotikID";
- const char *password = "123456789";
- // Broker MQTT
- const char *mqtt_broker = "free.mqtt.iyoti.id";
- const char *topic_pub = "robotikid/pub";
- const char *topic_sub = "robotikid/sub";
- const char *mqtt_username = "RobotikID";
- const char *mqtt_password = "1234567";
- const int mqtt_port = 1883;
- char client_id[20];
- unsigned long lastMillis = 0;
- char data_pot_sebelum[10] = "";
- WiFiClient espClient;
- PubSubClient client(espClient);
- const unsigned long MQTT_RECONNECT_DELAY = 5000; // Delay untuk mencoba kembali koneksi MQTT
- const unsigned long WIFI_RECONNECT_DELAY = 5000; // Delay untuk mencoba kembali koneksi WiFi
- void callback(char *topic, byte *payload, unsigned int length) {
- Serial.print("Pesan diterima [");
- Serial.print(topic);
- Serial.print("] ");
- // Tangani pesan yang masuk di sini
- Serial.println("Payload:");
- for (int i = 0; i < length; i++) {
- Serial.print((char)payload[i]);
- }
- Serial.println();
- }
- void setup() {
- Serial.begin(115200);
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.println("Menghubungkan ke WiFi..");
- }
- Serial.println("Terhubung ke WiFi");
- // Menghubungkan ke broker MQTT
- client.setServer(mqtt_broker, mqtt_port);
- while (!client.connected()) {
- if (client.connect(client_id, mqtt_username, mqtt_password)) {
- Serial.println("Terhubung ke broker MQTT");
- } else {
- Serial.print("Gagal Terhubung ");
- Serial.print(client.state());
- delay(MQTT_RECONNECT_DELAY);
- }
- }
- // Melakukan langganan topik
- client.setCallback(callback);
- client.subscribe(topic_sub);
- client.publish(topic_pub, "Halo, ESP32");
- lastMillis = millis();
- }
- void loop() {
- if (WiFi.status() != WL_CONNECTED) {
- WiFi.begin(ssid, password);
- delay(WIFI_RECONNECT_DELAY);
- } else if (!client.connected()) {
- reconnect();
- }
- client.loop();
- int analog_pot = analogRead(pin_Pot);
- char data_pot[10];
- sprintf(data_pot, "%d", analog_pot);
- if (millis() - lastMillis >= 1000) {
- client.publish(topic_pub, data_pot);
- Serial.println(data_pot);
- lastMillis = millis();
- strncpy(data_pot_sebelum, data_pot, sizeof(data_pot_sebelum));
- }
- }
- void reconnect() {
- while (!client.connected()) {
- Serial.print("Mencoba koneksi MQTT...");
- if (client.connect(client_id, mqtt_username, mqtt_password)) {
- Serial.println("terhubung");
- client.subscribe(topic_sub);
- } else {
- Serial.print("gagal, rc=");
- Serial.print(client.state());
- Serial.println(" coba lagi dalam 5 detik");
- delay(WIFI_RECONNECT_DELAY);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement