Issue with communication between arduino mega and nodemcu esp 8266

Hello all,

I am trying to use serial communication to send and receive data between my arduino mega and my esp 8266. Essnetially, my goal is to detect the voltage drop on an analog pin on my mega, send this info to my esp 8266, and then send an email to notify myself. To test this, I am sending the integer value 1 via serial from the mega to the esp, and then am trying to trigger the esp to do something via an if statement, but the if statement is not triggering, inexplicable to me. If anyone could help that would be great. For wiring, I am connecting digital pins 5 and 6 on the mega to tx and rx on the esp.

Here is the code being used on the Mega:


#include <SoftwareSerial.h>

SoftwareSerial espSerial(5, 6);

//DHT dht(DHTPIN, DHTTYPE);

String str;

void setup(){

Serial.begin(115200);

espSerial.begin(115200);

//dht.begin();

delay(2000);

}

void loop()

{

//float h = dht.readHumidity();

// Read temperature as Celsius (the default)

//float t = dht.readTemperature();

Serial.print(1);

espSerial.println(1);

delay(1000);

}

Here is the code on the esp

/*

Rui Santos

Complete project details at:

- ESP32: [https://RandomNerdTutorials.com/esp32-send-email-smtp-server-arduino-ide/](https://randomnerdtutorials.com/esp32-send-email-smtp-server-arduino-ide/)

- ESP8266: [https://RandomNerdTutorials.com/esp8266-nodemcu-send-email-smtp-server-arduino/](https://randomnerdtutorials.com/esp8266-nodemcu-send-email-smtp-server-arduino/)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

Example adapted from: https://github.com/mobizt/ESP-Mail-Client

*/

#include <Arduino.h>

#if defined(ESP32)

#include <WiFi.h>

#elif defined(ESP8266)

#include <ESP8266WiFi.h>

#endif

#include <ESP_Mail_Client.h>

#define WIFI_SSID "wifi"

#define WIFI_PASSWORD "ppswrd"

/** The smtp host name e.g. [smtp.gmail.com](http://smtp.gmail.com/) for GMail or [smtp.office365.com](http://smtp.office365.com/) for Outlook or [smtp.mail.yahoo.com](http://smtp.mail.yahoo.com/) */

#define SMTP_HOST "[smtp.gmail.com](http://smtp.gmail.com/)"

#define SMTP_PORT 465

/* The sign in credentials */

#define AUTHOR_EMAIL "[[email protected]](mailto:[email protected])"

#define AUTHOR_PASSWORD "zjxb vlto oaox xqzv"

/* Recipient's email*/

#define RECIPIENT_EMAIL "[[email protected]](mailto:[email protected])"

/* Declare the global used SMTPSession object for SMTP transport */

SMTPSession smtp;

/* Callback function to get the Email sending status */

void smtpCallback(SMTP_Status status);

//variable for pin that failed

int pin = 12;

