Dear all,
I would like to make communicate two arduinos using I2C.
The master triggers an update from the slave and receive the answer, a string of characters variable in length.
Please find below the code I wrote. It does not work, I think that I did some mistakes with the string sent and the conversion, since the output displayed by the master in the serial monitor is not readable.
I would also like to know if the logic is correct or, for my case, there is a better way to code this.
Furthermore I don't understand what are the implication of using the quantity number in the Wire.requestFrom(slave, 15); (Master), what happens if the Slave replies with a shorter message other than 15?
Thank you for your support,
dk
NOTE: I still not defied the format of the string sent back by the slave but it could be something like values separated by comma with a starting and terminating char such as: "!10,21,5,100?". The string will be then parsed by the Master to extract numbers 10, 21, 5, and 100. Is there a better way to do this?
// MASTER
#include <Wire.h>
void setup()
{
Wire.begin();
Serial.begin(9600);
Serial.println("Start");
}
void loop()
{
// [...]
// Request data from slave #2
Serial.println(requestValues(2));
delay(10000);
}
String requestValues(int slave){
String sValues;
int i = 0;
// Request value from slave
Wire.requestFrom(slave, 15);
while(0 < Wire.available())
{
sValues[i] = Wire.read();
i++;
}
sValues[i] = '\0';
return sValues;
}
// SLAVE
#include <Wire.h>
int led = 13;
void setup()
{
pinMode(led, OUTPUT);
Wire.begin(2);
Wire.onRequest(requestEvent);
ledStatus(1000);
}
void loop()
{
//do something
delay(100);
}
void requestEvent()
{
String sSensor = "Text value: " + sensorRead(1); // size of this string can vary from 10 up to 15
char buffer[20];
sSensor.toCharArray(buffer, 20);
Wire.write(buffer);
}
int sensorRead(int index){
int sensor;
sensor = 20;
// [...]
sensor = sensor + index;
ledStatus(500);
return sensor;
}
void ledStatus(int t){
digitalWrite(led, HIGH);
delay(t);
digitalWrite(led, LOW);
delay(t);
}