Hello Arduino Community!
Here I go with my first post and my first question. I’m trying to monitor sensors from my smartphone. My project is nearly finished, but I’m stuck at a point where I try to send some data collected from my Arduino to an ESP by I2C connection.
The ESP requires an answer, and when the answer is simple as in the following code, everything goes fine:
char response[14] = "12.23;5.32;4.5";
Another way of doing it and that works :
String response2 = "HEllo World";
response2.toCharArray(response, 14);
Wire.write(response);
However, my project requires converting float data into one char array as shown on the following code part "espWifiRequestEvent":
#include <Wire.h>
#include <string.h>
#define I2CAddressESPWifi 8
//char response[11] ="0123456789";
//int response = 89;
char response[14];
String phrase;
void setup()
{
Serial.begin(115200);
Wire.begin(I2CAddressESPWifi);
Wire.onReceive(espWifiReceiveEvent);
Wire.onRequest(espWifiRequestEvent);
}
void loop()
{
delay(1);
}
void espWifiReceiveEvent(int count)
{
Serial.print("Received[");
while (Wire.available())
{
char c = Wire.read();
Serial.print(c);
}
Serial.println("]");
//calc response.
}
void espWifiRequestEvent()
{
float temp = 23.5789643;
float hum = 58.956113138;
char tempChar[6];
char humChar[6];
dtostrf(temp,5,2,tempChar);
dtostrf(hum,5,2,humChar);
strcat(response, tempChar);
strcat(response, ";");
strcat(response, humChar);
Wire.write(response);
memset(response, '\0', 14);
delay (200);
}
*The float temperature and humidity values are fixed. It's just to debug my code.
I’m pretty sure I made a mistake somewhere, but I can’t find the answer… I hope you could help me with that!
Hereafter the Master ESP code:
#include <Wire.h>
#define I2CAddressESPWifi 8
int x=32;
void setup()
{
Serial.begin(115200);
Wire.begin(0,2);//Change to Wire.begin() for non ESP.
}
void loop()
{
Wire.beginTransmission(I2CAddressESPWifi);
Wire.write(x);
Wire.endTransmission();
x++;
delay(1);//Wait for Slave to calculate response.
Wire.requestFrom(I2CAddressESPWifi,14);
Serial.print("Request Return:[");
while (Wire.available())
{
delay(1);
char c = Wire.read();
Serial.print(c);
}
Serial.println("]");
delay(2000);
}
Tell me if you need more information!