void email(int pin){

Serial.begin(115200);

Serial.println();

WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

Serial.print("Connecting to Wi-Fi");

while (WiFi.status() != WL_CONNECTED){

Serial.print(".");

delay(300);

}

Serial.println();

Serial.print("Connected with IP: ");

Serial.println(WiFi.localIP());

Serial.println();

/* Set the network reconnection option */

MailClient.networkReconnect(true);

/** Enable the debug via Serial port

* 0 for no debugging

* 1 for basic level debugging

*

* Debug port can be changed via ESP_MAIL_DEFAULT_DEBUG_PORT in ESP_Mail_FS.h

*/

smtp.debug(1);

/* Set the callback function to get the sending results */

smtp.callback(smtpCallback);

/* Declare the Session_Config for user defined session credentials */

Session_Config config;

/* Set the session config */

config.server.host_name = SMTP_HOST;

config.server.port = SMTP_PORT;

config.login.email = AUTHOR_EMAIL;

config.login.password = AUTHOR_PASSWORD;

config.login.user_domain = "";

/*

Set the NTP config time

For times east of the Prime Meridian use 0-12

For times west of the Prime Meridian add 12 to the offset.

Ex. American/Denver GMT would be -6. 6 + 12 = 18

See https://en.wikipedia.org/wiki/Time_zone for a list of the GMT/UTC timezone offsets

*/

config.time.ntp_server = F("[pool.ntp.org](http://pool.ntp.org/),[time.nist.gov](http://time.nist.gov/)");

config.time.gmt_offset = 3;

config.time.day_light_offset = 0;

/* Declare the message class */

SMTP_Message message;

/* Set the message headers */

message.sender.name = F("ESP");

message.sender.email = AUTHOR_EMAIL;

message.subject = F("ESP Test Email");

message.addRecipient(F("me"), RECIPIENT_EMAIL);

/*Send HTML message*/

/*String htmlMsg = "<div style=\"color:#2f4468;\"><h1>Hello World!</h1><p>- Sent from ESP board</p></div>";

message.html.content = htmlMsg.c_str();

message.html.content = htmlMsg.c_str();

message.text.charSet = "us-ascii";

message.html.transfer_encoding = Content_Transfer_Encoding::enc_7bit;*/

//Send raw text message

String PF;

PF= String(pin);

String textMsg;

textMsg= PF + " failed";

message.text.content = textMsg.c_str();

message.text.charSet = "us-ascii";

message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;

message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;

message.response.notify = esp_mail_smtp_notify_success | esp_mail_smtp_notify_failure | esp_mail_smtp_notify_delay;

/* Connect to the server */

if (!smtp.connect(&config)){

ESP_MAIL_PRINTF("Connection error, Status Code: %d, Error Code: %d, Reason: %s", smtp.statusCode(), smtp.errorCode(), smtp.errorReason().c_str());

return;

}

if (!smtp.isLoggedIn()){

Serial.println("\nNot yet logged in.");

}

else{

if (smtp.isAuthenticated())

Serial.println("\nSuccessfully logged in.");

else

Serial.println("\nConnected with no Auth.");

}

/* Start sending Email and close the session */

if (!MailClient.sendMail(&smtp, &message))

ESP_MAIL_PRINTF("Error, Status Code: %d, Error Code: %d, Reason: %s", smtp.statusCode(), smtp.errorCode(), smtp.errorReason().c_str());

}

void setup(){

email(1);

}

void loop(){

// Open serial communications and wait for port to open:

//Serial.begin(115200);

//while (!Serial) {

//; // wait for serial port to connect. Needed for native USB port only

//}

if (Serial.available()) {

//Serial.write(Serial.read());

int coms = Serial.read();

Serial.write(coms);

if (coms == 1){

Serial.write("test");

email(1);

}

else{

Serial.write("bruh")

}

}

}

/* Callback function to get the Email sending status */

void smtpCallback(SMTP_Status status){

/* Print the current status */

Serial.println(status.info());

/* Print the sending result */

if (status.success()){

// ESP_MAIL_PRINTF used in the examples is for format printing via debug Serial port

// that works for all supported Arduino platform SDKs e.g. AVR, SAMD, ESP32 and ESP8266.

// In ESP8266 and ESP32, you can use Serial.printf directly.

Serial.println("----------------");

ESP_MAIL_PRINTF("Message sent success: %d\n", status.completedCount());

ESP_MAIL_PRINTF("Message sent failed: %d\n", status.failedCount());

Serial.println("----------------\n");

for (size_t i = 0; i < smtp.sendingResult.size(); i++)

{

/* Get the result item */

SMTP_Result result = smtp.sendingResult.getItem(i);

// In case, ESP32, ESP8266 and SAMD device, the timestamp get from result.timestamp should be valid if

// your device time was synched with NTP server.

// Other devices may show invalid timestamp as the device time was not set i.e. it will show Jan 1, 1970.

// You can call smtp.setSystemTime(xxx) to set device time manually. Where xxx is timestamp (seconds since Jan 1, 1970)

ESP_MAIL_PRINTF("Message No: %d\n", i + 1);

ESP_MAIL_PRINTF("Status: %s\n", result.completed ? "success" : "failed");

ESP_MAIL_PRINTF("Date/Time: %s\n", MailClient.Time.getDateTimeString(result.timestamp, "%B %d, %Y %H:%M:%S").c_str());

ESP_MAIL_PRINTF("Recipient: %s\n", result.recipients.c_str());

ESP_MAIL_PRINTF("Subject: %s\n", result.subject.c_str());

}

Serial.println("----------------\n");

// You need to clear sending result as the memory usage will grow up.

smtp.sendingResult.clear();

}

}

