Why isn't my ATmega328P sending DHT11 sensor data to the ESP-01 module via MQTT?

I am working on a temperature and humidity monitoring system using an ESP-01 module (ESP8266) and an 8-bit AVR microcontroller (ATmega328P). I am using the DHT11 sensor to read temperature and humidity values. The ESP-01 is used to send the sensor data to an IoT platform via Wi-Fi using the MQTT protocol. The system is running on the Arduino OS.

I have been able to configure the software to communicate with a sensor and transmit data, also set up pins for serial communication, initialized the sensor to read temperature and humidity, and implemented error checking for readings, then built a message with sensor data and tried to send it to the ESP-01 module. But then still encountered this error:
The ATmega328P is not successfully sending the read data to the ESP-01 module. If successful, the ATmega328P should be able to read and send the sensor data to the ESP-01 module.

This is my code snippet:
#include <DHT.h>
#include <SoftwareSerial.h>

#define DHTPIN 2  // Pin where the DHT11 is connected
#define DHTTYPE DHT11 // DHT 11

DHT dht(DHTPIN, DHTTYPE);
SoftwareSerial ESPserial(10, 11); // RX, TX (Potentially incorrect pins)

void setup() {
  Serial.begin(9600);
  // Introduce a potential baud rate mismatch between ATmega328P and ESP-01
  ESPserial.begin(115200); // Incorrect baud rate (assuming ESP-01 expects 9600)
  dht.begin();
  delay(2000);
}

void loop() {
  float h = dht.readHumidity();
  float t = dht.readTemperature();

  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  String data = "Temperature: " + String(t) + " Humidity: " + String(h);
  Serial.println(data);

  // Introduce a potential issue with ESPserial.print vs. ESPserial.println
  ESPserial.print(data); // Might not send a newline character

  delay(2000);
}

@Middleware & OS
Solution
The ATmega328P and ESP-01 need to communicate at the same baud rate. Change ESPserial.begin(115200); to ESPserial.begin(9600);.
Was this page helpful?