Serial Communication between NodeMCU and Arduino

Hi guys, in this post we will discuss how to establish Serial Communication between NodeMCU and Arduino[Esp8266 -12E] is explained.
Embedded Systems should be connected with each other to transfer data between them. Because all operations can’t be performed on a single system. For example, Arduino has 6 analog pins but NodeMCU has only one analog pin. So two are more microcontrollers or microprocessors can be combined to form a required embedded system. The connection can be established through any of the following protocols.

  • SPI
  • I2C
  • UART

Serial Communication:


 Serial communication is a communication process wherein data transfer occurs by transmitting data one bit at a time in sequential order over a computer bus or a communication channel. It is the most widely used approach to transfer information between data processing equipment and peripherals. Binary One represents a logic HIGH or 5 Volts, and zero represents a logic LOW or 0 Volts, used for communicating between the Arduino board and a computer or other devices. All Arduino boards have at least one serial port which is also known as a UART or USART. It communicates on digital pins 0 (RX) and 1 (TX) as well as with the computer via USB. Serial communication on pins TX/RX uses TTL logic levels (5V or 3.3V depending on the board).To establish serial communication between two devices, the devices should be connected as shown below.. Because the data sent from the device 1 should be received in the device 2 and vice versa.

CONNECTION:

serial commuication between arduino and nodemcu

1. Sending single data between Arduino and NodeMcu:






In this tutorial, the data is sent from Arduino to NodeMCU. NodeMCU requests the data from the Arduino by sending a character. Once the Arduino detects that there is an incoming data it sends the data in serial as the response. This Arduino and the NodeMCU code for the above-explained procedure is given below

ARDUINO PART:
In Arduino, we shall consider pin 5 as Rx and pin 6 as Tx. To use the GPIO pins for serial communication SoftwareSerial library can be used. Here we have created a serial port named s with pin 5 as RX and pin 6 as TX.

1
2
#include <SoftwareSerial.h>
SoftwareSerial s(5,6); // (Rx, Tx)

To begin the serial communication between Arduino and NodeMCU with 9600 bits per second

1
2
3
void setup() {
s.begin(9600);
}

To check if there is any incoming data in the serial the following command is used

1
2
3
if(s.available()>0)
{
}

To write our data in data in serial if there is an incoming data the void loop is configured as

1
2
3
4
5
6
7
 void loop() {
int data=50;
if(s.available()>0)
{
 s.write(data);
}
}

ARDUINO FULL CODE

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//Arduino code
#include <SoftwareSerial.h>
SoftwareSerial s(5,6);
 
void setup() {
s.begin(9600);
}
 
void loop() {
int data=50;
if(s.available()>0)
{
 s.write(data);
}
}

NODEMCU PART:
In NodeMCU we shall make pin 5 as Tx and pin 6 as Rx. So data sent by Arduino will be received by the NodeMCU and vice versa. So we can establish a successful Serial Communication between NodeMCU and Arduino.

1
2
#include <SoftwareSerial.h>
SoftwareSerial s(D6,D5); // (Rx, Tx)

NodeMCU sends the control character and starts listening for the data from the Arduino. This is implemented in the NodeMCU as shown below

1
2
3
4
5
6
7
8
void loop() {
  s.write("s");
  if (s.available()>0)
  {
    data=s.read();
    Serial.println(data);
  }
}

NODEMCU FULL CODE

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <SoftwareSerial.h>
SoftwareSerial s(D6,D5);
int data;
void setup() {
s.begin(9600);
Serial.begin(9600);
}
 
void loop() {
  s.write("s");
  if (s.available()>0)
  {
    data=s.read();
    Serial.println(data);
  }
 
 
}

2. Sending Multiple data between NodeMCU and Arduino:






To send multiple data in serial, JSON can be adapted. JSON stands for JavaScript Object Notation. JSON is a lightweight data interchange format for structuring data. JSON is based on key-value pairs. Key is always string, where value may be a integer, string or an array. An example of JSON is given below

1
2
3
4
5
{
"name":"mybtechprojects",
"no_of_posts":52,
"members":4
}

To know more about json visit this post. To install Json library follow the following steps.

  1. Go to Sketch–>Manage Library.
  2. Then search for ArduinoJson library and install 5.x version, since the 6.x version is still in beta. 6.x versions have a different type of functions.ArduinoJson library Installation

ARDUINO PART:
JsonBuffer does the memory management function. It contains two types

  1. DynamicJsonBuffer
  2. StaticJsonBuffer