You should not be using SoftwareSerial with a Mega - you should use one of its 3 hardware UARTs.

Serial1.print("1");
for instance
will send the character for the numeral '1'.

Your ESP sketch, for now, should be reduced to turning on an LED when a "1" is Serial.read.
I believe the 8266 is SoftwareSerial-capable.

ohhh so it would work if I said

if (Serial.read()==1){
Serial.write("test");
email(1);
}

if (Serial.read() == "1")

The email stuff - I don't know about.
If you can get the Serial.print("test") to work reliably, then the rest is academic I suppose.
Nail the fundamental and add the accessories later.

1 Like

To be clear:

Serial.write(1) ;  // writes the value 0x01
Serial.print(1); // writes the value 1 as the ASCII representation = 0x31
Serial.print('1')';  //  writes the single character '1' = 0x31
Serial.print("1"); // writes the 1 char array which is also 0x31

On the receiving side, you always read an int so make sure you test properly

if (Serial.read() == 1);  // matches Serial.write(1)
if (Serial.read() == '1'); // matches Serial.print(1), Serial.print('1') or Serial.print("1")
if (Serial.read() == "1");  // never works since "1" is a string

You also have to be aware that the Mega runs at 5V and the ESP2866 runs at 3.3V so you should not be wiring the Rx/Tx lines directly.

2 Likes

Hi there like @blh64 said don´t use the outputs directly, if you like you have to use resistors 270 Ohms and 470 Ohms, the 270 connected to gnd and the other to the powerline to reduce the voltage and what I saw also is you didn´t define the dht sensor pin, and why not using 2 ESP32 boards? If you already use one? You can use 1 ESP32 as a master and a lots of devices as slaves.

Greetings dingsken.

1 Like

@blh64
I have a hard time remembering that. Should have looked at my tried and true --

char inChar;

void setup() 
{
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
}

void loop() 
{
  if(Serial.available() > 0)
  {
    inChar = Serial.read();
    if(inChar == 'N')
    {
      digitalWrite(13, HIGH);
      delay(2000);
      digitalWrite(13, LOW);
    }
  }
}
#include <SoftwareSerial.h>
char inChar;
SoftwareSerial blueSerial(3, 2); // RX, TX  Arduino pin2 to BT's "RX"

void setup() 
{
  Serial.begin(9600);
  blueSerial.begin(9600);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
}

void loop() 
{
  if(blueSerial.available() > 0)
  {
    inChar = blueSerial.read();
    if(inChar == 'N')
    {
      digitalWrite(13, LOW);
      //delay(2000);
      //digitalWrite(13, LOW);
    }
    if(inChar == 'Y')
    {
      digitalWrite(13, HIGH);
    }
  }
}
1 Like

The email stuff I have figured out-- Just needed to get the communication going. Thanks for the help.

is there any particular reason to be using both a Mega and an ESP32/ESP8266?
why not just use the ESP32/ESP8266 to meansure the temperature and email the result
in addition for serial IO if using an ESP32 use a hardware serial port (Serial1 or Serial2) and if using an ESP8266 use EspSoftwareSerial

Mostly because it is what I have, and I need all of the analog pins on the mega.

The ESP32 Devkit V1 has 18 * 12 bit ADC channels

Available ADC channels with ESP32 MCU : 16
Available ADC channels with ESP32 Dev Module: 15 (Fig-1)

Figure-1:

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