I am trying to set up two-way communication between nodemcu and Arduino mega using serial i.e nodemcu send some particular data to Arduino and after receiving it Arduino responds it with another data particularly a string or integer. Is there any way to do it?
Have a look at the examples in Serial Input Basics - simple reliable ways to receive data. There is also a parse example to illustrate how to extract numbers from the received text.
The technique in the 3rd example will be the most reliable. It is what I use for Arduino to Arduino and Arduino to PC communication.
You can send data in a compatible format with code like this (or the equivalent in any other programming language)
Serial.print('<'); // start marker
Serial.print(value1);
Serial.print(','); // comma separator
Serial.print(value2);
Serial.println('>'); // end marker
...R
Here's where I started... extremely helpful.
"Gammon Forum : Electronics : Microprocessors : I2C - Two-Wire Peripheral Interface - for Arduino"
1. Build the following hardware setup between NodeMCU1.0 and MEGA. NodeMCU communicates with it SM1 uisng UART Port; it uses software UART port (SUART Port) to communicates with UART1 Port of MEGA.
2. NodeMCU sends 1234 to MEGA.
#include<SoftwareSerial.h>
SoftwareSerial SUART(4, 5); //D2, D1 = SRX, STX
char recStr[10] = "";
char ourStr[8] = "Arduino";
bool flag1 = false;
void setup()
{
Serial.begin(115200);
SUART.begin(115200);
}
void loop()
{
SUART.print("<1234>"); //sending 1234
Serial.println("<1234>");
//--add codes as needed to capture string coming from MEGA
delay(1000);
}
3. MEGA receives 1234 from NodeMCU and then sends the string - Arduino - to NodeMCU.
char recStr[10] = "";
void setup()
{
Serial.begin(115200);
Serial1.begin(115200);
}
void loop()
{
byte n = Serial1.available();
if (n != 0)
{
Serial1.readBytesUntil('>', recStr, 10);
int x = atoi(recStr + 1);
if (x == 1234)
{
char recStr[10] = "";
Serial.println("Received 1234 from Node; now sending - Arduino - to Node...!");
Serial1.println("<Arduino>");
}
}
}