Electronic – arduino – How to read LM35 temperature values on nodemcu when sent by arduino by I2C communication

#nodemcuarduinoi2c

ARDUINO SEND CODE

#include <Wire.h>
const int lm35_pin=A1;
int temp_adc_val;
  float temp_val;

void setup() {
  Wire.begin(8);                // join i2c bus with address #8
  Wire.onRequest(requestEvent); // register request event
  Serial.begin(9600);           // start serial for debug
}

void loop() {
  temp_adc_val = analogRead(lm35_pin);  /* Temperature */
  temp_val = (temp_adc_val * 4.88); /* adc value to equivalent voltage */
  temp_val = (temp_val/10); /* LM35  */
  Serial.print("Temperature = ");
  Serial.print(temp_val);
  Serial.print(" Degree Celsius\n");
  delay(1000);
}

// function that executes whenever data is requested from master
void requestEvent() {
  byte* RPMFloatPtr;
  RPMFloatPtr = (byte*) &temp_val;
  Wire.write(RPMFloatPtr,5);  
}

NODEMCU RECEIVE CODE

#include <Wire.h>
float data;
void setup() {
  Serial.begin(9600); /* begin serial for debug */
  Wire.begin(D1, D2); /* join i2c bus with SDA=D1 and SCL=D2 of NodeMCU */
}

void loop() {
  tempdata();
}

void tempdata()
{
Wire.requestFrom(8, 5); /* request & read data of size 13 from slave */
while(Wire.available())    // slave may send less than requested
{ 
    data = Wire.read(); // receive a byte as character   
} 
Serial.print(data);
Serial.println();
delay(1000);
}

arduinoa

arduino

I have done interfacing of NodeMCU and Arduino Uno by I2C communication.
The Arduino is reading values from a temperature sensor and correctly displaying it on serial monitor.
Now I want the same values to be sent to the NodeMCU by I2C communication and want to read them on the serial monitor of the NodeMCU. However, i can't see the same temperature values. Instead, the values are some random analog values between 0 and 255.

Best Answer

You're not receiving the value as a float. In the Arduino code your reading directly from the ADC, getting an integer value and converting that to float based on the specs of your ADC. That float value is then being output as chars onto the serial connection. In your Node MCU code you have the variable data declared as a float when you are receiving chars. As you are reading from the arduino 1 byte/char at a time you also either need to buffer the incoming data or print char by char to the serial monitor like below:

void tempdata()
{
    Wire.requestFrom(8, 5); /* request & read data of size 13 from slave */
    while(Wire.available())    // slave may send less than requested
    { 
       data = Wire.read(); // receive a byte as character
       Serial.print(data);
    } 

    Serial.println();
    delay(1000);
}