NodeMCU - Master and UNO - Slaves (I2C communication)

  1. Yes I can see the changes in the voltage as Pot1 is rotated

  2. Code as follows

Master-Node


// Include the required Wire library for I2C
#include "Wire.h"

int LED = 11;

int x = 0;

void setup() {

// Define the LED pin as Output

pinMode (LED, OUTPUT);

// Start the I2C Bus as Slave on address 9

Wire.begin(9);

// Attach a function to trigger when something is received.

Wire.onReceive(receiveEvent);

//bit rate for data transfer over Serial communication

Serial.begin(9600);

}

void receiveEvent(int bytes) {

x = Wire.read(); // read one character from the I2C

}

void loop() {

//potentiometer value from sensor

int ledPWM = map(x, 0, 255, 0, 1023);

analogWrite(LED, ledPWM);

Serial.print("X is: ");

Serial.println(x);

Serial.print("PWM is: ");

Serial.println(ledPWM);

delay(1000);

}

Slave - UNO


#include "Wire.h"

int x = 0;

int sensorPin = A0;

int sensorValue = 0;

void setup() {



Wire.begin();

Serial.begin(9600);

}

void loop() {

sensorValue = analogRead(sensorPin);

Serial.println(sensorValue);

Wire.beginTransmission(9);

// transmit to device #9

Wire.write(sensorValue);

delay(1000);

Wire.endTransmission();

// stop transmitting

}

Output Serial Monitor at Master

12:59:48.569 -> 0
0
12:59:49.553 -> 0
12:59:50.581 -> 0
12:59:51.556 -> 0
12:59:52.587 -> 0
12:59:53.571 -> 0
12:59:54.556 -> 0
12:59:55.559 -> 0
12:59:56.543 -> 38
12:59:57.575 -> 0
12:59:58.569 -> 256
12:59:59.553 -> 385
13:00:00.564 -> 623
13:00:01.544 -> 1010
13:00:02.575 -> 1023
13:00:03.551 -> 1023
13:00:04.536 -> 1023
13:00:05.565 -> 1023
13:00:06.538 -> 1023
13:00:07.561 -> 1023
13:00:08.543 -> 1023
13:00:09.572 -> 1023


  1. I will be basically connecting 3 i2c sensors and an analog sensor for each slave-uno as follows

BMP280 (I2C)
SCD30 (I2C)
INA219 (I2C)
MQ-8 (Analog)