DynamicJsonBuffer updates the memory automatically according to the requirement. Where StaticJsonBuffer allocates fixed memory and will not change according to the requirement. Here we have created a StaticJsonBuffer with a size 200.

1
StaticJsonBuffer<200> jsonBuffer;

JsonObject is where the key-value pairs are stored. The memory of the JsonObject is located in the buffer. The key-value pairs are generated as shown below

1
2
3
JsonObject& root = jsonBuffer.createObject();
root["data1"] = 100;
root["data2"] = 200;

To print the JsonObject to the serial port the following command is used

1
root.printTo(s);

ARDUINO FULL CODE

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <SoftwareSerial.h>
#include <ArduinoJson.h>
SoftwareSerial s(5,6);
 
void setup() {
s.begin(9600);
}
 
void loop() {
 StaticJsonBuffer<1000> jsonBuffer;
 JsonObject& root = jsonBuffer.createObject();
  root["data1"] = 100;
  root["data2"] = 200;
if(s.available()>0)
{
 root.printTo(s);
}
}

NODEMCU PART:

1
2
StaticJsonBuffer<1000> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(s);

The above mentioned code is used to create the jsonbuffer and read the JSON string the serial port and store it in a JsonOnject.

1
2
if (root == JsonObject::invalid())
    return;

If the JSON data parsed from the serial port is not in the valid format it should be ignored and the loop function repeats again.

NODEMCU FULL CODE

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <SoftwareSerial.h>
SoftwareSerial s(D6,D5);
#include <ArduinoJson.h>
 
void setup() {
  // Initialize Serial port
  Serial.begin(9600);
  s.begin(9600);
  while (!Serial) continue;
 
}
 
void loop() {
 StaticJsonBuffer<1000> jsonBuffer;
  JsonObject& root = jsonBuffer.parseObject(s);
  if (root == JsonObject::invalid())
    return;
 
  Serial.println("JSON received and parsed");
  root.prettyPrintTo(Serial);
  Serial.print("Data 1 ");
  Serial.println("");
  int data1=root["data1"];
  Serial.print(data1);
  Serial.print("   Data 2 ");
  int data2=root["data2"];
  Serial.print(data2);
  Serial.println("");
  Serial.println("---------------------xxxxx--------------------");
 
}

OUTPUT OF NodeMCU


3. To Send Dynamic Sensor Data from Arduino to NodeMCU





Now we shall send DHT-11 data and Gas sensor data from Arduino to NodeMCU through serial communication. To interface DHT-11 with NodeMCU and install the required libraries visit this post. Kindly refer to the connections given below,

ARDUINO PART:
Note
If the DHT-11 is not connected to the correct pin or if it does not work no data will be sent to NodeMCU.
Include the DHT library, define the pin to which the DHT sensor is connected, define the type of the DHT connected as shown below.

1
2
3
#include "DHT.h"
#define DHTPIN 2     
#define DHTTYPE DHT11

Create an object for the DHT class and pass the DHTPIN and DHTTYPE as parameters for constructer and begin the dht.

1
2
DHT dht(DHTPIN, DHTTYPE);
dht.begin();

Use the functions of the DHT library to find the temperature, humidity and heat index.

1
2
3
4
5
6
7
8
9
10
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);
 
  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

The values are stored as key values pairs to the JsonObject root. The value of the gas sensor connected to the analog pin is also read and stored. Then the data is printed into the serial port.

1
2
3
4
5
6
7
8
9
 root["temp"] = t;
 root["hum"] = h;
 root["hi"] = hic;
 root["gasv"]= analogRead(A0);
 
if(s.available()>0)
{
 root.printTo(s);
}

ARDUINO FULL CODE:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
 
#include <SoftwareSerial.h>
#include <ArduinoJson.h>
SoftwareSerial s(5,6);
#include "DHT.h"
#define DHTPIN 2     
#define DHTTYPE DHT11   
DHT dht(DHTPIN, DHTTYPE);
 
void setup() {
  s.begin(115200);
  pinMode(A0,INPUT);
  dht.begin();
}
StaticJsonBuffer<1000> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
void loop() {
 
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);
 
  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);
if (isnan(h) || isnan(t) || isnan(f)) {
    return;
  }
  // If the DHT-11 is not connected to correct pin or if it doesnot
//work no data will be sent
  root["temp"] = t;
  root["hum"] = h;
  root["hi"] = hic;
  root["gasv"]= analogRead(A0);
 
