Can't send data from Arduino Uno to ESP8266-01 serially

Hello.
I have an Arduino Uno and and ESP8266-01 module. I want to send data from a DHT11 sensor and a rain sensor, attached to the Arduino Uno to the ESP module via serial communication, and then to send them to HiveMQ Cloud. I don't get any prints in the serial monitor from the ESP, apart from the message "Hello World", which is also successfully sent to the topic in the cloud. I get the data readings from the Arduino correctly. I tried changing the baudrate as well, with no success. Here is the code:
Arduino code:

#include <DHT.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

#define DHTPIN 7       // DHT11 sensor data pin
#define DHTTYPE DHT11  // DHT11 sensor type
#define RAIN_PIN 4     // Rain sensor pin

bool isRaining = false; // Flag to track rain status

DHT dht(DHTPIN, DHTTYPE);

// LCD configuration for I2C
LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup() {
  Serial.begin(9600);  // Set baud rate to match ESP8266-01
  lcd.init();           // Initialize LCD
  lcd.backlight();      // Turn on backlight

  dht.begin();
  pinMode(RAIN_PIN, INPUT); // Set rain sensor pin as input
}

void loop() {
  float humidity = dht.readHumidity();
  float temperature = dht.readTemperature();

  if (isnan(humidity) || isnan(temperature)) {
    Serial.println("Failed to read from DHT sensor!");
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Sensor failure");
    delay(2000);
    return;
  }

  sendDataToESP(temperature, humidity, isRaining);

  if (digitalRead(RAIN_PIN) == LOW) {
    if (!isRaining) {
      Serial.println("It's raining!");
      isRaining = true; // Update rain status
      sendDataToESP(temperature, humidity, isRaining); // Sending data to ESP8266
      delay(1000);
    }
    Serial.print("Raining... \n");
  } else {
    if (isRaining) {
      Serial.println("Rain stopped!");
      isRaining = false; // Update rain status
      sendDataToESP(temperature, humidity, isRaining); // Sending data to ESP8266
      delay(1000);
    }
  }

  Serial.print("Temperature: ");
  Serial.print(temperature);
  Serial.print(" *C, Humidity: ");
  Serial.print(humidity);
  Serial.println("%");

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Temp: ");
  lcd.print(temperature);
  lcd.print("C");

  lcd.setCursor(0, 1);
  lcd.print("Humidity: ");
  lcd.print(humidity);
  lcd.print("%");

  delay(3000);
}

void sendDataToESP(float temp, float hum, bool rainStatus) {
  Serial.print(temp);
  Serial.print(",");
  Serial.print(hum);
  Serial.print(",");
  Serial.println(rainStatus ? "Raining" : "Not Raining");
}

ESP8266-01 code:

/*
 Basic sample of connecting ESP8266 with HiveMQ Cloud 

  - Time has to be obtained from NTP, because of CA expiration date validation.
 
 It connects to HiveMQ Cloud broker then:
  - Publishes "Hello World!" to the topic "testTopic" every two seconds.
  - Subscribes to the topic "testTopic", printing out any messages (string payload) it receives.

 It will reconnect to the server if the connection is lost using a blocking reconnect function.
*/

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <SoftwareSerial.h>

//---- WiFi settings
const char* ssid = "xxxxx";
const char* password = "xxxxx";

//---- HiveMQ Cloud Broker settings
const char* mqtt_server = "xxxxxxxxxxxx.s1.eu.hivemq.cloud";
const char* mqtt_user = "test123";
const char* mqtt_password = "xxxxxxx";

BearSSL::WiFiClientSecure espClient;
PubSubClient client(espClient);
SoftwareSerial arduinoSerial(2,3);

unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE	(50)
char msg[MSG_BUFFER_SIZE];
int value = 0;

// HiveMQ Cloud Let's Encrypt CA certificate (hardcoded)
static const char ca_cert[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcg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iogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
-----END CERTIFICATE-----
)EOF";

void setClock() {
  configTime(2 * 3600, 0, "ro.pool.ntp.org", "time.nist.gov"); // Adjusted for Bucharest (EET: UTC+2)

  Serial.print("Waiting for NTP time sync: ");
  time_t now = time(nullptr);
  while (now < 8 * 3600 * 2) {
    delay(500);
    Serial.print(".");
    now = time(nullptr);
  }
  Serial.println("");
  struct tm timeinfo;
  localtime_r(&now, &timeinfo); // Use localtime_r for local time
  Serial.print("Current time in Bucharest: ");
  Serial.print(asctime(&timeinfo));
}

void setup_wifi() {
  delay(10);
  Serial.begin(9600);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

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

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

void reconnect() {
  char err_buf[256];
  
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // MQTT client ID
    String clientId = "ESP8266Client";
    // Attempt to connect
    if (client.connect(clientId.c_str(), mqtt_user, mqtt_password)) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("testTopic", "Hello World!");
      // ... and resubscribe
      client.subscribe("testTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.println(client.state());
      espClient.getLastSSLError(err_buf, sizeof(err_buf));
      Serial.print("SSL error: ");
      Serial.println(err_buf);
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(9600);
  arduinoSerial.begin(9600);
  delay(5000);
  BearSSL::X509List *serverTrustedCA = new BearSSL::X509List(ca_cert);
  espClient.setTrustAnchors(serverTrustedCA);
  setup_wifi();
  setClock(); // Required for X.509 validation
  client.setServer(mqtt_server, 8883);
  client.setCallback(callback);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  //String dataArduino = arduinoSerial.readStringUntil('\n');
  //arduinoSerial.println("DE LA ARDUINO");

  while (arduinoSerial.available() > 0) {
    String dataReceived = arduinoSerial.readStringUntil('\n');
    Serial.print("Received data from Arduino: ");
    Serial.println(dataReceived);
    client.publish("testTopic", dataReceived.c_str());
  }
}

The data readings from the Arduino are printed correctly in the serial monitor. The wirings are correct as well.
Any help is greatly appreciated!

Can you post an annotated schematic showing how these are interconnected. Be sure to show all power, ground, and power sources. Also links to technical information on the hardware would be a big help.

You can't use the Arduino hardware serial for the serial monitor and the esp01 at the same time.

1 Like

remember the UNO uses 5V logic the ESP-01 3.3V - make sure you use a potential divider on the UNO Tx to ESP-01 Rx signal or you may damage the ESP-01
maybe simpler to connect a ds18b20-temperature-sensor to the ESP-01 and dump the UNO

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