NodeMCU communication with Arduino

Introduction

I2C (Inter-Integrated Circuit) is a serial bus interface connection protocol. It is also called as TWI (two-wire interface) since it uses only two wires for communication. Those two wires are SDA (serial data) and SCL (serial clock).
I2C is an acknowledgment based communication protocol i.e. transmitter checks for an acknowledgment from the receiver after transmitting data to know whether data is received by the receiver successfully.
I2Cworks in two modes namely,
  • Master mode
  • Slave mode
SDA (serial data) wire is used for data exchange in between master and slave devices. SCL (serial clock) is used for the synchronous clock in between master and slave devices.
The master device initiates communication with a slave device. The master device requires a slave device address to initiate the conversation with a slave device. The slave device responds to the master device when it is addressed by a master device.
NodeMCU has I2C functionality support on its GPIO pins. Due to internal functionality on ESP-12E, we cannot use all its GPIOs for I2C functionality. So, do tests before using any GPIO for I2C applications.

Example

Let’s write Arduino sketch for NodeMCU as I2C master device and Arduino sketch for Arduino Uno as I2C slave device. Master device sends hello string to slave device and slave device will send hello string in response to the master device.
Here, we are using
Master Device: NodeMCU
Slave Device: Arduino Uno
Slave Device Address: 8
Interfacing diagram is shown in the below figure

Arduino Sketch for NodeMCU (Master I2C Device)


Code: 

#include <Wire.h> void setup() { Serial. begin (9600); Wire. begin(D1, D2); } void loop() { Wire.beginTransmission (8); Wire.write("Hello Arduino"); Wire. endTransmission( ); Wire. requestFrom(8, 13); while(Wire.available()) { char c = Wire. read(); Serial.print(c); } Serial.println(); delay(1000); }



Arduino Sketch for Arduino Uno (Slave I2C Device)




Code: 

#include <Wire.h> void setup() { Wire.begin(8); Wire.onReceive(receiveEvent); Wire. onRequest(requestEvent); Serial.begin(9600); } void loop() { delay(100); } void receiveEvent(int howMany) { while (0 <Wire.available()) { char c = Wire. read(); /* receive byte as a character*/ Serial.print(c); /* print the character */ Serial.println(); /*to newline*/ } } // function that executes whenever data is requested from master void requestEvent() { Wire.write("Hello NodeMCU"); /*send string on request */ }


Comments