if(s.available()>0)
{
 root.printTo(s);
}
}

NODEMCU PART:
NODEMCU FULL CODE

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <SoftwareSerial.h>
SoftwareSerial s(D6,D5);
#include <ArduinoJson.h>
 
void setup() {
  // Initialize Serial port
  Serial.begin(115200);
  s.begin(115200);
  while (!Serial) continue;
}
 
void loop() {
  StaticJsonBuffer<1000> jsonBuffer;
  JsonObject& root = jsonBuffer.parseObject(s);
 
  if (root == JsonObject::invalid())
  {
    return;
  }
  //Print the data in the serial monitor
  Serial.println("JSON received and parsed");
  root.prettyPrintTo(Serial);
  Serial.println("");
  Serial.print("Temperature ");
  int data1=root["temp"];
  Serial.println(data1);
  Serial.print("Humidity    ");
  int data2=root["hum"];
  Serial.println(data2);
  Serial.print("Heat-index  ");
  int data3=root["hi"];
  Serial.println(data3);
  Serial.print("gas sensor  ");
  int data4=root["gasv"];
  Serial.println(data4);
  Serial.println("");
  Serial.println("---------------------xxxxx--------------------");
 Serial.println("");
}

OUTPUT:

dynamic data transfer using serial communication between arduino and nodemcu

To learn Python Basics for free kindly refer my tutorials here. And to get started with RaspberryPi microcontroller check these posts.




 

 THANK YOU
SHARE THIS!!!

Gowtham S

Gowtham is a programming enthusiast. His field of interest includes Arduino, NodeMCU, Raspberry Pi, and Python. To know more about him visit https://mybtechprojects.tech/about-us/.

