Arduino Mega with ESP01S for MQTT

Hello guys, so straightforward to my problem that was "Why esp01s is disconnected every 1 hour? "
my wiring like this


and my sketch like this:

#include <MQTT.h>
#include <WiFiEspAT.h>

const int relayLampu = 22;
const int relayKipas = 23;

// MQTT server credentials
const char* mqttServer = "redacted";
const int mqttPort = 1883;
const char* mqttUser = "redacted";
const char* mqttPassword = "redacted";

// MQTT topics
const char* lampuStateTopic = "stat/kos/lampu";
const char* lampuCommandTopic = "cmnd/kos/lampu";
const char* kipasStateTopic = "stat/kos/kipas";
const char* kipasCommandTopic = "cmnd/kos/kipas";

const char* ssid = "redacted";
const char* password = "redacted";

WiFiClient net;
MQTTClient client;

int lastLampuStatus = HIGH;
int lastKipasStatus = HIGH;

void checkWiFi() {
  // Reconnect WiFi if disconnected
  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("WiFi disconnected! Reconnecting...");
    connectWiFi();
  }
}

void connectWiFi() {
  Serial.print("Connecting to WiFi...");
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("Connected to WiFi");
}

void setup() {
  pinMode(relayLampu, OUTPUT);
  pinMode(relayKipas, OUTPUT);
  digitalWrite(relayLampu, HIGH);
  digitalWrite(relayKipas, HIGH);
  Serial.begin(115200);
  Serial1.begin(115200); // Ensure this matches the ESP8266's baud rate

  WiFi.init(&Serial1);

  connectWiFi();

  client.begin(mqttServer, mqttPort, net);
  client.onMessage(messageReceived);

  connectMQTT();
}

void loop() {
  checkWiFi();

  if (!client.connected()) {
    connectMQTT();
  }
  client.loop();

  int lampuStatus = digitalRead(relayLampu);
  if (lampuStatus != lastLampuStatus) {
    publishState(lampuStateTopic, lampuStatus == LOW ? "ON" : "OFF");
    lastLampuStatus = lampuStatus; // Update last status
  }

  int kipasStatus = digitalRead(relayKipas);
  if (kipasStatus != lastKipasStatus) {
    publishState(kipasStateTopic, kipasStatus == LOW ? "ON" : "OFF");
    lastKipasStatus = kipasStatus; // Update last status
  }
}

void connectMQTT() {
  while (!client.connected()) {
    Serial.print("Connecting to MQTT...");
    if (client.connect("ArduinoMega", mqttUser, mqttPassword)) {
      Serial.println("Connected to MQTT");

      // Subscribe to the state topics
      client.subscribe(lampuCommandTopic);
      client.subscribe(kipasCommandTopic);
    } else {
      Serial.print("Failed, rc=");
      Serial.print(client.lastError());
      Serial.println(" Trying again in 5 seconds...");
      delay(5000);
    }
  }
}

void messageReceived(String &topic, String &payload) {
  Serial.println("================================MESSAGE RECEIVED==================================");
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("]: ");
  Serial.println(payload);

  // Control relays based on incoming MQTT messages
  if (topic == lampuCommandTopic) {
    digitalWrite(relayLampu, payload == "ON" ? LOW : HIGH);
  } else if (topic == kipasCommandTopic) {
    digitalWrite(relayKipas, payload == "ON" ? LOW : HIGH);
  }
}

void publishState(const char* stateTopic, const char* payload) {
  if (client.publish(stateTopic, payload)) {
    Serial.print("Published ");
    Serial.print(payload);
    Serial.print(" to ");
    Serial.println(stateTopic);
  } else {
    Serial.println("Failed to publish message");
  }
}

note: the breadboard power supply can supply up to 700mA
im powering up arduino using adapter 12V
and powering up power supply using adapter 9V

I just looking where it wrong and cant figure out myself can you guys help me?
Thanks :smile:

Use a dedicated 3.3V regulator (e.g., AMS1117-3.3) that can provide at least 500 mA for the ESP-01S. The regulator should be well-decoupled with capacitors (e.g., 10 µF and 100 nF) at the input and output.

Could be it's nothing to do with your circuit. Could be your WiFi router. The Arduino may not be aware of this and WiFi.status() may indicate that it believes it is still connected. Maybe try

void loop() {

  if (!client.connected()) {
    connectWiFi();
    connectMQTT();
  }
  client.loop()

is it disconnecting from mqtt or from WiFi?

alright gonna try this one too,,,,but what i figure it out in the serial monitor it comes out that wifi disconnected and can do reconnect using checkWifi() function

when i check on serial monitor it says disconnected from wifi although my wifi is all safe, when i try to restart the arduino mega the wifi can connect back idk like the function check wifi/connectwifi didnt help the reconnect,,,and the MQTT is so fine no problem

Guys idk what happen but 8 hour elapsed and just right now the wifi said disconnected not like before every 1 hour, is there anything i can do? maybe add some function to restart arduino every wifi disconnect? , because my function cant do reconnection to wifi like Paul said maybe the state is not really disconnected :slight_smile:

Only with ~6volt on the DC socket.
That will drop to ~250mA with 9volt input, due to thermal limitations (regulator gets hot).

A Mega would be happier with a 5volt cellphone charger connected to the USB socket.
Leo..

So, should i swap the adapter? or what better solution with my existing components? sorry for dumb question :sweat_smile:

Only YOU know if things get hot.
If they do, then that could be a reason to change things.
Leo..

i see, thanks for your answer

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.