I am trying to carry out an I2C communication between arduino and esp. In this case I want to send 6 messages from the slave to the master, but the communication is corrupted from the 5. What is happening? The messages consist of 8 characters where 7 are the message and the 8th use to indicate the end of it.
//Slave part
#include <Wire.h>
String m0_I2C;
String m1_I2C,m2_I2C,m3_I2C,m4_I2C,m5_I2C;
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() {
float m0=22.56;
float m1=80.0;
float m2=42.9;
float m3=200.58;
float m4=200.0;
float m5=70.0;
m0_I2C=floatToString_I2C(m0, 7, 2, true);
m1_I2C = floatToString_I2C(m1, 7, 2, true);
m2_I2C=floatToString_I2C(m2, 7, 2, true);
m3_I2C=floatToString_I2C(m3, 7, 2, true);
m4_I2C=floatToString_I2C(m4, 7, 2, true);
m5_I2C=floatToString_I2C(m5, 7, 2, true);
Serial.println (m0.c_str());
Serial.println (m1.c_str());
Serial.println (m2_I2C.c_str());
Serial.println (m3_I2C.c_str());
Serial.println (m4_I2C.c_str());
Serial.println (m5_I2C.c_str());
delay(2000);
}
// function that executes whenever data is requested from master
void requestEvent() {
Wire.write(m0_I2C.c_str());
Wire.write(m1_I2C.c_str());
Wire.write(m2_I2C.c_str());
Wire.write(m3_I2C.c_str());
Wire.write(m4_I2C.c_str());
Wire.write(m5_I2C.c_str());
}
String floatToString_I2C( float n, int l, int d, boolean z){
char c[l+1];
char s[6];
String f;
dtostrf(n,l,d,c);
f=String(c);
if(z){
f.replace(" ","0");
}
f.concat("/"); // 8th
return f;
}
//Master part
#include <Wire.h>
void setup() {
Serial.begin(9600); /* begin serial for debug */
Wire.begin(5, 4); /* join i2c bus with SDA=D1 and SCL=D2 of NodeMCU */
}
void loop() {
Wire.beginTransmission(8); /* begin with device address 8 */
Wire.write("Hello Arduino");
Wire.endTransmission();
Wire.requestFrom(8, 50); //
String m0 = "";
String m1 = "";
String m2 = "";
String m3 = "";
String m4 = "";
String m5 = "";
int i=0;
while (i<50){
i++;
char c=Wire.read();
Serial.println(c);
}
m0=comunicacion(8);
Serial.println(m0);
m1=comunicacion(8);
Serial.println(m1);
m2=comunicacion(8);
Serial.println(m2);
m3=comunicacion(8);
Serial.println(m3);
m4=comunicacion(8);
Serial.println(m4);
m5=comunicacion(8);
Serial.println(m5);
delay(1000);
}
String comunicacion(int tamano){
char punto='/';
int i=0;
String variable ="";
while(i<tamano){
i++;
char c=Wire.read();
Serial.print(c);
if (c != punto){
variable.concat(c);
}
}
return variable;
}