54 Comments

  • How to send dynamic data from ARDUINO to nodemcu.
    When I’m trying to send using the 1 st program, i received nothing.

  • hey, i try use for program 1 to create serial communication for node mcu esp8266 and arduino nano with data from MQ 7 sensor, but the data send to node MCU looks different from data at nano serial monitor. can you help me?? whats wrong ??

    Arduino program
    #include
    SoftwareSerial s(0,1);

    int sensorValue;

    void setup() {
    Serial.begin(115200);
    pinMode(A1,INPUT);
    s.begin(115200);

    //pinMode(A1,INPUT);
    }

    void loop() {
    sensorValue = analogRead(1); // read analog input pin 0
    Serial.print(sensorValue/60, DEC); // prints the value read
    Serial.println(“ppm”);
    if(s.available()>0)
    {
    s.write(sensorValue);
    }

    delay(1000);
    }

    MCU program
    #include
    SoftwareSerial s(D7,D6);
    int data;
    void setup() {
    s.begin(115200);
    Serial.begin(115200);
    }

    void loop() {
    s.write(“s”);
    if (s.available()>0)
    {
    data=s.read();
    Serial.print(data);
    Serial.println(“ppm”);
    }
    delay(1000);

    }

    • Hi,

      Nice to hear from you. Try reading data from the analog pin if only serial port is available as shown below,

      SoftwareSerial s(0,1);

      int sensorValue;

      void setup() {
      Serial.begin(115200);
      pinMode(A1,INPUT);
      s.begin(115200);

      //pinMode(A1,INPUT);
      }

      void loop() {
      if(s.available()>0)
      {
      sensorValue = analogRead(1); // read analog input pin 0
      Serial.print(sensorValue/60, DEC); // prints the value read
      Serial.println(“ppm”);
      s.write(sensorValue);
      }

      delay(1000);
      }

  • Wouldn’t you need a tension divider for this communication? Can NodeMCU withstand 5V serial?

    • Hi hendrio,
      Good to hear from you. Serial Communication can be established directly between nodemcu and Arduino without other modules.
      Thank you.

  • How can I receive and send data between Arduino and nodeMCU?

  • // Memory pool for JSON object tree.
    //
    // Inside the brackets, 200 is the size of the pool in bytes.
    // Don’t forget to change this value to match your JSON document.
    // Use arduinojson.org/assistant to compute the capacity.

    can u explain me about this . i dont understand

  • how to send data from nodemcu to arduino. when i am using this code in reverse manner. it’s printing nothing on the arduino serial monitor.

    • When you interchange the code make sure you use SoftwareSerial s(5,6); for Arduino and SoftwareSerial s(D6,D5); for NodeMCU

  • Hi, may i know if i using the Arduino Mega to communicate with NodeMCU If the pin from the NodeMCU can be connected to the Arduino TX0 and RX0.

    • Hi Lim,

      Nice to hear from you, Yes, of course, you can use the Serial port(TX0,RX0). But in these examples we are defining our own serial ports using SoftwareSerial Library.

  • Hi, I have been implemented this project. This is working, but sometimes I’m receiving the zero value in the variables of the root what I’m using.
    How to solve this problem ? I’m using this values to print in a HTTP server using nodeMCU

    Thanks !

    • Hi Vitor,
      Happy to hear that you have tried out this idea. Zero in the variables implies that the size of the JSON Buffer is not sufficient. So try increasing the size of the JSON buffer.

      StaticJsonBuffer<200> jsonBuffer;

      Try using higher values instead of 200.

      Thankyou.

  • communication between arduino mega and nodemcu does not work. I have followed your stage. but it doesn’t work in my tool.

  • Hi. you have done a great task. however. I have 1 question. can I implement the same thing with distance sensor?

    • Hi amir,
      Nice to hear from you. Of course we can implement the same thing with ultrasonic sensor. Refer this post for connections and code here.

  • Hello, thank you for this amazing tutorial!
    One question, in sending multiple data nodemcu part

    while (!Serial) continue;

    What does this part do? And is this the SoftwareSerial or the Serial Monitor?

    Thanks!

    • Hi Ghareisa,
      Thanks for your complement. while (!Serial) continue; is used to check if the serial port is available for communication or not.

  • Arduino: 1.8.2 (Windows 10), Board: “NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Disabled, 4M (no SPIFFS), v2 Lower Memory, Disabled, None, Only Sketch, 115200″

    WARNING: Category ” in library ArduinoJson is not valid. Setting to ‘Uncategorized’
    Build options changed, rebuilding all
    C:\Users\Lenovo\Documents\Arduino\brodcemotori\SerialCommunicationEsp\SerialCommunicationEsp.ino: In function ‘void loop()’:

    SerialCommunicationEsp:14: error: no matching function for call to ‘ArduinoJson::StaticJsonBuffer::parseObject(SoftwareSerial&)’

    JsonObject& root = jsonBuffer.parseObject(s);

    ^

    C:\Users\Lenovo\Documents\Arduino\brodcemotori\SerialCommunicationEsp\SerialCommunicationEsp.ino:14:46: note: candidates are:

    In file included from C:\Users\Lenovo\Documents\Arduino\libraries\ArduinoJson\src/../include/ArduinoJson/DynamicJsonBuffer.hpp:9:0,

    from C:\Users\Lenovo\Documents\Arduino\libraries\ArduinoJson\src/../include/ArduinoJson.h:7,

    from C:\Users\Lenovo\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson.h:13,

    from C:\Users\Lenovo\Documents\Arduino\brodcemotori\SerialCommunicationEsp\SerialCommunicationEsp.ino:3:

    C:\Users\Lenovo\Documents\Arduino\libraries\ArduinoJson\src/../include/ArduinoJson/JsonBuffer.hpp:75:15: note: ArduinoJson::JsonObject& ArduinoJson::JsonBuffer::parseObject(char*, uint8_t)

    JsonObject &parseObject(char *json, uint8_t nestingLimit = DEFAULT_LIMIT);

    ^

    C:\Users\Lenovo\Documents\Arduino\libraries\ArduinoJson\src/../include/ArduinoJson/JsonBuffer.hpp:75:15: note: no known conversion for argument 1 from ‘SoftwareSerial’ to ‘char*’

    C:\Users\Lenovo\Documents\Arduino\libraries\ArduinoJson\src/../include/ArduinoJson/JsonBuffer.hpp:78:15: note: ArduinoJson::JsonObject& ArduinoJson::JsonBuffer::parseObject(const String&, uint8_t)

    JsonObject &parseObject(const String &json,

    ^

    C:\Users\Lenovo\Documents\Arduino\libraries\ArduinoJson\src/../include/ArduinoJson/JsonBuffer.hpp:78:15: note: no known conversion for argument 1 from ‘SoftwareSerial’ to ‘const String&’

    exit status 1
    no matching function for call to ‘ArduinoJson::StaticJsonBuffer::parseObject(SoftwareSerial&)’

    This report would have more information with
    “Show verbose output during compilation”
    option enabled in File -> Preferences.

  • why on sending multiple data node mcu full command got an error that is D6 is not declared in this scope

    • Hi nazim,
      Thanks for asking. I think that you are running the NodeMCU code in Arduino. Since D6 pin is not available in Arduino.

  • 1) how did you run 2 sketches, they are differnt progrms 1 for uno and other for nodemcu
    2) i need to send data to a cloud thingsspeak how do i do that?
    meaning i want a code to send the value from nodemcu to cloud

    • Hi sai nikhilesh,
      Thanks for asking. Follow the steps given below.
      1) To run 2 sketches

      1. Connect the Arduino Uno to the software
      2. Select Arduino Uno from the boards
      3. Select the port which the Arduino is connected
      4. Upload the code into Arduino
      5. Connect the NodeMCU to the laptop
      6. Select NodeMcu from the boards
      7. Select the port to which it is connected and upload the code
      8. Open the Serial Monitor to see the data incoming

      2) To send data to thingspeak refer this. To send data to ubidots cloud refer this.

  • hi!
    can you help me in programming to display dynamically the distance using ultrasonic sensor. please do help.

  • How to send data from nodemcu to Arduino using Arduino JSON. I want to receive character from mobile app on nodemcu . Send this character from nodemcu to Arduino using Arduino JSON. I want to control water pump using arduino

  • Hi,i follow all the instruction as above but why my serial for node mcu display nothing ? both(node mcu & arduino) usb port is connected to 5v ?

  • Muhammad Ibrahim

    (March 31, 2019 - 6:36 am)

    I received invalid JSON Format—->
    {” ” :t
    }Data 1 0
    Data 2 0
    what is the problem the connection and the code is the same you make .so what is the problem?

    • Hi Ibrahim,
      Thanks for asking. Have you installed the 5.x version of ArduinoJson library? Because 6.x versions are in beta. And make sure that the connections are correct since you don’t receive any data. Thankyou.

  • how to do serial communication from arduino uno to ESP8266-01?

    • Hi Dhruv,
      You can follow the same code given above, after flashing the NodeMCU firmware into esp8266. For flashing firmware refer here.

  • i have done all the steps but in serial monitor it is not showing correctly

    i am working on this project (https://circuitdigest.com/microcontroller-projects/iot-electricity-energy-meter-using-esp12-arduino) and want to send data from arduino to node emu for further transmitting it to web but not able to send data from arduino to node emu please help..

    • Hi shreyansh,

      IoT Based Electricity Energy Meter is a good project. First, make sure that the connections are correct. Then program the Arduino first and then NodeMCU.

  • Great tutorial!
    However, what about sending data FROM a NodeMcu TO an Arduino with serial. I’ve been stuck for days trying to make that work. All i get is a blank serial monitor on my Arduino’s side. Could you make a tutorial on how to do that ?

    • Hi Jasper Smith,
      Thanks. Reusing the same code in a reverse manner should work. But make sure that you change the rx and tx pins in the codes.

  • Hello,
    thank you for this great tutorial. I followed the steps but I see nothing in the serial monitor ( i used arduino uno).
    Also, If I used arduino mega, what pins shoul I change in the serial software?

    • Hello Aisha,
      Thanks for asking. I guess that you are establishing serial communication between Arduino Uno and Arduino Mega. You can use the same code for for Arduino Uno but for Arduino Mega use the NodeMCU code but change the serial pins in NodeMCU code. SoftwareSerial s(6,5); or any pins instead of SoftwareSerial s(D6,D5);.

  • HI Sir. how can i communicate uno with nodemcu with ultrasonic sensor to the thingspeak?

    • Thanks for asking. First, we can directly interface the ultrasonic sensor with NodeMCU. Then we can push the data from NodeMCU to Thingspeak. Check this post for sending data to thingspeak.

  • Hi Gowtham, I am using Arduino UNO, with the ArduinoJson 5.13.5, I followed the steps given by you, But i too am getting nothing on the Serial Monitor
    PS: Baud rate set to 9600

    • Hi shashidhara,
      Thanks for commenting. Please check that you have used the same baud rate for NodeMCU and Arduino. Then check the connections once more and make sure that the USB port is working properly. Or try using other USB ports. Thankyou

  • It is possible use arduino uno and nodemcu upload the sensor data on thingspeak? I don’t want use nodemcu only for upload the sensor data.
    Thank you.

    • Hi karipap,
      Thanks for commenting. In NodeMCU only 1 Analog pin is available. So if we want to use only 1 analog sensor we can go for NodeMCU. If we want more analog pins, ESP32 can be used.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.