I have improved the code, but still have not fixed every problem. I am trying to copy a code from JHaskell's blog. I will aslo send the sender code.
// Wire Master Reader
// by Nicholas Zambetti <http://www.zambetti.com>
// Demonstrates use of the Wire library
// Reads data from an I2C/TWI slave device
// Refer to the "Wire Slave Sender" example for use with this
// Created 29 March 2006
// This example code is in the public domain.
// Written by Nick Gammon
// May 2012
#include <Wire.h>
#define DATABUFFERSIZE 6
char dataBuffer[DATABUFFERSIZE + 1]; //Add 1 for NULL terminator
byte dataBufferIndex = 0;
char startChar = '%'; // or '!', or whatever your start character is
char endChar = '&';
void setup() {
Wire.begin(); // join i2c bus (address optional for master)
Serial.begin(9600); // start serial for output
}
void loop() {
Wire.requestFrom(8, 6);
char startChar = '%'; // or '!', or whatever your start character is
char endChar = '&';
if (getSerialString()) {
//String available for parsing. Parse it here
boolean getSerialString() {
static byte dataBufferIndex = 0;
while (Wire.available() > 0) {
char incomingbyte = Wire.read();
if (incomingbyte == startChar) {
dataBufferIndex = 0; //Initialize our dataBufferIndex variable
storeString = true;
}
if (storeString) {
//Let's check our index here, and abort if we're outside our buffer size
//We use our define here so our buffer size can be easily modified
if (dataBufferIndex == DATABUFFERSIZE) {
//Oops, our index is pointing to an array element outside our buffer.
dataBufferIndex = 0;
break;
}
if (incomingbyte == endChar) {
dataBuffer[dataBufferIndex] = 0; //null terminate the C string
//Our data string is complete. return true
return true;
}
else {
dataBuffer[dataBufferIndex++] = incomingbyte;
dataBuffer[dataBufferIndex] = 0; //null terminate the C string
}
}
else {
}
}
//We've read in all the available Serial data, and don't have a valid string yet, so return false
return false;
}
}
boolean storeString = false; //This will be our flag to put the data in our buffer
while (Wire.available() > 0) {
char incomingbyte = Wire.read();
if (incomingbyte == startChar) {
dataBufferIndex = 0; //Initialize our dataBufferIndex variable
storeString = true;
}
if (storeString) {
//Let's check our index here, and abort if we're outside our buffer size
//We use our define here so our buffer size can be easily modified
if (dataBufferIndex == DATABUFFERSIZE) {
//Oops, our index is pointing to an array element outside our buffer.
dataBufferIndex = 0;
break;
}
if (incomingbyte == endChar) {
//Our data string is complete. Parse it here
storeString = false;
}
else {
dataBuffer[dataBufferIndex++] = incomingbyte;
dataBuffer[dataBufferIndex] = 0; //null terminate the C string
}
}
}
Serial.print(c);
}
Serial.println(" ");
delay(500);